blob: 90cf5ee65dff8942f82d1f305ec6f9a6dbe9e995 [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;
Reid Klecknerd7857f02014-10-24 17:42:17 +000050 // TODO: Add support for __pascal to LLVM.
51 case CC_X86Pascal: return llvm::CallingConv::C;
52 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000053 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000054 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
55 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
John McCallab26cfa2010-02-05 21:31:56 +000056 }
57}
58
John McCall8ee376f2010-02-24 07:14:12 +000059/// Derives the 'this' type for codegen purposes, i.e. ignoring method
60/// qualification.
61/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000062static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
63 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
64 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000065}
66
John McCall8ee376f2010-02-24 07:14:12 +000067/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000068static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
69 return MD->getType()->getCanonicalTypeUnqualified()
70 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000071}
72
73/// Returns the "extra-canonicalized" return type, which discards
74/// qualifiers on the return type. Codegen doesn't care about them,
75/// and it makes ABI code a little easier to be able to assume that
76/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000077static CanQualType GetReturnType(QualType RetTy) {
78 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000079}
80
John McCall8dda7b22012-07-07 06:41:13 +000081/// Arrange the argument and result information for a value of the given
82/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000083const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000084CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000085 // When translating an unprototyped function type, always use a
86 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000087 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000088 /*instanceMethod=*/false,
89 /*chainCall=*/false, None,
90 FTNP->getExtInfo(), RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +000091}
92
John McCall8dda7b22012-07-07 06:41:13 +000093/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000094/// type, on top of any implicit parameters already stored.
95static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +000096arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +000097 SmallVectorImpl<CanQualType> &prefix,
98 CanQual<FunctionProtoType> FTP) {
John McCall8dda7b22012-07-07 06:41:13 +000099 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000100 // FIXME: Kill copy.
Alp Toker9cacbab2014-01-20 20:26:09 +0000101 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
102 prefix.push_back(FTP->getParamType(i));
Alp Toker314cc812014-01-25 16:55:45 +0000103 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
Peter Collingbournef7706832014-12-12 23:41:25 +0000104 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
105 /*chainCall=*/false, prefix,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000106 FTP->getExtInfo(), required);
John McCall8ee376f2010-02-24 07:14:12 +0000107}
108
John McCalla729c622012-02-17 03:33:10 +0000109/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000110/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000111const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000112CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCalla729c622012-02-17 03:33:10 +0000113 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000114 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
115 FTP);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000116}
117
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000118static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000119 // Set the appropriate calling convention for the Function.
120 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000121 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000122
123 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000124 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000125
Douglas Gregora941dca2010-05-18 16:57:00 +0000126 if (D->hasAttr<ThisCallAttr>())
127 return CC_X86ThisCall;
128
Reid Klecknerd7857f02014-10-24 17:42:17 +0000129 if (D->hasAttr<VectorCallAttr>())
130 return CC_X86VectorCall;
131
Dawn Perchik335e16b2010-09-03 01:29:35 +0000132 if (D->hasAttr<PascalAttr>())
133 return CC_X86Pascal;
134
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000135 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
136 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
137
Guy Benyeif0a014b2012-12-25 08:53:55 +0000138 if (D->hasAttr<IntelOclBiccAttr>())
139 return CC_IntelOclBicc;
140
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000141 if (D->hasAttr<MSABIAttr>())
142 return IsWindows ? CC_C : CC_X86_64Win64;
143
144 if (D->hasAttr<SysVABIAttr>())
145 return IsWindows ? CC_X86_64SysV : CC_C;
146
John McCallab26cfa2010-02-05 21:31:56 +0000147 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000148}
149
John McCalla729c622012-02-17 03:33:10 +0000150/// Arrange the argument and result information for a call to an
151/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000152/// (Zero value of RD means we don't have any meaningful "this" argument type,
153/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000154/// The member function must be an ordinary function, i.e. not a
155/// constructor or destructor.
156const CGFunctionInfo &
157CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
158 const FunctionProtoType *FTP) {
159 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000160
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000161 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000162 if (RD)
163 argTypes.push_back(GetThisType(Context, RD));
164 else
165 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000166
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000167 return ::arrangeLLVMFunctionInfo(
168 *this, true, argTypes,
169 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000170}
171
John McCalla729c622012-02-17 03:33:10 +0000172/// Arrange the argument and result information for a declaration or
173/// definition of the given C++ non-static member function. The
174/// member function must be an ordinary function, i.e. not a
175/// constructor or destructor.
176const CGFunctionInfo &
177CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000178 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000179 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
180
John McCalla729c622012-02-17 03:33:10 +0000181 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000182
John McCalla729c622012-02-17 03:33:10 +0000183 if (MD->isInstance()) {
184 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000185 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000186 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCalla729c622012-02-17 03:33:10 +0000187 }
188
John McCall8dda7b22012-07-07 06:41:13 +0000189 return arrangeFreeFunctionType(prototype);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000190}
191
John McCalla729c622012-02-17 03:33:10 +0000192const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000193CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
194 StructorType Type) {
195
John McCalla729c622012-02-17 03:33:10 +0000196 SmallVector<CanQualType, 16> argTypes;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000197 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000198
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000199 GlobalDecl GD;
200 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
201 GD = GlobalDecl(CD, toCXXCtorType(Type));
202 } else {
203 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
204 GD = GlobalDecl(DD, toCXXDtorType(Type));
205 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000206
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000207 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000208
209 // Add the formal parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000210 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
211 argTypes.push_back(FTP->getParamType(i));
John McCall5d865c322010-08-31 07:33:07 +0000212
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000213 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
Reid Kleckner89077a12013-12-17 19:46:40 +0000214
215 RequiredArgs required =
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000216 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000217
John McCall8dda7b22012-07-07 06:41:13 +0000218 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000219 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
220 ? argTypes.front()
221 : TheCXXABI.hasMostDerivedReturn(GD)
222 ? CGM.getContext().VoidPtrTy
223 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
225 /*chainCall=*/false, argTypes, extInfo,
226 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;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000237 for (const auto &Arg : args)
238 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000239
240 CanQual<FunctionProtoType> FPT = GetFormalType(D);
241 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
242 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000243 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
244 ? ArgTypes.front()
245 : TheCXXABI.hasMostDerivedReturn(GD)
246 ? CGM.getContext().VoidPtrTy
247 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000248
249 FunctionType::ExtInfo Info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000250 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
251 /*chainCall=*/false, ArgTypes, Info,
252 Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000253}
254
John McCalla729c622012-02-17 03:33:10 +0000255/// Arrange the argument and result information for the declaration or
256/// definition of the given function.
257const CGFunctionInfo &
258CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000259 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000260 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000261 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000262
John McCall2da83a32010-02-26 00:48:12 +0000263 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000264
John McCall2da83a32010-02-26 00:48:12 +0000265 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000266
267 // When declaring a function without a prototype, always use a
268 // non-variadic type.
269 if (isa<FunctionNoProtoType>(FTy)) {
270 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Peter Collingbournef7706832014-12-12 23:41:25 +0000271 return arrangeLLVMFunctionInfo(
272 noProto->getReturnType(), /*instanceMethod=*/false,
273 /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000274 }
275
John McCall2da83a32010-02-26 00:48:12 +0000276 assert(isa<FunctionProtoType>(FTy));
John McCall8dda7b22012-07-07 06:41:13 +0000277 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000278}
279
John McCalla729c622012-02-17 03:33:10 +0000280/// Arrange the argument and result information for the declaration or
281/// definition of an Objective-C method.
282const CGFunctionInfo &
283CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
284 // It happens that this is the same as a call with no optional
285 // arguments, except also using the formal 'self' type.
286 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
287}
288
289/// Arrange the argument and result information for the function type
290/// through which to perform a send to the given Objective-C method,
291/// using the given receiver type. The receiver type is not always
292/// the 'self' type of the method or even an Objective-C pointer type.
293/// This is *not* the right method for actually performing such a
294/// message send, due to the possibility of optional arguments.
295const CGFunctionInfo &
296CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
297 QualType receiverType) {
298 SmallVector<CanQualType, 16> argTys;
299 argTys.push_back(Context.getCanonicalParamType(receiverType));
300 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000301 // FIXME: Kill copy?
Aaron Ballman43b68be2014-03-07 17:50:17 +0000302 for (const auto *I : MD->params()) {
303 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000304 }
John McCall31168b02011-06-15 23:02:42 +0000305
306 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000307 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
308 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000309
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000311 MD->hasAttr<NSReturnsRetainedAttr>())
312 einfo = einfo.withProducesResult(true);
313
John McCalla729c622012-02-17 03:33:10 +0000314 RequiredArgs required =
315 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
316
Peter Collingbournef7706832014-12-12 23:41:25 +0000317 return arrangeLLVMFunctionInfo(
318 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
319 /*chainCall=*/false, argTys, einfo, required);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000320}
321
John McCalla729c622012-02-17 03:33:10 +0000322const CGFunctionInfo &
323CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000324 // FIXME: Do we need to handle ObjCMethodDecl?
325 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000326
Anders Carlsson6710c532010-02-06 02:44:09 +0000327 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000328 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000329
330 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000331 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000332
John McCalla729c622012-02-17 03:33:10 +0000333 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000334}
335
Reid Klecknerc3473512014-08-29 21:43:29 +0000336/// Arrange a thunk that takes 'this' as the first parameter followed by
337/// varargs. Return a void pointer, regardless of the actual return type.
338/// The body of the thunk will end in a musttail call to a function of the
339/// correct type, and the caller will bitcast the function to the correct
340/// prototype.
341const CGFunctionInfo &
342CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
343 assert(MD->isVirtual() && "only virtual memptrs have thunks");
344 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
345 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000346 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
347 /*chainCall=*/false, ArgTys,
Reid Klecknerc3473512014-08-29 21:43:29 +0000348 FTP->getExtInfo(), RequiredArgs(1));
349}
350
John McCallc818bbb2012-12-07 07:03:17 +0000351/// Arrange a call as unto a free function, except possibly with an
352/// additional number of formal parameters considered required.
353static const CGFunctionInfo &
354arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000355 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000356 const CallArgList &args,
357 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000358 unsigned numExtraRequiredArgs,
359 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000360 assert(args.size() >= numExtraRequiredArgs);
361
362 // In most cases, there are no optional arguments.
363 RequiredArgs required = RequiredArgs::All;
364
365 // If we have a variadic prototype, the required arguments are the
366 // extra prefix plus the arguments in the prototype.
367 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
368 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000369 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000370
371 // If we don't have a prototype at all, but we're supposed to
372 // explicitly use the variadic convention for unprototyped calls,
373 // treat all of the arguments as required but preserve the nominal
374 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000375 } else if (CGM.getTargetCodeGenInfo()
376 .isNoProtoCallVariadic(args,
377 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000378 required = RequiredArgs(args.size());
379 }
380
Peter Collingbournef7706832014-12-12 23:41:25 +0000381 // FIXME: Kill copy.
382 SmallVector<CanQualType, 16> argTypes;
383 for (const auto &arg : args)
384 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
385 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
386 /*instanceMethod=*/false, chainCall,
387 argTypes, fnType->getExtInfo(), required);
John McCallc818bbb2012-12-07 07:03:17 +0000388}
389
John McCalla729c622012-02-17 03:33:10 +0000390/// Figure out the rules for calling a function with the given formal
391/// type using the given arguments. The arguments are necessary
392/// because the function might be unprototyped, in which case it's
393/// target-dependent in crazy ways.
394const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000395CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000396 const FunctionType *fnType,
397 bool chainCall) {
398 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
399 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000400}
John McCalla729c622012-02-17 03:33:10 +0000401
John McCallc818bbb2012-12-07 07:03:17 +0000402/// A block function call is essentially a free-function call with an
403/// extra implicit argument.
404const CGFunctionInfo &
405CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
406 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000407 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
408 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000409}
410
411const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000412CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
413 const CallArgList &args,
414 FunctionType::ExtInfo info,
415 RequiredArgs required) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000416 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000417 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000418 for (const auto &Arg : args)
419 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000420 return arrangeLLVMFunctionInfo(
421 GetReturnType(resultType), /*instanceMethod=*/false,
422 /*chainCall=*/false, argTypes, info, required);
John McCall8dda7b22012-07-07 06:41:13 +0000423}
424
425/// Arrange a call to a C++ method, passing the given arguments.
426const CGFunctionInfo &
427CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
428 const FunctionProtoType *FPT,
429 RequiredArgs required) {
430 // FIXME: Kill copy.
431 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000432 for (const auto &Arg : args)
433 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
John McCall8dda7b22012-07-07 06:41:13 +0000434
435 FunctionType::ExtInfo info = FPT->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000436 return arrangeLLVMFunctionInfo(
437 GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
438 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbar3cd20632009-01-31 02:19:00 +0000439}
440
Reid Kleckner4982b822014-01-31 22:54:50 +0000441const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
442 QualType resultType, const FunctionArgList &args,
443 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000444 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000445 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000446 for (auto Arg : args)
447 argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
John McCalla729c622012-02-17 03:33:10 +0000448
449 RequiredArgs required =
450 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Peter Collingbournef7706832014-12-12 23:41:25 +0000451 return arrangeLLVMFunctionInfo(
452 GetReturnType(resultType), /*instanceMethod=*/false,
453 /*chainCall=*/false, argTypes, info, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000454}
455
John McCalla729c622012-02-17 03:33:10 +0000456const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000457 return arrangeLLVMFunctionInfo(
458 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
459 None, FunctionType::ExtInfo(), RequiredArgs::All);
John McCalla738c252011-03-09 04:27:21 +0000460}
461
John McCalla729c622012-02-17 03:33:10 +0000462/// Arrange the argument and result information for an abstract value
463/// of a given function type. This is the method which all of the
464/// above functions ultimately defer to.
465const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000466CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000467 bool instanceMethod,
468 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000469 ArrayRef<CanQualType> argTypes,
470 FunctionType::ExtInfo info,
471 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000472 assert(std::all_of(argTypes.begin(), argTypes.end(),
473 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000474
John McCalla729c622012-02-17 03:33:10 +0000475 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCallab26cfa2010-02-05 21:31:56 +0000476
Daniel Dunbare0be8292009-02-03 00:07:12 +0000477 // Lookup or create unique function info.
478 llvm::FoldingSetNodeID ID;
Peter Collingbournef7706832014-12-12 23:41:25 +0000479 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
480 resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000481
Craig Topper8a13c412014-05-21 05:09:00 +0000482 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000483 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000484 if (FI)
485 return *FI;
486
John McCalla729c622012-02-17 03:33:10 +0000487 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000488 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
489 resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000490 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000491
David Blaikie82e95a32014-11-19 07:49:47 +0000492 bool inserted = FunctionsBeingProcessed.insert(FI).second;
493 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000494 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000495
Daniel Dunbar313321e2009-02-03 05:31:23 +0000496 // Compute ABI information.
Chris Lattner22326a12010-07-29 02:31:05 +0000497 getABIInfo().computeInfo(*FI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000498
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000499 // Loop over all of the computed argument and return value info. If any of
500 // them are direct or extend without a specified coerce type, specify the
501 // default now.
John McCalla729c622012-02-17 03:33:10 +0000502 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000503 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000504 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000505
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000506 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000507 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000508 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000509
John McCalla729c622012-02-17 03:33:10 +0000510 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
511 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000512
Daniel Dunbare0be8292009-02-03 00:07:12 +0000513 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000514}
515
John McCalla729c622012-02-17 03:33:10 +0000516CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000517 bool instanceMethod,
518 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000519 const FunctionType::ExtInfo &info,
520 CanQualType resultType,
521 ArrayRef<CanQualType> argTypes,
522 RequiredArgs required) {
523 void *buffer = operator new(sizeof(CGFunctionInfo) +
524 sizeof(ArgInfo) * (argTypes.size() + 1));
525 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
526 FI->CallingConvention = llvmCC;
527 FI->EffectiveCallingConvention = llvmCC;
528 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000529 FI->InstanceMethod = instanceMethod;
530 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000531 FI->NoReturn = info.getNoReturn();
532 FI->ReturnsRetained = info.getProducesResult();
533 FI->Required = required;
534 FI->HasRegParm = info.getHasRegParm();
535 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000536 FI->ArgStruct = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000537 FI->NumArgs = argTypes.size();
538 FI->getArgsBuffer()[0].type = resultType;
539 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
540 FI->getArgsBuffer()[i + 1].type = argTypes[i];
541 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000542}
543
544/***/
545
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000546namespace {
547// ABIArgInfo::Expand implementation.
548
549// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
550struct TypeExpansion {
551 enum TypeExpansionKind {
552 // Elements of constant arrays are expanded recursively.
553 TEK_ConstantArray,
554 // Record fields are expanded recursively (but if record is a union, only
555 // the field with the largest size is expanded).
556 TEK_Record,
557 // For complex types, real and imaginary parts are expanded recursively.
558 TEK_Complex,
559 // All other types are not expandable.
560 TEK_None
561 };
562
563 const TypeExpansionKind Kind;
564
565 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
566 virtual ~TypeExpansion() {}
567};
568
569struct ConstantArrayExpansion : TypeExpansion {
570 QualType EltTy;
571 uint64_t NumElts;
572
573 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
574 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
575 static bool classof(const TypeExpansion *TE) {
576 return TE->Kind == TEK_ConstantArray;
577 }
578};
579
580struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000581 SmallVector<const CXXBaseSpecifier *, 1> Bases;
582
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000583 SmallVector<const FieldDecl *, 1> Fields;
584
Reid Klecknere9f6a712014-10-31 17:10:41 +0000585 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
586 SmallVector<const FieldDecl *, 1> &&Fields)
587 : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000588 static bool classof(const TypeExpansion *TE) {
589 return TE->Kind == TEK_Record;
590 }
591};
592
593struct ComplexExpansion : TypeExpansion {
594 QualType EltTy;
595
596 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
597 static bool classof(const TypeExpansion *TE) {
598 return TE->Kind == TEK_Complex;
599 }
600};
601
602struct NoExpansion : TypeExpansion {
603 NoExpansion() : TypeExpansion(TEK_None) {}
604 static bool classof(const TypeExpansion *TE) {
605 return TE->Kind == TEK_None;
606 }
607};
608} // namespace
609
610static std::unique_ptr<TypeExpansion>
611getTypeExpansion(QualType Ty, const ASTContext &Context) {
612 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
613 return llvm::make_unique<ConstantArrayExpansion>(
614 AT->getElementType(), AT->getSize().getZExtValue());
615 }
616 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000617 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000618 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000619 const RecordDecl *RD = RT->getDecl();
620 assert(!RD->hasFlexibleArrayMember() &&
621 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000622 if (RD->isUnion()) {
623 // Unions can be here only in degenerative cases - all the fields are same
624 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000625 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000626 CharUnits UnionSize = CharUnits::Zero();
627
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000628 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000629 // Skip zero length bitfields.
630 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
631 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000632 assert(!FD->isBitField() &&
633 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000634 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000635 if (UnionSize < FieldSize) {
636 UnionSize = FieldSize;
637 LargestFD = FD;
638 }
639 }
640 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000641 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000642 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000643 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
644 assert(!CXXRD->isDynamicClass() &&
645 "cannot expand vtable pointers in dynamic classes");
646 for (const CXXBaseSpecifier &BS : CXXRD->bases())
647 Bases.push_back(&BS);
648 }
649
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000650 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000651 // Skip zero length bitfields.
652 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
653 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000654 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000655 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000656 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000657 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000658 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000659 return llvm::make_unique<RecordExpansion>(std::move(Bases),
660 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000661 }
662 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
663 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
664 }
665 return llvm::make_unique<NoExpansion>();
666}
667
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000668static int getExpansionSize(QualType Ty, const ASTContext &Context) {
669 auto Exp = getTypeExpansion(Ty, Context);
670 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
671 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
672 }
673 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
674 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000675 for (auto BS : RExp->Bases)
676 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000677 for (auto FD : RExp->Fields)
678 Res += getExpansionSize(FD->getType(), Context);
679 return Res;
680 }
681 if (isa<ComplexExpansion>(Exp.get()))
682 return 2;
683 assert(isa<NoExpansion>(Exp.get()));
684 return 1;
685}
686
Alexey Samsonov153004f2014-09-29 22:08:00 +0000687void
688CodeGenTypes::getExpandedTypes(QualType Ty,
689 SmallVectorImpl<llvm::Type *>::iterator &TI) {
690 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000691 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
692 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000693 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000694 }
695 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000696 for (auto BS : RExp->Bases)
697 getExpandedTypes(BS->getType(), TI);
698 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000699 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000700 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
701 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000702 *TI++ = EltTy;
703 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000704 } else {
705 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000706 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000707 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000708}
709
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000710void CodeGenFunction::ExpandTypeFromArgs(
711 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000712 assert(LV.isSimple() &&
713 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000714
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000715 auto Exp = getTypeExpansion(Ty, getContext());
716 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
717 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
718 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, i);
719 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
720 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000721 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000722 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000723 llvm::Value *This = LV.getAddress();
724 for (const CXXBaseSpecifier *BS : RExp->Bases) {
725 // Perform a single step derived-to-base conversion.
726 llvm::Value *Base =
727 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
728 /*NullCheckValue=*/false, SourceLocation());
729 LValue SubLV = MakeAddrLValue(Base, BS->getType());
730
731 // Recurse onto bases.
732 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
733 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000734 for (auto FD : RExp->Fields) {
735 // FIXME: What are the right qualifiers here?
736 LValue SubLV = EmitLValueForField(LV, FD);
737 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000738 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000739 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000740 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000741 EmitStoreThroughLValue(RValue::get(*AI++),
742 MakeAddrLValue(RealAddr, CExp->EltTy));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000743 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000744 EmitStoreThroughLValue(RValue::get(*AI++),
745 MakeAddrLValue(ImagAddr, CExp->EltTy));
746 } else {
747 assert(isa<NoExpansion>(Exp.get()));
748 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000749 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000750}
751
752void CodeGenFunction::ExpandTypeToArgs(
753 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
754 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
755 auto Exp = getTypeExpansion(Ty, getContext());
756 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
757 llvm::Value *Addr = RV.getAggregateAddr();
758 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
759 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, i);
760 RValue EltRV =
761 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
762 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
763 }
764 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000765 llvm::Value *This = RV.getAggregateAddr();
766 for (const CXXBaseSpecifier *BS : RExp->Bases) {
767 // Perform a single step derived-to-base conversion.
768 llvm::Value *Base =
769 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
770 /*NullCheckValue=*/false, SourceLocation());
771 RValue BaseRV = RValue::getAggregate(Base);
772
773 // Recurse onto bases.
774 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
775 IRCallArgPos);
776 }
777
778 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000779 for (auto FD : RExp->Fields) {
780 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
781 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
782 IRCallArgPos);
783 }
784 } else if (isa<ComplexExpansion>(Exp.get())) {
785 ComplexPairTy CV = RV.getComplexVal();
786 IRCallArgs[IRCallArgPos++] = CV.first;
787 IRCallArgs[IRCallArgPos++] = CV.second;
788 } else {
789 assert(isa<NoExpansion>(Exp.get()));
790 assert(RV.isScalar() &&
791 "Unexpected non-scalar rvalue during struct expansion.");
792
793 // Insert a bitcast as needed.
794 llvm::Value *V = RV.getScalarVal();
795 if (IRCallArgPos < IRFuncTy->getNumParams() &&
796 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
797 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
798
799 IRCallArgs[IRCallArgPos++] = V;
800 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000801}
802
Chris Lattner895c52b2010-06-27 06:04:18 +0000803/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +0000804/// accessing some number of bytes out of it, try to gep into the struct to get
805/// at its inner goodness. Dive as deep as possible without entering an element
806/// with an in-memory size smaller than DstSize.
807static llvm::Value *
Chris Lattner895c52b2010-06-27 06:04:18 +0000808EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000809 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +0000810 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +0000811 // We can't dive into a zero-element struct.
812 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000813
Chris Lattner2192fe52011-07-18 04:24:23 +0000814 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000815
Chris Lattner1cd66982010-06-27 05:56:15 +0000816 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +0000817 // first element is the same size as the whole struct, we can enter it. The
818 // comparison must be made on the store size and not the alloca size. Using
819 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000820 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +0000821 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000822 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +0000823 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +0000824 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000825
Chris Lattner1cd66982010-06-27 05:56:15 +0000826 // GEP into the first element.
827 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000828
Chris Lattner1cd66982010-06-27 05:56:15 +0000829 // If the first element is a struct, recurse.
Chris Lattner2192fe52011-07-18 04:24:23 +0000830 llvm::Type *SrcTy =
Chris Lattner1cd66982010-06-27 05:56:15 +0000831 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +0000833 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000834
835 return SrcPtr;
836}
837
Chris Lattner055097f2010-06-27 06:26:04 +0000838/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
839/// are either integers or pointers. This does a truncation of the value if it
840/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000841///
842/// This behaves as if the value were coerced through memory, so on big-endian
843/// targets the high bits are preserved in a truncation, while little-endian
844/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +0000845static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +0000846 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +0000847 CodeGenFunction &CGF) {
848 if (Val->getType() == Ty)
849 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000850
Chris Lattner055097f2010-06-27 06:26:04 +0000851 if (isa<llvm::PointerType>(Val->getType())) {
852 // If this is Pointer->Pointer avoid conversion to and from int.
853 if (isa<llvm::PointerType>(Ty))
854 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000855
Chris Lattner055097f2010-06-27 06:26:04 +0000856 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +0000857 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +0000858 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000859
Chris Lattner2192fe52011-07-18 04:24:23 +0000860 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +0000861 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +0000862 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000863
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000864 if (Val->getType() != DestIntTy) {
865 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
866 if (DL.isBigEndian()) {
867 // Preserve the high bits on big-endian targets.
868 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +0000869 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
870 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
871
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +0000872 if (SrcSize > DstSize) {
873 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
874 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
875 } else {
876 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
877 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
878 }
879 } else {
880 // Little-endian targets preserve the low bits. No shifts required.
881 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
882 }
883 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000884
Chris Lattner055097f2010-06-27 06:26:04 +0000885 if (isa<llvm::PointerType>(Ty))
886 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
887 return Val;
888}
889
Chris Lattner1cd66982010-06-27 05:56:15 +0000890
891
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000892/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
893/// a pointer to an object of type \arg Ty.
894///
895/// This safely handles the case when the src type is smaller than the
896/// destination type; in this situation the values of bits which not
897/// present in the src are undefined.
898static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +0000899 llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000900 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000901 llvm::Type *SrcTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000902 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000903
Chris Lattnerd200eda2010-06-28 22:51:39 +0000904 // If SrcTy and Ty are the same, just do a load.
905 if (SrcTy == Ty)
906 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000907
Micah Villmowdd31ca12012-10-08 16:25:52 +0000908 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000909
Chris Lattner2192fe52011-07-18 04:24:23 +0000910 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000911 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +0000912 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
913 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000914
Micah Villmowdd31ca12012-10-08 16:25:52 +0000915 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000916
Chris Lattner055097f2010-06-27 06:26:04 +0000917 // If the source and destination are integer or pointer types, just do an
918 // extension or truncation to the desired type.
919 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
920 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
921 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
922 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
923 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000924
Daniel Dunbarb52d0772009-02-03 05:59:18 +0000925 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000926 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +0000927 // Generally SrcSize is never greater than DstSize, since this means we are
928 // losing bits. However, this can happen in cases where the structure has
929 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +0000930 //
Mike Stump18bb9282009-05-16 07:57:57 +0000931 // FIXME: Assert that we aren't truncating non-padding bits when have access
932 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000933 llvm::Value *Casted =
934 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +0000935 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
936 // FIXME: Use better alignment / avoid requiring aligned load.
937 Load->setAlignment(1);
938 return Load;
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000939 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000940
Chris Lattner3fcc7902010-06-27 01:06:27 +0000941 // Otherwise do coercion through memory. This is stupid, but
942 // simple.
943 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Ren84b921f2012-11-28 22:08:52 +0000944 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
945 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
946 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +0000947 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +0000948 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
949 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
950 1, false);
Chris Lattner3fcc7902010-06-27 01:06:27 +0000951 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000952}
953
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000954// Function to store a first-class aggregate into memory. We prefer to
955// store the elements rather than the aggregate to be more friendly to
956// fast-isel.
957// FIXME: Do we need to recurse here?
958static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
959 llvm::Value *DestPtr, bool DestIsVolatile,
960 bool LowAlignment) {
961 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +0000962 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000963 dyn_cast<llvm::StructType>(Val->getType())) {
964 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
965 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
966 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
967 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
968 DestIsVolatile);
969 if (LowAlignment)
970 SI->setAlignment(1);
971 }
972 } else {
Bill Wendlingf6af30f2012-03-16 21:45:12 +0000973 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
974 if (LowAlignment)
975 SI->setAlignment(1);
Eli Friedmanaf9b3252011-05-17 21:08:01 +0000976 }
977}
978
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000979/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
980/// where the source and destination may have different types.
981///
982/// This safely handles the case when the src type is larger than the
983/// destination type; the upper bits of the src will be lost.
984static void CreateCoercedStore(llvm::Value *Src,
985 llvm::Value *DstPtr,
Anders Carlsson17490832009-12-24 20:40:36 +0000986 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000987 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000988 llvm::Type *SrcTy = Src->getType();
989 llvm::Type *DstTy =
Daniel Dunbarf5589ac2009-02-02 19:06:38 +0000990 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +0000991 if (SrcTy == DstTy) {
992 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
993 return;
994 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000995
Micah Villmowdd31ca12012-10-08 16:25:52 +0000996 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000997
Chris Lattner2192fe52011-07-18 04:24:23 +0000998 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattner895c52b2010-06-27 06:04:18 +0000999 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
1000 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1001 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001002
Chris Lattner055097f2010-06-27 06:26:04 +00001003 // If the source and destination are integer or pointer types, just do an
1004 // extension or truncation to the desired type.
1005 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1006 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1007 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1008 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
1009 return;
1010 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001011
Micah Villmowdd31ca12012-10-08 16:25:52 +00001012 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001013
Daniel Dunbar313321e2009-02-03 05:31:23 +00001014 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001015 if (SrcSize <= DstSize) {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001016 llvm::Value *Casted =
1017 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbaree9e4c22009-02-07 02:46:03 +00001018 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001019 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001020 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001021 // Otherwise do coercion through memory. This is stupid, but
1022 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001023
1024 // Generally SrcSize is never greater than DstSize, since this means we are
1025 // losing bits. However, this can happen in cases where the structure has
1026 // additional padding, for example due to a user specified alignment.
1027 //
1028 // FIXME: Assert that we aren't truncating non-padding bits when have access
1029 // to that information.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001030 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1031 CGF.Builder.CreateStore(Src, Tmp);
Manman Ren84b921f2012-11-28 22:08:52 +00001032 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
1033 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
1034 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren836a93b2012-11-28 22:29:41 +00001035 // FIXME: Use better alignment.
Manman Ren84b921f2012-11-28 22:08:52 +00001036 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1037 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
1038 1, false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001039 }
1040}
1041
Alexey Samsonov153004f2014-09-29 22:08:00 +00001042namespace {
1043
1044/// Encapsulates information about the way function arguments from
1045/// CGFunctionInfo should be passed to actual LLVM IR function.
1046class ClangToLLVMArgMapping {
1047 static const unsigned InvalidIndex = ~0U;
1048 unsigned InallocaArgNo;
1049 unsigned SRetArgNo;
1050 unsigned TotalIRArgs;
1051
1052 /// Arguments of LLVM IR function corresponding to single Clang argument.
1053 struct IRArgs {
1054 unsigned PaddingArgIndex;
1055 // Argument is expanded to IR arguments at positions
1056 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1057 unsigned FirstArgIndex;
1058 unsigned NumberOfArgs;
1059
1060 IRArgs()
1061 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1062 NumberOfArgs(0) {}
1063 };
1064
1065 SmallVector<IRArgs, 8> ArgInfo;
1066
1067public:
1068 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1069 bool OnlyRequiredArgs = false)
1070 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1071 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1072 construct(Context, FI, OnlyRequiredArgs);
1073 }
1074
1075 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1076 unsigned getInallocaArgNo() const {
1077 assert(hasInallocaArg());
1078 return InallocaArgNo;
1079 }
1080
1081 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1082 unsigned getSRetArgNo() const {
1083 assert(hasSRetArg());
1084 return SRetArgNo;
1085 }
1086
1087 unsigned totalIRArgs() const { return TotalIRArgs; }
1088
1089 bool hasPaddingArg(unsigned ArgNo) const {
1090 assert(ArgNo < ArgInfo.size());
1091 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1092 }
1093 unsigned getPaddingArgNo(unsigned ArgNo) const {
1094 assert(hasPaddingArg(ArgNo));
1095 return ArgInfo[ArgNo].PaddingArgIndex;
1096 }
1097
1098 /// Returns index of first IR argument corresponding to ArgNo, and their
1099 /// quantity.
1100 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1101 assert(ArgNo < ArgInfo.size());
1102 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1103 ArgInfo[ArgNo].NumberOfArgs);
1104 }
1105
1106private:
1107 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1108 bool OnlyRequiredArgs);
1109};
1110
1111void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1112 const CGFunctionInfo &FI,
1113 bool OnlyRequiredArgs) {
1114 unsigned IRArgNo = 0;
1115 bool SwapThisWithSRet = false;
1116 const ABIArgInfo &RetAI = FI.getReturnInfo();
1117
1118 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1119 SwapThisWithSRet = RetAI.isSRetAfterThis();
1120 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1121 }
1122
1123 unsigned ArgNo = 0;
1124 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1125 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1126 ++I, ++ArgNo) {
1127 assert(I != FI.arg_end());
1128 QualType ArgType = I->type;
1129 const ABIArgInfo &AI = I->info;
1130 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1131 auto &IRArgs = ArgInfo[ArgNo];
1132
1133 if (AI.getPaddingType())
1134 IRArgs.PaddingArgIndex = IRArgNo++;
1135
1136 switch (AI.getKind()) {
1137 case ABIArgInfo::Extend:
1138 case ABIArgInfo::Direct: {
1139 // FIXME: handle sseregparm someday...
1140 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1141 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1142 IRArgs.NumberOfArgs = STy->getNumElements();
1143 } else {
1144 IRArgs.NumberOfArgs = 1;
1145 }
1146 break;
1147 }
1148 case ABIArgInfo::Indirect:
1149 IRArgs.NumberOfArgs = 1;
1150 break;
1151 case ABIArgInfo::Ignore:
1152 case ABIArgInfo::InAlloca:
1153 // ignore and inalloca doesn't have matching LLVM parameters.
1154 IRArgs.NumberOfArgs = 0;
1155 break;
1156 case ABIArgInfo::Expand: {
1157 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1158 break;
1159 }
1160 }
1161
1162 if (IRArgs.NumberOfArgs > 0) {
1163 IRArgs.FirstArgIndex = IRArgNo;
1164 IRArgNo += IRArgs.NumberOfArgs;
1165 }
1166
1167 // Skip over the sret parameter when it comes second. We already handled it
1168 // above.
1169 if (IRArgNo == 1 && SwapThisWithSRet)
1170 IRArgNo++;
1171 }
1172 assert(ArgNo == ArgInfo.size());
1173
1174 if (FI.usesInAlloca())
1175 InallocaArgNo = IRArgNo++;
1176
1177 TotalIRArgs = IRArgNo;
1178}
1179} // namespace
1180
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001181/***/
1182
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001183bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001184 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001185}
1186
Tim Northovere77cc392014-03-29 13:28:05 +00001187bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1188 return ReturnTypeUsesSRet(FI) &&
1189 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1190}
1191
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001192bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1193 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1194 switch (BT->getKind()) {
1195 default:
1196 return false;
1197 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001198 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001199 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001200 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001201 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001202 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001203 }
1204 }
1205
1206 return false;
1207}
1208
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001209bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1210 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1211 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1212 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001213 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001214 }
1215 }
1216
1217 return false;
1218}
1219
Chris Lattnera5f58b02011-07-09 17:41:47 +00001220llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001221 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1222 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001223}
1224
Chris Lattnera5f58b02011-07-09 17:41:47 +00001225llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001226CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001227
David Blaikie82e95a32014-11-19 07:49:47 +00001228 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1229 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001230 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001231
Alexey Samsonov153004f2014-09-29 22:08:00 +00001232 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001233 const ABIArgInfo &retAI = FI.getReturnInfo();
1234 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001235 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001236 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001237
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001238 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001239 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001240 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001241 break;
1242
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001243 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001244 if (retAI.getInAllocaSRet()) {
1245 // sret things on win32 aren't void, they return the sret pointer.
1246 QualType ret = FI.getReturnType();
1247 llvm::Type *ty = ConvertType(ret);
1248 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1249 resultType = llvm::PointerType::get(ty, addressSpace);
1250 } else {
1251 resultType = llvm::Type::getVoidTy(getLLVMContext());
1252 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001253 break;
1254
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001255 case ABIArgInfo::Indirect: {
John McCall85dd2c52011-05-15 02:19:42 +00001256 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
1257 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001258 break;
1259 }
1260
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001261 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001262 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001263 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Alexey Samsonov153004f2014-09-29 22:08:00 +00001266 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1267 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1268
1269 // Add type for sret argument.
1270 if (IRFunctionArgs.hasSRetArg()) {
1271 QualType Ret = FI.getReturnType();
1272 llvm::Type *Ty = ConvertType(Ret);
1273 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1274 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1275 llvm::PointerType::get(Ty, AddressSpace);
1276 }
1277
1278 // Add type for inalloca argument.
1279 if (IRFunctionArgs.hasInallocaArg()) {
1280 auto ArgStruct = FI.getArgStruct();
1281 assert(ArgStruct);
1282 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1283 }
1284
John McCallc818bbb2012-12-07 07:03:17 +00001285 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001286 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001287 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1288 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001289 for (; it != ie; ++it, ++ArgNo) {
1290 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001291
Rafael Espindolafad28de2012-10-24 01:59:00 +00001292 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001293 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1294 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1295 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001296
Alexey Samsonov153004f2014-09-29 22:08:00 +00001297 unsigned FirstIRArg, NumIRArgs;
1298 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1299
1300 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001301 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001302 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001303 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001304 break;
1305
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001306 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001307 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001308 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001309 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001310 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001311 break;
1312 }
1313
1314 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001315 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001316 // Fast-isel and the optimizer generally like scalar values better than
1317 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001318 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001319 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001320 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1321 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001322 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001323 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001324 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001325 assert(NumIRArgs == 1);
1326 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001327 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001328 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Daniel Dunbard3674e62008-09-11 01:48:57 +00001331 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001332 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1333 getExpandedTypes(it->type, ArgTypesIter);
1334 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001335 break;
1336 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001337 }
1338
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001339 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1340 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001341
1342 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001343}
1344
Chris Lattner2192fe52011-07-18 04:24:23 +00001345llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001346 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001347 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001348
Chris Lattner8806e322011-07-10 00:18:59 +00001349 if (!isFuncTypeConvertible(FPT))
1350 return llvm::StructType::get(getLLVMContext());
1351
1352 const CGFunctionInfo *Info;
1353 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001354 Info =
1355 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001356 else
John McCalla729c622012-02-17 03:33:10 +00001357 Info = &arrangeCXXMethodDeclaration(MD);
1358 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001359}
1360
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001361void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbard931a872009-02-02 22:03:45 +00001362 const Decl *TargetDecl,
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001363 AttributeListType &PAL,
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00001364 unsigned &CallingConv,
1365 bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001366 llvm::AttrBuilder FuncAttrs;
1367 llvm::AttrBuilder RetAttrs;
Paul Robinson08556952014-12-11 20:14:04 +00001368 bool HasOptnone = false;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001369
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001370 CallingConv = FI.getEffectiveCallingConvention();
1371
John McCallab26cfa2010-02-05 21:31:56 +00001372 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001373 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001374
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001375 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001376 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001377 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001378 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001379 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001380 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001381 if (TargetDecl->hasAttr<NoReturnAttr>())
1382 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001383 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1384 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smithdebc59d2013-01-30 05:45:05 +00001385
1386 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCallbe349de2010-07-08 06:48:12 +00001387 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl31ad7542011-03-13 17:09:40 +00001388 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling207f0532012-12-20 19:27:06 +00001389 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith49af6292013-03-05 08:30:04 +00001390 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1391 // These attributes are not inherited by overloads.
1392 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1393 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001394 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001395 }
1396
Eric Christopherbf005ec2011-08-15 22:38:22 +00001397 // 'const' and 'pure' attribute functions are also nounwind.
1398 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001399 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1400 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001401 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001402 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1403 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001404 }
David Majnemer631a90b2015-02-04 07:23:21 +00001405 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001406 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001407 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1408 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001409
1410 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001411 }
1412
Paul Robinson08556952014-12-11 20:14:04 +00001413 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1414 if (!HasOptnone) {
1415 if (CodeGenOpts.OptimizeSize)
1416 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1417 if (CodeGenOpts.OptimizeSize == 2)
1418 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1419 }
1420
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001421 if (CodeGenOpts.DisableRedZone)
Bill Wendling207f0532012-12-20 19:27:06 +00001422 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruthbc55fe22009-11-12 17:24:48 +00001423 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling207f0532012-12-20 19:27:06 +00001424 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001425 if (CodeGenOpts.EnableSegmentedStacks &&
1426 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001427 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001428
Bill Wendling2f81db62013-02-22 20:53:29 +00001429 if (AttrOnCallSite) {
1430 // Attributes that should go on the call site only.
1431 if (!CodeGenOpts.SimplifyLibCalls)
1432 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendling706469b2013-02-28 22:49:57 +00001433 } else {
1434 // Attributes that should go on the function, but not the call site.
Bill Wendling706469b2013-02-28 22:49:57 +00001435 if (!CodeGenOpts.DisableFPElim) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001436 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling706469b2013-02-28 22:49:57 +00001437 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001438 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001439 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001440 } else {
Bill Wendlingdabafea2013-03-13 22:24:33 +00001441 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendling17d1b6142013-08-22 21:16:51 +00001442 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendling706469b2013-02-28 22:49:57 +00001443 }
1444
Bill Wendlingdabafea2013-03-13 22:24:33 +00001445 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001446 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001447 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001448 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001449 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001450 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001451 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001452 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendlingdabafea2013-03-13 22:24:33 +00001453 FuncAttrs.addAttribute("use-soft-float",
Bill Wendlingf69f5942013-07-26 21:51:11 +00001454 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendlingb3219722013-07-22 20:15:41 +00001455 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling021c8de2013-07-12 22:26:07 +00001456 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlinga9cc8c02013-07-25 00:32:41 +00001457
Bill Wendlingd8f49502013-08-01 21:41:02 +00001458 if (!CodeGenOpts.StackRealignment)
1459 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendling985d1c52013-02-15 21:30:01 +00001460 }
1461
Alexey Samsonov153004f2014-09-29 22:08:00 +00001462 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001463
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001464 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001465 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001466 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001467 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001468 if (RetTy->hasSignedIntegerRepresentation())
1469 RetAttrs.addAttribute(llvm::Attribute::SExt);
1470 else if (RetTy->hasUnsignedIntegerRepresentation())
1471 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001472 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001473 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001474 if (RetAI.getInReg())
1475 RetAttrs.addAttribute(llvm::Attribute::InReg);
1476 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001477 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001478 break;
1479
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001480 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001481 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001482 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001483 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1484 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001485 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001486 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001487
Daniel Dunbard3674e62008-09-11 01:48:57 +00001488 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001489 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001490 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001491
Hal Finkela2347ba2014-07-18 15:52:10 +00001492 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1493 QualType PTy = RefTy->getPointeeType();
1494 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1495 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1496 .getQuantity());
1497 else if (getContext().getTargetAddressSpace(PTy) == 0)
1498 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1499 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001500
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001501 // Attach return attributes.
1502 if (RetAttrs.hasAttributes()) {
1503 PAL.push_back(llvm::AttributeSet::get(
1504 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1505 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001506
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001507 // Attach attributes to sret.
1508 if (IRFunctionArgs.hasSRetArg()) {
1509 llvm::AttrBuilder SRETAttrs;
1510 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
1511 if (RetAI.getInReg())
1512 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1513 PAL.push_back(llvm::AttributeSet::get(
1514 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1515 }
1516
1517 // Attach attributes to inalloca argument.
1518 if (IRFunctionArgs.hasInallocaArg()) {
1519 llvm::AttrBuilder Attrs;
1520 Attrs.addAttribute(llvm::Attribute::InAlloca);
1521 PAL.push_back(llvm::AttributeSet::get(
1522 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1523 }
1524
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001525 unsigned ArgNo = 0;
1526 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1527 E = FI.arg_end();
1528 I != E; ++I, ++ArgNo) {
1529 QualType ParamType = I->type;
1530 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001531 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001532
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001533 // Add attribute for padding argument, if necessary.
1534 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001535 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001536 PAL.push_back(llvm::AttributeSet::get(
1537 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1538 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001539 }
1540
John McCall39ec71f2010-03-27 00:47:27 +00001541 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1542 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001543 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001544 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001545 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001546 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001547 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001548 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001549 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001550 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001551 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001552 if (ArgNo == 0 && FI.isChainCall())
1553 Attrs.addAttribute(llvm::Attribute::Nest);
1554 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001555 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001556 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001557
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001558 case ABIArgInfo::Indirect:
Rafael Espindola703c47f2012-10-19 05:04:37 +00001559 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001560 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001561
Anders Carlsson20759ad2009-09-16 15:53:40 +00001562 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001563 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001564
Bill Wendlinga7912f82012-10-10 07:36:56 +00001565 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1566
Daniel Dunbarc2304432009-03-18 19:51:01 +00001567 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001568 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1569 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001570 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001571
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001572 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001573 case ABIArgInfo::Expand:
Mike Stump11289f42009-09-09 15:08:12 +00001574 continue;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001575
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001576 case ABIArgInfo::InAlloca:
1577 // inalloca disables readnone and readonly.
1578 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1579 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001580 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001581 }
Mike Stump11289f42009-09-09 15:08:12 +00001582
Hal Finkela2347ba2014-07-18 15:52:10 +00001583 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
1584 QualType PTy = RefTy->getPointeeType();
1585 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
1586 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1587 .getQuantity());
1588 else if (getContext().getTargetAddressSpace(PTy) == 0)
1589 Attrs.addAttribute(llvm::Attribute::NonNull);
1590 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001591
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001592 if (Attrs.hasAttributes()) {
1593 unsigned FirstIRArg, NumIRArgs;
1594 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1595 for (unsigned i = 0; i < NumIRArgs; i++)
1596 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
1597 FirstIRArg + i + 1, Attrs));
1598 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001599 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001600 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001601
Bill Wendlinga7912f82012-10-10 07:36:56 +00001602 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00001603 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00001604 AttributeSet::get(getLLVMContext(),
1605 llvm::AttributeSet::FunctionIndex,
1606 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001607}
1608
John McCalla738c252011-03-09 04:27:21 +00001609/// An argument came in as a promoted argument; demote it back to its
1610/// declared type.
1611static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1612 const VarDecl *var,
1613 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001614 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00001615
1616 // This can happen with promotions that actually don't change the
1617 // underlying type, like the enum promotions.
1618 if (value->getType() == varType) return value;
1619
1620 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1621 && "unexpected promotion type");
1622
1623 if (isa<llvm::IntegerType>(varType))
1624 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1625
1626 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1627}
1628
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001629/// Returns the attribute (either parameter attribute, or function
1630/// attribute), which declares argument ArgNo to be non-null.
1631static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
1632 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001633 // FIXME: __attribute__((nonnull)) can also be applied to:
1634 // - references to pointers, where the pointee is known to be
1635 // nonnull (apparently a Clang extension)
1636 // - transparent unions containing pointers
1637 // In the former case, LLVM IR cannot represent the constraint. In
1638 // the latter case, we have no guarantee that the transparent union
1639 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001640 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
1641 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001642 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001643 if (PVD) {
1644 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
1645 return ParmNNAttr;
1646 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001647 // Check function attributes.
1648 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001649 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001650 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001651 if (NNAttr->isNonNull(ArgNo))
1652 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001653 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001654 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00001655}
1656
Daniel Dunbard931a872009-02-02 22:03:45 +00001657void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1658 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00001659 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00001660 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
1661 // Naked functions don't have prologues.
1662 return;
1663
John McCallcaa19452009-07-28 01:00:58 +00001664 // If this is an implicit-return-zero function, go ahead and
1665 // initialize the return value. TODO: it might be nice to have
1666 // a more general mechanism for this that didn't require synthesized
1667 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00001668 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00001669 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00001670 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001671 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00001672 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00001673 Builder.CreateStore(Zero, ReturnValue);
1674 }
1675 }
1676
Mike Stump18bb9282009-05-16 07:57:57 +00001677 // FIXME: We no longer need the types from FunctionArgList; lift up and
1678 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00001679
Alexey Samsonov153004f2014-09-29 22:08:00 +00001680 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001681 // Flattened function arguments.
1682 SmallVector<llvm::Argument *, 16> FnArgs;
1683 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
1684 for (auto &Arg : Fn->args()) {
1685 FnArgs.push_back(&Arg);
1686 }
1687 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00001688
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001689 // If we're using inalloca, all the memory arguments are GEPs off of the last
1690 // parameter, which is a pointer to the complete memory area.
Craig Topper8a13c412014-05-21 05:09:00 +00001691 llvm::Value *ArgStruct = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001692 if (IRFunctionArgs.hasInallocaArg()) {
1693 ArgStruct = FnArgs[IRFunctionArgs.getInallocaArgNo()];
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001694 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1695 }
1696
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001697 // Name the struct return parameter.
1698 if (IRFunctionArgs.hasSRetArg()) {
1699 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
Daniel Dunbar613855c2008-09-09 23:27:19 +00001700 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00001701 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001702 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00001703 }
Mike Stump11289f42009-09-09 15:08:12 +00001704
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001705 // Track if we received the parameter as a pointer (indirect, byval, or
1706 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1707 // into a local alloca for us.
1708 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
Reid Kleckner8ae16272014-02-01 00:23:22 +00001709 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001710 SmallVector<ValueAndIsPtr, 16> ArgVals;
1711 ArgVals.reserve(Args.size());
1712
Reid Kleckner739756c2013-12-04 19:23:12 +00001713 // Create a pointer value for every parameter declaration. This usually
1714 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1715 // any cleanups or do anything that might unwind. We do that separately, so
1716 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00001717 assert(FI.arg_size() == Args.size() &&
1718 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001719 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001720 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001721 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00001722 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00001723 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001724 QualType Ty = info_it->type;
1725 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001726
John McCalla738c252011-03-09 04:27:21 +00001727 bool isPromoted =
1728 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1729
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001730 unsigned FirstIRArg, NumIRArgs;
1731 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00001732
Daniel Dunbard3674e62008-09-11 01:48:57 +00001733 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001734 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001735 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001736 llvm::Value *V = Builder.CreateStructGEP(
1737 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1738 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001739 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001740 }
1741
Daniel Dunbar747865a2009-02-05 09:16:39 +00001742 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001743 assert(NumIRArgs == 1);
1744 llvm::Value *V = FnArgs[FirstIRArg];
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001745
John McCall47fb9502013-03-07 21:37:08 +00001746 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001747 // Aggregates and complex variables are accessed by reference. All we
1748 // need to do is realign the value, if requested
1749 if (ArgI.getIndirectRealign()) {
1750 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1751
1752 // Copy from the incoming argument pointer to the temporary with the
1753 // appropriate alignment.
1754 //
1755 // FIXME: We should have a common utility for generating an aggregate
1756 // copy.
Chris Lattner2192fe52011-07-18 04:24:23 +00001757 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyck705ba072011-01-19 01:58:38 +00001758 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumidd634362011-03-10 14:02:21 +00001759 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1760 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1761 Builder.CreateMemCpy(Dst,
1762 Src,
Ken Dyck705ba072011-01-19 01:58:38 +00001763 llvm::ConstantInt::get(IntPtrTy,
1764 Size.getQuantity()),
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001765 ArgI.getIndirectAlign(),
1766 false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00001767 V = AlignedTemp;
1768 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001769 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001770 } else {
1771 // Load scalar value from indirect argument.
Ken Dyck705ba072011-01-19 01:58:38 +00001772 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky2d84e842013-10-02 02:29:49 +00001773 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1774 Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001775
1776 if (isPromoted)
1777 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001778 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar747865a2009-02-05 09:16:39 +00001779 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00001780 break;
1781 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001782
1783 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001784 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00001785
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001786 // If we have the trivial case, handle it with no muss and fuss.
1787 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001788 ArgI.getCoerceToType() == ConvertType(Ty) &&
1789 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001790 assert(NumIRArgs == 1);
1791 auto AI = FnArgs[FirstIRArg];
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001792 llvm::Value *V = AI;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001793
Hal Finkel48d53e22014-07-19 01:41:07 +00001794 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001795 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
1796 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00001797 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1798 AI->getArgNo() + 1,
1799 llvm::Attribute::NonNull));
1800
Hal Finkel48d53e22014-07-19 01:41:07 +00001801 QualType OTy = PVD->getOriginalType();
1802 if (const auto *ArrTy =
1803 getContext().getAsConstantArrayType(OTy)) {
1804 // A C99 array parameter declaration with the static keyword also
1805 // indicates dereferenceability, and if the size is constant we can
1806 // use the dereferenceable attribute (which requires the size in
1807 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00001808 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00001809 QualType ETy = ArrTy->getElementType();
1810 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
1811 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
1812 ArrSize) {
1813 llvm::AttrBuilder Attrs;
1814 Attrs.addDereferenceableAttr(
1815 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
1816 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1817 AI->getArgNo() + 1, Attrs));
1818 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
1819 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1820 AI->getArgNo() + 1,
1821 llvm::Attribute::NonNull));
1822 }
1823 }
1824 } else if (const auto *ArrTy =
1825 getContext().getAsVariableArrayType(OTy)) {
1826 // For C99 VLAs with the static keyword, we don't know the size so
1827 // we can't use the dereferenceable attribute, but in addrspace(0)
1828 // we know that it must be nonnull.
1829 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
1830 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
1831 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1832 AI->getArgNo() + 1,
1833 llvm::Attribute::NonNull));
1834 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00001835
1836 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
1837 if (!AVAttr)
1838 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
1839 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
1840 if (AVAttr) {
1841 llvm::Value *AlignmentValue =
1842 EmitScalarExpr(AVAttr->getAlignment());
1843 llvm::ConstantInt *AlignmentCI =
1844 cast<llvm::ConstantInt>(AlignmentValue);
1845 unsigned Alignment =
1846 std::min((unsigned) AlignmentCI->getZExtValue(),
1847 +llvm::Value::MaximumAlignment);
1848
1849 llvm::AttrBuilder Attrs;
1850 Attrs.addAlignmentAttr(Alignment);
1851 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1852 AI->getArgNo() + 1, Attrs));
1853 }
Hal Finkel48d53e22014-07-19 01:41:07 +00001854 }
1855
Bill Wendling507c3512012-10-16 05:23:44 +00001856 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001857 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1858 AI->getArgNo() + 1,
1859 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00001860
Chris Lattner7369c142011-07-20 06:29:00 +00001861 // Ensure the argument is the correct type.
1862 if (V->getType() != ArgI.getCoerceToType())
1863 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1864
John McCalla738c252011-03-09 04:27:21 +00001865 if (isPromoted)
1866 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00001867
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001868 if (const CXXMethodDecl *MD =
1869 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001870 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001871 V = CGM.getCXXABI().
1872 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00001873 }
1874
Rafael Espindola8778c282012-11-29 16:09:03 +00001875 // Because of merging of function types from multiple decls it is
1876 // possible for the type of an argument to not match the corresponding
1877 // type in the function type. Since we are codegening the callee
1878 // in here, add a cast to the argument type.
1879 llvm::Type *LTy = ConvertType(Arg->getType());
1880 if (V->getType() != LTy)
1881 V = Builder.CreateBitCast(V, LTy);
1882
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001883 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001884 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00001885 }
Mike Stump11289f42009-09-09 15:08:12 +00001886
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001887 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001888
Chris Lattnerff941a62010-07-28 18:24:28 +00001889 // The alignment we need to use is the max of the requested alignment for
1890 // the argument plus the alignment required by our access code below.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001891 unsigned AlignmentToUse =
Micah Villmowdd31ca12012-10-08 16:25:52 +00001892 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerff941a62010-07-28 18:24:28 +00001893 AlignmentToUse = std::max(AlignmentToUse,
1894 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001895
Chris Lattnerff941a62010-07-28 18:24:28 +00001896 Alloca->setAlignment(AlignmentToUse);
Chris Lattnerc401de92010-07-05 20:21:00 +00001897 llvm::Value *V = Alloca;
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001898 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001899
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001900 // If the value is offset in memory, apply the offset now.
1901 if (unsigned Offs = ArgI.getDirectOffset()) {
1902 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1903 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001904 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00001905 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1906 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001907
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001908 // Fast-isel and the optimizer generally like scalar values better than
1909 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001910 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001911 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
1912 STy->getNumElements() > 1) {
Micah Villmowdd31ca12012-10-08 16:25:52 +00001913 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001914 llvm::Type *DstTy =
1915 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00001916 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001917
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001918 if (SrcSize <= DstSize) {
1919 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1920
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001921 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001922 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001923 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001924 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1925 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001926 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001927 }
1928 } else {
1929 llvm::AllocaInst *TempAlloca =
1930 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1931 TempAlloca->setAlignment(AlignmentToUse);
1932 llvm::Value *TempV = TempAlloca;
1933
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001934 assert(STy->getNumElements() == NumIRArgs);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001935 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001936 auto AI = FnArgs[FirstIRArg + i];
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001937 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1938 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001939 Builder.CreateStore(AI, EltPtr);
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00001940 }
1941
1942 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner15ec3612010-06-29 00:06:42 +00001943 }
1944 } else {
1945 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001946 assert(NumIRArgs == 1);
1947 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00001948 AI->setName(Arg->getName() + ".coerce");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001949 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00001950 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001951
1952
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001953 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00001954 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001955 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00001956 if (isPromoted)
1957 V = emitArgumentDemotion(*this, Arg, V);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001958 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1959 } else {
1960 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00001961 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001962 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001963 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001964
1965 case ABIArgInfo::Expand: {
1966 // If this structure was expanded into multiple arguments then
1967 // we need to create a temporary and reconstruct it from the
1968 // arguments.
Eli Friedman3d9f47f2011-11-03 21:39:02 +00001969 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedmana0544d62011-12-03 04:14:32 +00001970 CharUnits Align = getContext().getDeclAlign(Arg);
1971 Alloca->setAlignment(Align.getQuantity());
1972 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001973 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001974
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001975 auto FnArgIter = FnArgs.begin() + FirstIRArg;
1976 ExpandTypeFromArgs(Ty, LV, FnArgIter);
1977 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
1978 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
1979 auto AI = FnArgs[FirstIRArg + i];
1980 AI->setName(Arg->getName() + "." + Twine(i));
1981 }
1982 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001983 }
1984
1985 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001986 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001987 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001988 if (!hasScalarEvaluationKind(Ty)) {
1989 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1990 } else {
1991 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1992 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1993 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001994 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00001995 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00001996 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001997
Reid Kleckner739756c2013-12-04 19:23:12 +00001998 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1999 for (int I = Args.size() - 1; I >= 0; --I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002000 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2001 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002002 } else {
2003 for (unsigned I = 0, E = Args.size(); I != E; ++I)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002004 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
2005 I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002006 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002007}
2008
John McCallffa2c1a2012-01-29 07:46:59 +00002009static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2010 while (insn->use_empty()) {
2011 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2012 if (!bitcast) return;
2013
2014 // This is "safe" because we would have used a ConstantExpr otherwise.
2015 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2016 bitcast->eraseFromParent();
2017 }
2018}
2019
John McCall31168b02011-06-15 23:02:42 +00002020/// Try to emit a fused autorelease of a return result.
2021static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2022 llvm::Value *result) {
2023 // We must be immediately followed the cast.
2024 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002025 if (BB->empty()) return nullptr;
2026 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002027
Chris Lattner2192fe52011-07-18 04:24:23 +00002028 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002029
2030 // result is in a BasicBlock and is therefore an Instruction.
2031 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2032
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002033 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCall31168b02011-06-15 23:02:42 +00002034
2035 // Look for:
2036 // %generator = bitcast %type1* %generator2 to %type2*
2037 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2038 // We would have emitted this as a constant if the operand weren't
2039 // an Instruction.
2040 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2041
2042 // Require the generator to be immediately followed by the cast.
2043 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002044 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002045
2046 insnsToKill.push_back(bitcast);
2047 }
2048
2049 // Look for:
2050 // %generator = call i8* @objc_retain(i8* %originalResult)
2051 // or
2052 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2053 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002054 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002055
2056 bool doRetainAutorelease;
2057
2058 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
2059 doRetainAutorelease = true;
2060 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
2061 .objc_retainAutoreleasedReturnValue) {
2062 doRetainAutorelease = false;
2063
John McCallcfa4e9b2012-09-07 23:30:50 +00002064 // If we emitted an assembly marker for this call (and the
2065 // ARCEntrypoints field should have been set if so), go looking
2066 // for that call. If we can't find it, we can't do this
2067 // optimization. But it should always be the immediately previous
2068 // instruction, unless we needed bitcasts around the call.
2069 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
2070 llvm::Instruction *prev = call->getPrevNode();
2071 assert(prev);
2072 if (isa<llvm::BitCastInst>(prev)) {
2073 prev = prev->getPrevNode();
2074 assert(prev);
2075 }
2076 assert(isa<llvm::CallInst>(prev));
2077 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
2078 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
2079 insnsToKill.push_back(prev);
2080 }
John McCall31168b02011-06-15 23:02:42 +00002081 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002082 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002083 }
2084
2085 result = call->getArgOperand(0);
2086 insnsToKill.push_back(call);
2087
2088 // Keep killing bitcasts, for sanity. Note that we no longer care
2089 // about precise ordering as long as there's exactly one use.
2090 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2091 if (!bitcast->hasOneUse()) break;
2092 insnsToKill.push_back(bitcast);
2093 result = bitcast->getOperand(0);
2094 }
2095
2096 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002097 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCall31168b02011-06-15 23:02:42 +00002098 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
2099 (*i)->eraseFromParent();
2100
2101 // Do the fused retain/autorelease if we were asked to.
2102 if (doRetainAutorelease)
2103 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2104
2105 // Cast back to the result type.
2106 return CGF.Builder.CreateBitCast(result, resultType);
2107}
2108
John McCallffa2c1a2012-01-29 07:46:59 +00002109/// If this is a +1 of the value of an immutable 'self', remove it.
2110static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2111 llvm::Value *result) {
2112 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002113 const ObjCMethodDecl *method =
2114 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002115 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002116 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002117 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002118
2119 // Look for a retain call.
2120 llvm::CallInst *retainCall =
2121 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2122 if (!retainCall ||
2123 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002124 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002125
2126 // Look for an ordinary load of 'self'.
2127 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2128 llvm::LoadInst *load =
2129 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2130 if (!load || load->isAtomic() || load->isVolatile() ||
2131 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Craig Topper8a13c412014-05-21 05:09:00 +00002132 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002133
2134 // Okay! Burn it all down. This relies for correctness on the
2135 // assumption that the retain is emitted as part of the return and
2136 // that thereafter everything is used "linearly".
2137 llvm::Type *resultType = result->getType();
2138 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2139 assert(retainCall->use_empty());
2140 retainCall->eraseFromParent();
2141 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2142
2143 return CGF.Builder.CreateBitCast(load, resultType);
2144}
2145
John McCall31168b02011-06-15 23:02:42 +00002146/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002147///
2148/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002149static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2150 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002151 // If we're returning 'self', kill the initial retain. This is a
2152 // heuristic attempt to "encourage correctness" in the really unfortunate
2153 // case where we have a return of self during a dealloc and we desperately
2154 // need to avoid the possible autorelease.
2155 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2156 return self;
2157
John McCall31168b02011-06-15 23:02:42 +00002158 // At -O0, try to emit a fused retain/autorelease.
2159 if (CGF.shouldUseFusedARCCalls())
2160 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2161 return fused;
2162
2163 return CGF.EmitARCAutoreleaseReturnValue(result);
2164}
2165
John McCall6e1c0122012-01-29 02:35:02 +00002166/// Heuristically search for a dominating store to the return-value slot.
2167static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
2168 // If there are multiple uses of the return-value slot, just check
2169 // for something immediately preceding the IP. Sometimes this can
2170 // happen with how we generate implicit-returns; it can also happen
2171 // with noreturn cleanups.
2172 if (!CGF.ReturnValue->hasOneUse()) {
2173 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002174 if (IP->empty()) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002175 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Craig Topper8a13c412014-05-21 05:09:00 +00002176 if (!store) return nullptr;
2177 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002178 assert(!store->isAtomic() && !store->isVolatile()); // see below
2179 return store;
2180 }
2181
2182 llvm::StoreInst *store =
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002183 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002184 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002185
2186 // These aren't actually possible for non-coerced returns, and we
2187 // only care about non-coerced returns on this code path.
2188 assert(!store->isAtomic() && !store->isVolatile());
2189
2190 // Now do a first-and-dirty dominance check: just walk up the
2191 // single-predecessors chain from the current insertion point.
2192 llvm::BasicBlock *StoreBB = store->getParent();
2193 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2194 while (IP != StoreBB) {
2195 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002196 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002197 }
2198
2199 // Okay, the store's basic block dominates the insertion point; we
2200 // can do our thing.
2201 return store;
2202}
2203
Adrian Prantl3be10542013-05-02 17:30:20 +00002204void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002205 bool EmitRetDbgLoc,
2206 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002207 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2208 // Naked functions don't have epilogues.
2209 Builder.CreateUnreachable();
2210 return;
2211 }
2212
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002213 // Functions with no result always return void.
Craig Topper8a13c412014-05-21 05:09:00 +00002214 if (!ReturnValue) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002215 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002216 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002217 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002218
Dan Gohman481e40c2010-07-20 20:13:52 +00002219 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002220 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002221 QualType RetTy = FI.getReturnType();
2222 const ABIArgInfo &RetAI = FI.getReturnInfo();
2223
2224 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002225 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002226 // Aggregrates get evaluated directly into the destination. Sometimes we
2227 // need to return the sret value in a register, though.
2228 assert(hasAggregateEvaluationKind(RetTy));
2229 if (RetAI.getInAllocaSRet()) {
2230 llvm::Function::arg_iterator EI = CurFn->arg_end();
2231 --EI;
2232 llvm::Value *ArgStruct = EI;
2233 llvm::Value *SRet =
2234 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
2235 RV = Builder.CreateLoad(SRet, "sret");
2236 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002237 break;
2238
Daniel Dunbar03816342010-08-21 02:24:36 +00002239 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002240 auto AI = CurFn->arg_begin();
2241 if (RetAI.isSRetAfterThis())
2242 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002243 switch (getEvaluationKind(RetTy)) {
2244 case TEK_Complex: {
2245 ComplexPairTy RT =
Nick Lewycky2d84e842013-10-02 02:29:49 +00002246 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
2247 EndLoc);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002248 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002249 /*isInit*/ true);
2250 break;
2251 }
2252 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002253 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002254 break;
2255 case TEK_Scalar:
2256 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Reid Kleckner37abaca2014-05-09 22:46:15 +00002257 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002258 /*isInit*/ true);
2259 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002260 }
2261 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002262 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002263
2264 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002265 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002266 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2267 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002268 // The internal return value temp always will have pointer-to-return-type
2269 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002270
John McCall6e1c0122012-01-29 02:35:02 +00002271 // If there is a dominating store to ReturnValue, we can elide
2272 // the load, zap the store, and usually zap the alloca.
2273 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002274 // Reuse the debug location from the store unless there is
2275 // cleanup code to be emitted between the store and return
2276 // instruction.
2277 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002278 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002279 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002280 RV = SI->getValueOperand();
2281 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002282
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002283 // If that was the only use of the return value, nuke it as well now.
2284 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
2285 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Craig Topper8a13c412014-05-21 05:09:00 +00002286 ReturnValue = nullptr;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002287 }
John McCall6e1c0122012-01-29 02:35:02 +00002288
2289 // Otherwise, we have to do a simple load.
2290 } else {
2291 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002292 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002293 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002294 llvm::Value *V = ReturnValue;
2295 // If the value is offset in memory, apply the offset now.
2296 if (unsigned Offs = RetAI.getDirectOffset()) {
2297 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
2298 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002299 V = Builder.CreateBitCast(V,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002300 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2301 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002302
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002303 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002304 }
John McCall31168b02011-06-15 23:02:42 +00002305
2306 // In ARC, end functions that return a retainable type with a call
2307 // to objc_autoreleaseReturnValue.
2308 if (AutoreleaseResult) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002310 !FI.isReturnsRetained() &&
2311 RetTy->isObjCRetainableType());
2312 RV = emitAutoreleaseOfResult(*this, RV);
2313 }
2314
Chris Lattner726b3d02010-06-26 23:13:19 +00002315 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002316
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002317 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002318 break;
2319
2320 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002321 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002322 }
2323
Alexey Samsonovde443c52014-08-13 00:26:40 +00002324 llvm::Instruction *Ret;
2325 if (RV) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002326 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002327 if (auto RetNNAttr = CurGD.getDecl()->getAttr<ReturnsNonNullAttr>()) {
2328 SanitizerScope SanScope(this);
2329 llvm::Value *Cond = Builder.CreateICmpNE(
2330 RV, llvm::Constant::getNullValue(RV->getType()));
2331 llvm::Constant *StaticData[] = {
2332 EmitCheckSourceLocation(EndLoc),
2333 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2334 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002335 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
2336 "nonnull_return", StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002337 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002338 }
2339 Ret = Builder.CreateRet(RV);
2340 } else {
2341 Ret = Builder.CreateRetVoid();
2342 }
2343
Devang Patel65497582010-07-21 18:08:50 +00002344 if (!RetDbgLoc.isUnknown())
Benjamin Kramer03278662015-02-07 13:15:54 +00002345 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002346}
2347
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002348static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2349 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2350 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2351}
2352
2353static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
2354 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2355 // placeholders.
2356 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
2357 llvm::Value *Placeholder =
2358 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
2359 Placeholder = CGF.Builder.CreateLoad(Placeholder);
2360 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
2361 Ty.getQualifiers(),
2362 AggValueSlot::IsNotDestructed,
2363 AggValueSlot::DoesNotNeedGCBarriers,
2364 AggValueSlot::IsNotAliased);
2365}
2366
John McCall32ea9692011-03-11 20:59:21 +00002367void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002368 const VarDecl *param,
2369 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002370 // StartFunction converted the ABI-lowered parameter(s) into a
2371 // local alloca. We need to turn that into an r-value suitable
2372 // for EmitCall.
John McCall32ea9692011-03-11 20:59:21 +00002373 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002374
John McCall32ea9692011-03-11 20:59:21 +00002375 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002376
John McCall23f66262010-05-26 22:34:26 +00002377 // For the most part, we just need to load the alloca, except:
2378 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall47fb9502013-03-07 21:37:08 +00002379 // 2) references to non-scalars are pointers directly to the aggregate.
2380 // I don't know why references to scalars are different here.
John McCall32ea9692011-03-11 20:59:21 +00002381 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall47fb9502013-03-07 21:37:08 +00002382 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall32ea9692011-03-11 20:59:21 +00002383 return args.add(RValue::getAggregate(local), type);
John McCall23f66262010-05-26 22:34:26 +00002384
2385 // Locals which are references to scalars are represented
2386 // with allocas holding the pointer.
John McCall32ea9692011-03-11 20:59:21 +00002387 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall23f66262010-05-26 22:34:26 +00002388 }
2389
Reid Klecknerab2090d2014-07-26 01:34:32 +00002390 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2391 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002392
Nick Lewycky2d84e842013-10-02 02:29:49 +00002393 args.add(convertTempToRValue(local, type, loc), type);
John McCall23f66262010-05-26 22:34:26 +00002394}
2395
John McCall31168b02011-06-15 23:02:42 +00002396static bool isProvablyNull(llvm::Value *addr) {
2397 return isa<llvm::ConstantPointerNull>(addr);
2398}
2399
2400static bool isProvablyNonNull(llvm::Value *addr) {
2401 return isa<llvm::AllocaInst>(addr);
2402}
2403
2404/// Emit the actual writing-back of a writeback.
2405static void emitWriteback(CodeGenFunction &CGF,
2406 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002407 const LValue &srcLV = writeback.Source;
2408 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002409 assert(!isProvablyNull(srcAddr) &&
2410 "shouldn't have writeback for provably null argument");
2411
Craig Topper8a13c412014-05-21 05:09:00 +00002412 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002413
2414 // If the argument wasn't provably non-null, we need to null check
2415 // before doing the store.
2416 bool provablyNonNull = isProvablyNonNull(srcAddr);
2417 if (!provablyNonNull) {
2418 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2419 contBB = CGF.createBasicBlock("icr.done");
2420
2421 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2422 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2423 CGF.EmitBlock(writebackBB);
2424 }
2425
2426 // Load the value to writeback.
2427 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2428
2429 // Cast it back, in case we're writing an id to a Foo* or something.
2430 value = CGF.Builder.CreateBitCast(value,
2431 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2432 "icr.writeback-cast");
2433
2434 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00002435
2436 // If we have a "to use" value, it's something we need to emit a use
2437 // of. This has to be carefully threaded in: if it's done after the
2438 // release it's potentially undefined behavior (and the optimizer
2439 // will ignore it), and if it happens before the retain then the
2440 // optimizer could move the release there.
2441 if (writeback.ToUse) {
2442 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2443
2444 // Retain the new value. No need to block-copy here: the block's
2445 // being passed up the stack.
2446 value = CGF.EmitARCRetainNonBlock(value);
2447
2448 // Emit the intrinsic use here.
2449 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2450
2451 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00002452 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00002453
2454 // Put the new value in place (primitively).
2455 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2456
2457 // Release the old value.
2458 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2459
2460 // Otherwise, we can just do a normal lvalue store.
2461 } else {
2462 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2463 }
John McCall31168b02011-06-15 23:02:42 +00002464
2465 // Jump to the continuation block.
2466 if (!provablyNonNull)
2467 CGF.EmitBlock(contBB);
2468}
2469
2470static void emitWritebacks(CodeGenFunction &CGF,
2471 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00002472 for (const auto &I : args.writebacks())
2473 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00002474}
2475
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002476static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2477 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002478 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002479 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2480 CallArgs.getCleanupsToDeactivate();
2481 // Iterate in reverse to increase the likelihood of popping the cleanup.
2482 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2483 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2484 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2485 I->IsActiveIP->eraseFromParent();
2486 }
2487}
2488
John McCalleff18842013-03-23 02:35:54 +00002489static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2490 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2491 if (uop->getOpcode() == UO_AddrOf)
2492 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002493 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00002494}
2495
John McCall31168b02011-06-15 23:02:42 +00002496/// Emit an argument that's being passed call-by-writeback. That is,
2497/// we are passing the address of
2498static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2499 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00002500 LValue srcLV;
2501
2502 // Make an optimistic effort to emit the address as an l-value.
2503 // This can fail if the the argument expression is more complicated.
2504 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2505 srcLV = CGF.EmitLValue(lvExpr);
2506
2507 // Otherwise, just emit it as a scalar.
2508 } else {
2509 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2510
2511 QualType srcAddrType =
2512 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2513 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2514 }
2515 llvm::Value *srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00002516
2517 // The dest and src types don't necessarily match in LLVM terms
2518 // because of the crazy ObjC compatibility rules.
2519
Chris Lattner2192fe52011-07-18 04:24:23 +00002520 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00002521 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2522
2523 // If the address is a constant null, just pass the appropriate null.
2524 if (isProvablyNull(srcAddr)) {
2525 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2526 CRE->getType());
2527 return;
2528 }
2529
John McCall31168b02011-06-15 23:02:42 +00002530 // Create the temporary.
2531 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2532 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002533 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2534 // and that cleanup will be conditional if we can't prove that the l-value
2535 // isn't null, so we need to register a dominating point so that the cleanups
2536 // system will make valid IR.
2537 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2538
John McCall31168b02011-06-15 23:02:42 +00002539 // Zero-initialize it if we're not doing a copy-initialization.
2540 bool shouldCopy = CRE->shouldCopy();
2541 if (!shouldCopy) {
2542 llvm::Value *null =
2543 llvm::ConstantPointerNull::get(
2544 cast<llvm::PointerType>(destType->getElementType()));
2545 CGF.Builder.CreateStore(null, temp);
2546 }
Craig Topper8a13c412014-05-21 05:09:00 +00002547
2548 llvm::BasicBlock *contBB = nullptr;
2549 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002550
2551 // If the address is *not* known to be non-null, we need to switch.
2552 llvm::Value *finalArgument;
2553
2554 bool provablyNonNull = isProvablyNonNull(srcAddr);
2555 if (provablyNonNull) {
2556 finalArgument = temp;
2557 } else {
2558 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2559
2560 finalArgument = CGF.Builder.CreateSelect(isNull,
2561 llvm::ConstantPointerNull::get(destType),
2562 temp, "icr.argument");
2563
2564 // If we need to copy, then the load has to be conditional, which
2565 // means we need control flow.
2566 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00002567 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002568 contBB = CGF.createBasicBlock("icr.cont");
2569 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2570 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2571 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002572 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00002573 }
2574 }
2575
Craig Topper8a13c412014-05-21 05:09:00 +00002576 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00002577
John McCall31168b02011-06-15 23:02:42 +00002578 // Perform a copy if necessary.
2579 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002580 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002581 assert(srcRV.isScalar());
2582
2583 llvm::Value *src = srcRV.getScalarVal();
2584 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2585 "icr.cast");
2586
2587 // Use an ordinary store, not a store-to-lvalue.
2588 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00002589
2590 // If optimization is enabled, and the value was held in a
2591 // __strong variable, we need to tell the optimizer that this
2592 // value has to stay alive until we're doing the store back.
2593 // This is because the temporary is effectively unretained,
2594 // and so otherwise we can violate the high-level semantics.
2595 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2596 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2597 valueToUse = src;
2598 }
John McCall31168b02011-06-15 23:02:42 +00002599 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002600
John McCall31168b02011-06-15 23:02:42 +00002601 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002602 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00002603 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00002604 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00002605
2606 // Make a phi for the value to intrinsically use.
2607 if (valueToUse) {
2608 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2609 "icr.to-use");
2610 phiToUse->addIncoming(valueToUse, copyBB);
2611 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2612 originBB);
2613 valueToUse = phiToUse;
2614 }
2615
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00002616 condEval.end(CGF);
2617 }
John McCall31168b02011-06-15 23:02:42 +00002618
John McCalleff18842013-03-23 02:35:54 +00002619 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00002620 args.add(RValue::get(finalArgument), CRE->getType());
2621}
2622
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002623void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2624 assert(!StackBase && !StackCleanup.isValid());
2625
2626 // Save the stack.
2627 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2628 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2629
2630 // Control gets really tied up in landing pads, so we have to spill the
2631 // stacksave to an alloca to avoid violating SSA form.
2632 // TODO: This is dead if we never emit the cleanup. We should create the
2633 // alloca and store lazily on the first cleanup emission.
2634 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2635 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2636 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2637 StackCleanup = CGF.EHStack.getInnermostEHScope();
2638 assert(StackCleanup.isValid());
2639}
2640
2641void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2642 if (StackBase) {
2643 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2644 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2645 // We could load StackBase from StackBaseMem, but in the non-exceptional
2646 // case we can skip it.
2647 CGF.Builder.CreateCall(F, StackBase);
2648 }
2649}
2650
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002651static void emitNonNullArgCheck(CodeGenFunction &CGF, RValue RV,
2652 QualType ArgType, SourceLocation ArgLoc,
2653 const FunctionDecl *FD, unsigned ParmNum) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002654 if (!CGF.SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002655 return;
2656 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
2657 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
2658 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
2659 if (!NNAttr)
2660 return;
2661 CodeGenFunction::SanitizerScope SanScope(&CGF);
2662 assert(RV.isScalar());
2663 llvm::Value *V = RV.getScalarVal();
2664 llvm::Value *Cond =
2665 CGF.Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
2666 llvm::Constant *StaticData[] = {
2667 CGF.EmitCheckSourceLocation(ArgLoc),
2668 CGF.EmitCheckSourceLocation(NNAttr->getLocation()),
2669 llvm::ConstantInt::get(CGF.Int32Ty, ArgNo + 1),
2670 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002671 CGF.EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
2672 "nonnull_arg", StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002673}
2674
Reid Kleckner739756c2013-12-04 19:23:12 +00002675void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2676 ArrayRef<QualType> ArgTypes,
2677 CallExpr::const_arg_iterator ArgBeg,
2678 CallExpr::const_arg_iterator ArgEnd,
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002679 const FunctionDecl *CalleeDecl,
David Blaikie835afb22015-01-21 23:08:17 +00002680 unsigned ParamsToSkip) {
Reid Kleckner739756c2013-12-04 19:23:12 +00002681 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2682 // because arguments are destroyed left to right in the callee.
2683 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002684 // Insert a stack save if we're going to need any inalloca args.
2685 bool HasInAllocaArgs = false;
2686 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2687 I != E && !HasInAllocaArgs; ++I)
2688 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2689 if (HasInAllocaArgs) {
2690 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2691 Args.allocateArgumentMemory(*this);
2692 }
2693
2694 // Evaluate each argument.
Reid Kleckner739756c2013-12-04 19:23:12 +00002695 size_t CallArgsStart = Args.size();
2696 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2697 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2698 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002699 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2700 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002701 }
2702
2703 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2704 // IR function.
2705 std::reverse(Args.begin() + CallArgsStart, Args.end());
2706 return;
2707 }
2708
2709 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2710 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2711 assert(Arg != ArgEnd);
2712 EmitCallArg(Args, *Arg, ArgTypes[I]);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002713 emitNonNullArgCheck(*this, Args.back().RV, ArgTypes[I], Arg->getExprLoc(),
2714 CalleeDecl, ParamsToSkip + I);
Reid Kleckner739756c2013-12-04 19:23:12 +00002715 }
2716}
2717
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002718namespace {
2719
2720struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2721 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2722 : Addr(Addr), Ty(Ty) {}
2723
2724 llvm::Value *Addr;
2725 QualType Ty;
2726
Craig Topper4f12f102014-03-12 06:41:41 +00002727 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002728 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2729 assert(!Dtor->isTrivial());
2730 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2731 /*Delegating=*/false, Addr);
2732 }
2733};
2734
2735}
2736
David Blaikie38b25912015-02-09 19:13:51 +00002737struct DisableDebugLocationUpdates {
2738 CodeGenFunction &CGF;
2739 bool disabledDebugInfo;
2740 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
2741 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
2742 CGF.disableDebugInfo();
2743 }
2744 ~DisableDebugLocationUpdates() {
2745 if (disabledDebugInfo)
2746 CGF.enableDebugInfo();
2747 }
2748};
2749
John McCall32ea9692011-03-11 20:59:21 +00002750void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2751 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00002752 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00002753 if (const ObjCIndirectCopyRestoreExpr *CRE
2754 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002755 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00002756 assert(getContext().hasSameType(E->getType(), type));
2757 return emitWritebackArg(*this, args, CRE);
2758 }
2759
John McCall0a76c0c2011-08-26 18:42:59 +00002760 assert(type->isReferenceType() == E->isGLValue() &&
2761 "reference binding to unmaterialized r-value!");
2762
John McCall17054bd62011-08-26 21:08:13 +00002763 if (E->isGLValue()) {
2764 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00002765 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00002766 }
Mike Stump11289f42009-09-09 15:08:12 +00002767
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002768 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2769
2770 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2771 // However, we still have to push an EH-only cleanup in case we unwind before
2772 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00002773 if (HasAggregateEvalKind &&
2774 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2775 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00002776 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00002777 AggValueSlot Slot;
2778 if (args.isUsingInAlloca())
2779 Slot = createPlaceholderSlot(*this, type);
2780 else
2781 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00002782
2783 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2784 bool DestroyedInCallee =
2785 RD && RD->hasNonTrivialDestructor() &&
2786 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2787 if (DestroyedInCallee)
2788 Slot.setExternallyDestructed();
2789
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002790 EmitAggExpr(E, Slot);
2791 RValue RV = Slot.asRValue();
2792 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002793
Reid Klecknere39ee212014-05-03 00:33:28 +00002794 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002795 // Create a no-op GEP between the placeholder and the cleanup so we can
2796 // RAUW it successfully. It also serves as a marker of the first
2797 // instruction where the cleanup is active.
2798 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002799 // This unreachable is a temporary marker which will be removed later.
2800 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2801 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002802 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002803 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002804 }
2805
2806 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00002807 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2808 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2809 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00002810 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2811 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2812 } else {
2813 // We can't represent a misaligned lvalue in the CallArgList, so copy
2814 // to an aligned temporary now.
2815 llvm::Value *tmp = CreateMemTemp(type);
2816 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2817 L.getAlignment());
2818 args.add(RValue::getAggregate(tmp), type);
2819 }
Eli Friedmandf968192011-05-26 00:10:27 +00002820 return;
2821 }
2822
John McCall32ea9692011-03-11 20:59:21 +00002823 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00002824}
2825
Reid Kleckner79b0fd72014-10-10 00:05:45 +00002826QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
2827 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
2828 // implicitly widens null pointer constants that are arguments to varargs
2829 // functions to pointer-sized ints.
2830 if (!getTarget().getTriple().isOSWindows())
2831 return Arg->getType();
2832
2833 if (Arg->getType()->isIntegerType() &&
2834 getContext().getTypeSize(Arg->getType()) <
2835 getContext().getTargetInfo().getPointerWidth(0) &&
2836 Arg->isNullPointerConstant(getContext(),
2837 Expr::NPC_ValueDependentIsNotNull)) {
2838 return getContext().getIntPtrType();
2839 }
2840
2841 return Arg->getType();
2842}
2843
Dan Gohman515a60d2012-02-16 00:57:37 +00002844// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2845// optimizer it can aggressively ignore unwind edges.
2846void
2847CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2848 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2849 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2850 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2851 CGM.getNoObjCARCExceptionsMetadata());
2852}
2853
John McCall882987f2013-02-28 19:01:20 +00002854/// Emits a call to the given no-arguments nounwind runtime function.
2855llvm::CallInst *
2856CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2857 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002858 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002859}
2860
2861/// Emits a call to the given nounwind runtime function.
2862llvm::CallInst *
2863CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2864 ArrayRef<llvm::Value*> args,
2865 const llvm::Twine &name) {
2866 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2867 call->setDoesNotThrow();
2868 return call;
2869}
2870
2871/// Emits a simple call (never an invoke) to the given no-arguments
2872/// runtime function.
2873llvm::CallInst *
2874CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2875 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002876 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002877}
2878
2879/// Emits a simple call (never an invoke) to the given runtime
2880/// function.
2881llvm::CallInst *
2882CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2883 ArrayRef<llvm::Value*> args,
2884 const llvm::Twine &name) {
2885 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2886 call->setCallingConv(getRuntimeCC());
2887 return call;
2888}
2889
2890/// Emits a call or invoke to the given noreturn runtime function.
2891void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2892 ArrayRef<llvm::Value*> args) {
2893 if (getInvokeDest()) {
2894 llvm::InvokeInst *invoke =
2895 Builder.CreateInvoke(callee,
2896 getUnreachableBlock(),
2897 getInvokeDest(),
2898 args);
2899 invoke->setDoesNotReturn();
2900 invoke->setCallingConv(getRuntimeCC());
2901 } else {
2902 llvm::CallInst *call = Builder.CreateCall(callee, args);
2903 call->setDoesNotReturn();
2904 call->setCallingConv(getRuntimeCC());
2905 Builder.CreateUnreachable();
2906 }
Justin Bogner06bd6d02014-01-13 21:24:18 +00002907 PGO.setCurrentRegionUnreachable();
John McCall882987f2013-02-28 19:01:20 +00002908}
2909
2910/// Emits a call or invoke instruction to the given nullary runtime
2911/// function.
2912llvm::CallSite
2913CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2914 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002915 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00002916}
2917
2918/// Emits a call or invoke instruction to the given runtime function.
2919llvm::CallSite
2920CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2921 ArrayRef<llvm::Value*> args,
2922 const Twine &name) {
2923 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2924 callSite.setCallingConv(getRuntimeCC());
2925 return callSite;
2926}
2927
2928llvm::CallSite
2929CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2930 const Twine &Name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00002931 return EmitCallOrInvoke(Callee, None, Name);
John McCall882987f2013-02-28 19:01:20 +00002932}
2933
John McCallbd309292010-07-06 01:34:17 +00002934/// Emits a call or invoke instruction to the given function, depending
2935/// on the current state of the EH stack.
2936llvm::CallSite
2937CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00002938 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002939 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00002940 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00002941
Dan Gohman515a60d2012-02-16 00:57:37 +00002942 llvm::Instruction *Inst;
2943 if (!InvokeDest)
2944 Inst = Builder.CreateCall(Callee, Args, Name);
2945 else {
2946 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2947 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2948 EmitBlock(ContBB);
2949 }
2950
2951 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2952 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002953 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00002954 AddObjCARCExceptionMetadata(Inst);
2955
2956 return Inst;
John McCallbd309292010-07-06 01:34:17 +00002957}
2958
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002959/// \brief Store a non-aggregate value to an address to initialize it. For
2960/// initialization, a non-atomic store will be used.
2961static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2962 LValue Dst) {
2963 if (Src.isScalar())
2964 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2965 else
2966 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2967}
2968
2969void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2970 llvm::Value *New) {
2971 DeferredReplacements.push_back(std::make_pair(Old, New));
2972}
Chris Lattnerd59d8672011-07-12 06:29:11 +00002973
Daniel Dunbard931a872009-02-02 22:03:45 +00002974RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002975 llvm::Value *Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00002976 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002977 const CallArgList &CallArgs,
David Chisnall9eecafa2010-05-01 11:15:56 +00002978 const Decl *TargetDecl,
David Chisnallff5f88c2010-05-02 13:41:58 +00002979 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00002980 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00002981
2982 // Handle struct-return functions by passing a pointer to the
2983 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00002984 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002985 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002986
Chris Lattnerbb1952c2011-07-12 04:46:18 +00002987 llvm::FunctionType *IRFuncTy =
2988 cast<llvm::FunctionType>(
2989 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +00002990
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002991 // If we're using inalloca, insert the allocation after the stack save.
2992 // FIXME: Do this earlier rather than hacking it in here!
Craig Topper8a13c412014-05-21 05:09:00 +00002993 llvm::Value *ArgMemory = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002994 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Reid Kleckner9df1d972014-04-10 01:40:15 +00002995 llvm::Instruction *IP = CallArgs.getStackBase();
2996 llvm::AllocaInst *AI;
2997 if (IP) {
2998 IP = IP->getNextNode();
2999 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3000 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003001 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003002 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003003 AI->setUsedWithInAlloca(true);
3004 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
3005 ArgMemory = AI;
3006 }
3007
Alexey Samsonov153004f2014-09-29 22:08:00 +00003008 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003009 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3010
Chris Lattner4ca97c32009-06-13 00:26:38 +00003011 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003012 // alloca to hold the result, unless one is given to us.
Craig Topper8a13c412014-05-21 05:09:00 +00003013 llvm::Value *SRetPtr = nullptr;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003014 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003015 SRetPtr = ReturnValue.getValue();
3016 if (!SRetPtr)
3017 SRetPtr = CreateMemTemp(RetTy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003018 if (IRFunctionArgs.hasSRetArg()) {
3019 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003020 } else {
3021 llvm::Value *Addr =
3022 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
3023 Builder.CreateStore(SRetPtr, Addr);
3024 }
Anders Carlsson17490832009-12-24 20:40:36 +00003025 }
Mike Stump11289f42009-09-09 15:08:12 +00003026
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003027 assert(CallInfo.arg_size() == CallArgs.size() &&
3028 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003029 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003030 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003031 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003032 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003033 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003034 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003035
John McCall47fb9502013-03-07 21:37:08 +00003036 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003037
3038 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003039 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3040 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3041 llvm::UndefValue::get(ArgInfo.getPaddingType());
3042
3043 unsigned FirstIRArg, NumIRArgs;
3044 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003045
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003046 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003047 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003048 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003049 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3050 if (RV.isAggregate()) {
3051 // Replace the placeholder with the appropriate argument slot GEP.
3052 llvm::Instruction *Placeholder =
3053 cast<llvm::Instruction>(RV.getAggregateAddr());
3054 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3055 Builder.SetInsertPoint(Placeholder);
3056 llvm::Value *Addr = Builder.CreateStructGEP(
3057 ArgMemory, ArgInfo.getInAllocaFieldIndex());
3058 Builder.restoreIP(IP);
3059 deferPlaceholderReplacement(Placeholder, Addr);
3060 } else {
3061 // Store the RValue into the argument struct.
3062 llvm::Value *Addr =
3063 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
David Majnemer32b57b02014-03-31 16:12:47 +00003064 unsigned AS = Addr->getType()->getPointerAddressSpace();
3065 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3066 // There are some cases where a trivial bitcast is not avoidable. The
3067 // definition of a type later in a translation unit may change it's type
3068 // from {}* to (%struct.foo*)*.
3069 if (Addr->getType() != MemType)
3070 Addr = Builder.CreateBitCast(Addr, MemType);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003071 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
3072 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3073 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003074 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003075 }
3076
Daniel Dunbar03816342010-08-21 02:24:36 +00003077 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003078 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003079 if (RV.isScalar() || RV.isComplex()) {
3080 // Make a temporary alloca to pass the argument.
Eli Friedman7e68c882011-06-15 18:26:32 +00003081 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3082 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
3083 AI->setAlignment(ArgInfo.getIndirectAlign());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003084 IRCallArgs[FirstIRArg] = AI;
John McCall47fb9502013-03-07 21:37:08 +00003085
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003086 LValue argLV = MakeAddrLValue(AI, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003087 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003088 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003089 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003090 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003091 // 1. If the argument is not byval, and we are required to copy the
3092 // source. (This case doesn't occur on any common architecture.)
3093 // 2. If the argument is byval, RV is not sufficiently aligned, and
3094 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003095 // 3. If the argument is byval, but RV is located in an address space
3096 // different than that of the argument (0).
Eli Friedmanf7456192011-06-15 22:09:18 +00003097 llvm::Value *Addr = RV.getAggregateAddr();
3098 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003099 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyei3832bfd2013-03-10 12:59:00 +00003100 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003101 const unsigned ArgAddrSpace =
3102 (FirstIRArg < IRFuncTy->getNumParams()
3103 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3104 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003105 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall47fb9502013-03-07 21:37:08 +00003106 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyei3832bfd2013-03-10 12:59:00 +00003107 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
3108 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003109 // Create an aligned temporary, and copy to it.
Eli Friedmanf7456192011-06-15 22:09:18 +00003110 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
3111 if (Align > AI->getAlignment())
3112 AI->setAlignment(Align);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003113 IRCallArgs[FirstIRArg] = AI;
Chad Rosier615ed1a2012-03-29 17:37:10 +00003114 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003115 } else {
3116 // Skip the extra memcpy call.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003117 IRCallArgs[FirstIRArg] = Addr;
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003118 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003119 }
3120 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003121 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003122
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003123 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003124 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003125 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003126
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003127 case ABIArgInfo::Extend:
3128 case ABIArgInfo::Direct: {
3129 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003130 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3131 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003132 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003133 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003134 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003135 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003136 else
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003137 V = Builder.CreateLoad(RV.getAggregateAddr());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003138
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003139 // We might have to widen integers, but we should never truncate.
3140 if (ArgInfo.getCoerceToType() != V->getType() &&
3141 V->getType()->isIntegerTy())
3142 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3143
Chris Lattner3ce86682011-07-12 04:53:39 +00003144 // If the argument doesn't match, perform a bitcast to coerce it. This
3145 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003146 if (FirstIRArg < IRFuncTy->getNumParams() &&
3147 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3148 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
3149 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003150 break;
3151 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003152
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003153 // FIXME: Avoid the conversion through memory if possible.
3154 llvm::Value *SrcPtr;
John McCall47fb9502013-03-07 21:37:08 +00003155 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003156 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall47fb9502013-03-07 21:37:08 +00003157 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003158 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump11289f42009-09-09 15:08:12 +00003159 } else
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003160 SrcPtr = RV.getAggregateAddr();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003161
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003162 // If the value is offset in memory, apply the offset now.
3163 if (unsigned Offs = ArgInfo.getDirectOffset()) {
3164 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
3165 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003166 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003167 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
3168
3169 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003170
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003171 // Fast-isel and the optimizer generally like scalar values better than
3172 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003173 llvm::StructType *STy =
3174 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003175 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
Chandler Carrutha6399a52012-10-10 11:29:08 +00003176 llvm::Type *SrcTy =
3177 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
3178 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3179 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3180
3181 // If the source type is smaller than the destination type of the
3182 // coerce-to logic, copy the source value into a temp alloca the size
3183 // of the destination type to allow loading all of it. The bits past
3184 // the source value are left undef.
3185 if (SrcSize < DstSize) {
3186 llvm::AllocaInst *TempAlloca
3187 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
3188 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
3189 SrcPtr = TempAlloca;
3190 } else {
3191 SrcPtr = Builder.CreateBitCast(SrcPtr,
3192 llvm::PointerType::getUnqual(STy));
3193 }
3194
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003195 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003196 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3197 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerff941a62010-07-28 18:24:28 +00003198 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
3199 // We don't know what we're loading from.
3200 LI->setAlignment(1);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003201 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003202 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003203 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003204 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003205 assert(NumIRArgs == 1);
3206 IRCallArgs[FirstIRArg] =
3207 CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003208 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003209
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003210 break;
3211 }
3212
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003213 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003214 unsigned IRArgPos = FirstIRArg;
3215 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3216 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003217 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003218 }
3219 }
Mike Stump11289f42009-09-09 15:08:12 +00003220
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003221 if (ArgMemory) {
3222 llvm::Value *Arg = ArgMemory;
Reid Klecknerafba553e2014-07-08 02:24:27 +00003223 if (CallInfo.isVariadic()) {
3224 // When passing non-POD arguments by value to variadic functions, we will
3225 // end up with a variadic prototype and an inalloca call site. In such
3226 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3227 // the callee.
3228 unsigned CalleeAS =
3229 cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
3230 Callee = Builder.CreateBitCast(
3231 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
3232 } else {
3233 llvm::Type *LastParamTy =
3234 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3235 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003236#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003237 // Assert that these structs have equivalent element types.
3238 llvm::StructType *FullTy = CallInfo.getArgStruct();
3239 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3240 cast<llvm::PointerType>(LastParamTy)->getElementType());
3241 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3242 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3243 DE = DeclaredTy->element_end(),
3244 FI = FullTy->element_begin();
3245 DI != DE; ++DI, ++FI)
3246 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003247#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003248 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3249 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003250 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003251 assert(IRFunctionArgs.hasInallocaArg());
3252 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003253 }
3254
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003255 if (!CallArgs.getCleanupsToDeactivate().empty())
3256 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3257
Chris Lattner4ca97c32009-06-13 00:26:38 +00003258 // If the callee is a bitcast of a function to a varargs pointer to function
3259 // type, check to see if we can remove the bitcast. This handles some cases
3260 // with unprototyped functions.
3261 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
3262 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003263 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
3264 llvm::FunctionType *CurFT =
Chris Lattner4ca97c32009-06-13 00:26:38 +00003265 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2192fe52011-07-18 04:24:23 +00003266 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump11289f42009-09-09 15:08:12 +00003267
Chris Lattner4ca97c32009-06-13 00:26:38 +00003268 if (CE->getOpcode() == llvm::Instruction::BitCast &&
3269 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattner4c8da962009-06-23 01:38:41 +00003270 ActualFT->getNumParams() == CurFT->getNumParams() &&
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003271 ActualFT->getNumParams() == IRCallArgs.size() &&
Fariborz Jahaniancf7f66f2011-03-01 17:28:13 +00003272 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner4ca97c32009-06-13 00:26:38 +00003273 bool ArgsMatch = true;
3274 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
3275 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
3276 ArgsMatch = false;
3277 break;
3278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279
Chris Lattner4ca97c32009-06-13 00:26:38 +00003280 // Strip the cast if we can get away with it. This is a nice cleanup,
3281 // but also allows us to inline the function at -O0 if it is marked
3282 // always_inline.
3283 if (ArgsMatch)
3284 Callee = CalleeF;
3285 }
3286 }
Mike Stump11289f42009-09-09 15:08:12 +00003287
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003288 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
3289 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
3290 // Inalloca argument can have different type.
3291 if (IRFunctionArgs.hasInallocaArg() &&
3292 i == IRFunctionArgs.getInallocaArgNo())
3293 continue;
3294 if (i < IRFuncTy->getNumParams())
3295 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
3296 }
3297
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003298 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00003299 CodeGen::AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003300 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
3301 CallingConv, true);
Bill Wendling3087d022012-12-07 23:17:26 +00003302 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00003303 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00003304
Craig Topper8a13c412014-05-21 05:09:00 +00003305 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling5e85be42012-12-30 10:32:17 +00003306 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
Reid Klecknere7b3f7c2015-02-11 00:00:21 +00003307 llvm::Attribute::NoUnwind) ||
3308 currentFunctionUsesSEHTry())
John McCallbd309292010-07-06 01:34:17 +00003309 InvokeDest = getInvokeDest();
3310
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003311 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00003312 if (!InvokeDest) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003313 CS = Builder.CreateCall(Callee, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003314 } else {
3315 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003316 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
Daniel Dunbar12347492009-02-23 17:26:39 +00003317 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003318 }
Chris Lattnere70a0072010-06-29 16:40:28 +00003319 if (callOrInvoke)
David Chisnallff5f88c2010-05-02 13:41:58 +00003320 *callOrInvoke = CS.getInstruction();
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00003321
Peter Collingbourne41af7c22014-05-20 17:12:51 +00003322 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
3323 !CS.hasFnAttr(llvm::Attribute::NoInline))
3324 Attrs =
3325 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3326 llvm::Attribute::AlwaysInline);
3327
Reid Klecknera5930002015-02-11 21:40:48 +00003328 // Disable inlining inside SEH __try blocks.
Reid Kleckner11c033e2015-02-12 23:40:45 +00003329 if (isSEHTryScope())
Reid Klecknera5930002015-02-11 21:40:48 +00003330 Attrs =
3331 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
3332 llvm::Attribute::NoInline);
3333
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003334 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00003335 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003336
Dan Gohman515a60d2012-02-16 00:57:37 +00003337 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3338 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003339 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003340 AddObjCARCExceptionMetadata(CS.getInstruction());
3341
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003342 // If the call doesn't return, finish the basic block and clear the
3343 // insertion point; this allows the rest of IRgen to discard
3344 // unreachable code.
3345 if (CS.doesNotReturn()) {
3346 Builder.CreateUnreachable();
3347 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003348
Mike Stump18bb9282009-05-16 07:57:57 +00003349 // FIXME: For now, emit a dummy basic block because expr emitters in
3350 // generally are not ready to handle emitting expressions at unreachable
3351 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003352 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00003353
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003354 // Return a reasonable RValue.
3355 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00003356 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00003357
3358 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00003359 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar613855c2008-09-09 23:27:19 +00003360 CI->setName("call");
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00003361
John McCall31168b02011-06-15 23:02:42 +00003362 // Emit any writebacks immediately. Arguably this should happen
3363 // after any return-value munging.
3364 if (CallArgs.hasWritebacks())
3365 emitWritebacks(*this, CallArgs);
3366
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003367 // The stack cleanup for inalloca arguments has to run out of the normal
3368 // lexical order, so deactivate it and run it manually here.
3369 CallArgs.freeArgumentMemory(*this);
3370
Hal Finkelee90a222014-09-26 05:04:30 +00003371 RValue Ret = [&] {
3372 switch (RetAI.getKind()) {
3373 case ABIArgInfo::InAlloca:
3374 case ABIArgInfo::Indirect:
3375 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbard3674e62008-09-11 01:48:57 +00003376
Hal Finkelee90a222014-09-26 05:04:30 +00003377 case ABIArgInfo::Ignore:
3378 // If we are ignoring an argument that had a result, make sure to
3379 // construct the appropriate return value for our caller.
3380 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003381
Hal Finkelee90a222014-09-26 05:04:30 +00003382 case ABIArgInfo::Extend:
3383 case ABIArgInfo::Direct: {
3384 llvm::Type *RetIRTy = ConvertType(RetTy);
3385 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
3386 switch (getEvaluationKind(RetTy)) {
3387 case TEK_Complex: {
3388 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
3389 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
3390 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003391 }
Hal Finkelee90a222014-09-26 05:04:30 +00003392 case TEK_Aggregate: {
3393 llvm::Value *DestPtr = ReturnValue.getValue();
3394 bool DestIsVolatile = ReturnValue.isVolatile();
3395
3396 if (!DestPtr) {
3397 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3398 DestIsVolatile = false;
3399 }
3400 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
3401 return RValue::getAggregate(DestPtr);
3402 }
3403 case TEK_Scalar: {
3404 // If the argument doesn't match, perform a bitcast to coerce it. This
3405 // can happen due to trivial type mismatches.
3406 llvm::Value *V = CI;
3407 if (V->getType() != RetIRTy)
3408 V = Builder.CreateBitCast(V, RetIRTy);
3409 return RValue::get(V);
3410 }
3411 }
3412 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003413 }
Hal Finkelee90a222014-09-26 05:04:30 +00003414
3415 llvm::Value *DestPtr = ReturnValue.getValue();
3416 bool DestIsVolatile = ReturnValue.isVolatile();
3417
3418 if (!DestPtr) {
3419 DestPtr = CreateMemTemp(RetTy, "coerce");
3420 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00003421 }
Hal Finkelee90a222014-09-26 05:04:30 +00003422
3423 // If the value is offset in memory, apply the offset now.
3424 llvm::Value *StorePtr = DestPtr;
3425 if (unsigned Offs = RetAI.getDirectOffset()) {
3426 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3427 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
3428 StorePtr = Builder.CreateBitCast(StorePtr,
3429 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
John McCall47fb9502013-03-07 21:37:08 +00003430 }
Hal Finkelee90a222014-09-26 05:04:30 +00003431 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
3432
3433 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003434 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003435
Hal Finkelee90a222014-09-26 05:04:30 +00003436 case ABIArgInfo::Expand:
3437 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00003438 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003439
Hal Finkelee90a222014-09-26 05:04:30 +00003440 llvm_unreachable("Unhandled ABIArgInfo::Kind");
3441 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003442
Hal Finkelee90a222014-09-26 05:04:30 +00003443 if (Ret.isScalar() && TargetDecl) {
3444 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
3445 llvm::Value *OffsetValue = nullptr;
3446 if (const auto *Offset = AA->getOffset())
3447 OffsetValue = EmitScalarExpr(Offset);
3448
3449 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
3450 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
3451 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
3452 OffsetValue);
3453 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00003454 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00003455
Hal Finkelee90a222014-09-26 05:04:30 +00003456 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003457}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00003458
3459/* VarArg handling */
3460
3461llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3462 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3463}