blob: d0849d3263ab589fc6b0c50d5f8fceb7486a73cf [file] [log] [blame]
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar0dbe2272008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnerce933992010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCallde5d3c72012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Mark Lacey8b549992013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000028#include "llvm/IR/Attributes.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070029#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/InlineAsm.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070032#include "llvm/IR/Intrinsics.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000033#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000034using namespace clang;
35using namespace CodeGen;
36
37/***/
38
John McCall04a67a62010-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 Gregorf813a2c2010-05-18 16:57:00 +000044 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davise8519c32013-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 Korobeynikov414d8962011-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 Benyei38980082012-12-25 08:53:55 +000049 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik52fc3142010-09-03 01:29:35 +000050 // TODO: add support for CC_X86Pascal to llvm
John McCall04a67a62010-02-05 21:31:56 +000051 }
52}
53
John McCall0b0ef0a2010-02-24 07:14:12 +000054/// Derives the 'this' type for codegen purposes, i.e. ignoring method
55/// qualification.
56/// FIXME: address space qualification?
John McCallead608a2010-02-26 00:48:12 +000057static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
58 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
59 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000060}
61
John McCall0b0ef0a2010-02-24 07:14:12 +000062/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000063static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
64 return MD->getType()->getCanonicalTypeUnqualified()
65 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-02-24 07:14:12 +000066}
67
68/// Returns the "extra-canonicalized" return type, which discards
69/// qualifiers on the return type. Codegen doesn't care about them,
70/// and it makes ABI code a little easier to be able to assume that
71/// all parameter and return types are top-level unqualified.
John McCallead608a2010-02-26 00:48:12 +000072static CanQualType GetReturnType(QualType RetTy) {
73 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000074}
75
John McCall0f3d0972012-07-07 06:41:13 +000076/// Arrange the argument and result information for a value of the given
77/// unprototyped freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +000078const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +000079CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCallde5d3c72012-02-17 03:33:10 +000080 // When translating an unprototyped function type, always use a
81 // variadic type.
Stephen Hines651f13c2014-04-23 16:59:28 -070082 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
83 false, None, FTNP->getExtInfo(),
84 RequiredArgs(0));
John McCall0b0ef0a2010-02-24 07:14:12 +000085}
86
John McCall0f3d0972012-07-07 06:41:13 +000087/// Arrange the LLVM function layout for a value of the given function
88/// type, on top of any implicit parameters already stored. Use the
89/// given ExtInfo instead of the ExtInfo from the function type.
90static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
Stephen Hines651f13c2014-04-23 16:59:28 -070091 bool IsInstanceMethod,
John McCall0f3d0972012-07-07 06:41:13 +000092 SmallVectorImpl<CanQualType> &prefix,
93 CanQual<FunctionProtoType> FTP,
94 FunctionType::ExtInfo extInfo) {
95 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbar541b63b2009-02-02 23:23:47 +000096 // FIXME: Kill copy.
Stephen Hines651f13c2014-04-23 16:59:28 -070097 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
98 prefix.push_back(FTP->getParamType(i));
99 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
100 return CGT.arrangeLLVMFunctionInfo(resultType, IsInstanceMethod, prefix,
101 extInfo, required);
John McCall0f3d0972012-07-07 06:41:13 +0000102}
103
104/// Arrange the argument and result information for a free function (i.e.
105/// not a C++ or ObjC instance method) of the given type.
106static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
107 SmallVectorImpl<CanQualType> &prefix,
108 CanQual<FunctionProtoType> FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700109 return arrangeLLVMFunctionInfo(CGT, false, prefix, FTP, FTP->getExtInfo());
John McCall0f3d0972012-07-07 06:41:13 +0000110}
111
John McCall0f3d0972012-07-07 06:41:13 +0000112/// Arrange the argument and result information for a free function (i.e.
113/// not a C++ or ObjC instance method) of the given type.
114static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
115 SmallVectorImpl<CanQualType> &prefix,
116 CanQual<FunctionProtoType> FTP) {
117 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Stephen Hines651f13c2014-04-23 16:59:28 -0700118 return arrangeLLVMFunctionInfo(CGT, true, prefix, FTP, extInfo);
John McCall0b0ef0a2010-02-24 07:14:12 +0000119}
120
John McCallde5d3c72012-02-17 03:33:10 +0000121/// Arrange the argument and result information for a value of the
John McCall0f3d0972012-07-07 06:41:13 +0000122/// given freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +0000123const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000124CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCallde5d3c72012-02-17 03:33:10 +0000125 SmallVector<CanQualType, 16> argTypes;
John McCall0f3d0972012-07-07 06:41:13 +0000126 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000127}
128
Stephen Hines651f13c2014-04-23 16:59:28 -0700129static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000130 // Set the appropriate calling convention for the Function.
131 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000132 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000133
134 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000135 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000136
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000137 if (D->hasAttr<ThisCallAttr>())
138 return CC_X86ThisCall;
139
Dawn Perchik52fc3142010-09-03 01:29:35 +0000140 if (D->hasAttr<PascalAttr>())
141 return CC_X86Pascal;
142
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000143 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
144 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
145
Derek Schuff263366f2012-10-16 22:30:41 +0000146 if (D->hasAttr<PnaclCallAttr>())
147 return CC_PnaclCall;
148
Guy Benyei38980082012-12-25 08:53:55 +0000149 if (D->hasAttr<IntelOclBiccAttr>())
150 return CC_IntelOclBicc;
151
Stephen Hines651f13c2014-04-23 16:59:28 -0700152 if (D->hasAttr<MSABIAttr>())
153 return IsWindows ? CC_C : CC_X86_64Win64;
154
155 if (D->hasAttr<SysVABIAttr>())
156 return IsWindows ? CC_X86_64SysV : CC_C;
157
John McCall04a67a62010-02-05 21:31:56 +0000158 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000159}
160
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700161static bool isAAPCSVFP(const CGFunctionInfo &FI, const TargetInfo &Target) {
162 switch (FI.getEffectiveCallingConvention()) {
163 case llvm::CallingConv::C:
164 switch (Target.getTriple().getEnvironment()) {
165 case llvm::Triple::EABIHF:
166 case llvm::Triple::GNUEABIHF:
167 return true;
168 default:
169 return false;
170 }
171 case llvm::CallingConv::ARM_AAPCS_VFP:
172 return true;
173 default:
174 return false;
175 }
176}
177
John McCallde5d3c72012-02-17 03:33:10 +0000178/// Arrange the argument and result information for a call to an
179/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000180/// (Zero value of RD means we don't have any meaningful "this" argument type,
181/// so fall back to a generic pointer type).
John McCallde5d3c72012-02-17 03:33:10 +0000182/// The member function must be an ordinary function, i.e. not a
183/// constructor or destructor.
184const CGFunctionInfo &
185CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
186 const FunctionProtoType *FTP) {
187 SmallVector<CanQualType, 16> argTypes;
John McCall0b0ef0a2010-02-24 07:14:12 +0000188
Anders Carlsson375c31c2009-10-03 19:43:08 +0000189 // Add the 'this' pointer.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000190 if (RD)
191 argTypes.push_back(GetThisType(Context, RD));
192 else
193 argTypes.push_back(Context.VoidPtrTy);
John McCall0b0ef0a2010-02-24 07:14:12 +0000194
John McCall0f3d0972012-07-07 06:41:13 +0000195 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000196 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000197}
198
John McCallde5d3c72012-02-17 03:33:10 +0000199/// Arrange the argument and result information for a declaration or
200/// definition of the given C++ non-static member function. The
201/// member function must be an ordinary function, i.e. not a
202/// constructor or destructor.
203const CGFunctionInfo &
204CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramere5753592013-09-09 14:48:42 +0000205 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCallfc400282010-09-03 01:26:39 +0000206 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
207
John McCallde5d3c72012-02-17 03:33:10 +0000208 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000209
John McCallde5d3c72012-02-17 03:33:10 +0000210 if (MD->isInstance()) {
211 // The abstract case is perfectly fine.
Mark Lacey25296602013-10-02 20:35:23 +0000212 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000213 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCallde5d3c72012-02-17 03:33:10 +0000214 }
215
John McCall0f3d0972012-07-07 06:41:13 +0000216 return arrangeFreeFunctionType(prototype);
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000217}
218
John McCallde5d3c72012-02-17 03:33:10 +0000219/// Arrange the argument and result information for a declaration
220/// or definition to the given constructor variant.
221const CGFunctionInfo &
222CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
223 CXXCtorType ctorKind) {
224 SmallVector<CanQualType, 16> argTypes;
225 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000226
227 GlobalDecl GD(D, ctorKind);
228 CanQualType resultType =
229 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000230
John McCall4c40d982010-08-31 07:33:07 +0000231 CanQual<FunctionProtoType> FTP = GetFormalType(D);
232
233 // Add the formal parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -0700234 for (unsigned i = 0, e = FTP->getNumParams(); i != e; ++i)
235 argTypes.push_back(FTP->getParamType(i));
236
237 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
238
239 RequiredArgs required =
240 (D->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
John McCall4c40d982010-08-31 07:33:07 +0000241
John McCall0f3d0972012-07-07 06:41:13 +0000242 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Stephen Hines651f13c2014-04-23 16:59:28 -0700243 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo, required);
244}
245
246/// Arrange a call to a C++ method, passing the given arguments.
247const CGFunctionInfo &
248CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
249 const CXXConstructorDecl *D,
250 CXXCtorType CtorKind,
251 unsigned ExtraArgs) {
252 // FIXME: Kill copy.
253 SmallVector<CanQualType, 16> ArgTypes;
254 for (CallArgList::const_iterator i = args.begin(), e = args.end(); i != e;
255 ++i)
256 ArgTypes.push_back(Context.getCanonicalParamType(i->Ty));
257
258 CanQual<FunctionProtoType> FPT = GetFormalType(D);
259 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
260 GlobalDecl GD(D, CtorKind);
261 CanQualType ResultType =
262 TheCXXABI.HasThisReturn(GD) ? ArgTypes.front() : Context.VoidTy;
263
264 FunctionType::ExtInfo Info = FPT->getExtInfo();
265 return arrangeLLVMFunctionInfo(ResultType, true, ArgTypes, Info, Required);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000266}
267
John McCallde5d3c72012-02-17 03:33:10 +0000268/// Arrange the argument and result information for a declaration,
269/// definition, or call to the given destructor variant. It so
270/// happens that all three cases produce the same information.
271const CGFunctionInfo &
272CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
273 CXXDtorType dtorKind) {
274 SmallVector<CanQualType, 2> argTypes;
275 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000276
277 GlobalDecl GD(D, dtorKind);
278 CanQualType resultType =
279 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall0b0ef0a2010-02-24 07:14:12 +0000280
John McCallde5d3c72012-02-17 03:33:10 +0000281 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall4c40d982010-08-31 07:33:07 +0000282
283 CanQual<FunctionProtoType> FTP = GetFormalType(D);
Stephen Hines651f13c2014-04-23 16:59:28 -0700284 assert(FTP->getNumParams() == 0 && "dtor with formal parameters");
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000285 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall4c40d982010-08-31 07:33:07 +0000286
John McCall0f3d0972012-07-07 06:41:13 +0000287 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
Stephen Hines651f13c2014-04-23 16:59:28 -0700288 return arrangeLLVMFunctionInfo(resultType, true, argTypes, extInfo,
John McCall0f3d0972012-07-07 06:41:13 +0000289 RequiredArgs::All);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000290}
291
John McCallde5d3c72012-02-17 03:33:10 +0000292/// Arrange the argument and result information for the declaration or
293/// definition of the given function.
294const CGFunctionInfo &
295CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattner3eb67ca2009-05-12 20:27:19 +0000296 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000297 if (MD->isInstance())
John McCallde5d3c72012-02-17 03:33:10 +0000298 return arrangeCXXMethodDeclaration(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
John McCallead608a2010-02-26 00:48:12 +0000300 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCallde5d3c72012-02-17 03:33:10 +0000301
John McCallead608a2010-02-26 00:48:12 +0000302 assert(isa<FunctionType>(FTy));
John McCallde5d3c72012-02-17 03:33:10 +0000303
304 // When declaring a function without a prototype, always use a
305 // non-variadic type.
306 if (isa<FunctionNoProtoType>(FTy)) {
307 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700308 return arrangeLLVMFunctionInfo(noProto->getReturnType(), false, None,
Dmitri Gribenko55431692013-05-05 00:41:58 +0000309 noProto->getExtInfo(), RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000310 }
311
John McCallead608a2010-02-26 00:48:12 +0000312 assert(isa<FunctionProtoType>(FTy));
John McCall0f3d0972012-07-07 06:41:13 +0000313 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000314}
315
John McCallde5d3c72012-02-17 03:33:10 +0000316/// Arrange the argument and result information for the declaration or
317/// definition of an Objective-C method.
318const CGFunctionInfo &
319CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
320 // It happens that this is the same as a call with no optional
321 // arguments, except also using the formal 'self' type.
322 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
323}
324
325/// Arrange the argument and result information for the function type
326/// through which to perform a send to the given Objective-C method,
327/// using the given receiver type. The receiver type is not always
328/// the 'self' type of the method or even an Objective-C pointer type.
329/// This is *not* the right method for actually performing such a
330/// message send, due to the possibility of optional arguments.
331const CGFunctionInfo &
332CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
333 QualType receiverType) {
334 SmallVector<CanQualType, 16> argTys;
335 argTys.push_back(Context.getCanonicalParamType(receiverType));
336 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000337 // FIXME: Kill copy?
Stephen Hines651f13c2014-04-23 16:59:28 -0700338 for (const auto *I : MD->params()) {
339 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall0b0ef0a2010-02-24 07:14:12 +0000340 }
John McCallf85e1932011-06-15 23:02:42 +0000341
342 FunctionType::ExtInfo einfo;
Stephen Hines651f13c2014-04-23 16:59:28 -0700343 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
344 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCallf85e1932011-06-15 23:02:42 +0000345
David Blaikie4e4d0842012-03-11 07:00:24 +0000346 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000347 MD->hasAttr<NSReturnsRetainedAttr>())
348 einfo = einfo.withProducesResult(true);
349
John McCallde5d3c72012-02-17 03:33:10 +0000350 RequiredArgs required =
351 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
352
Stephen Hines651f13c2014-04-23 16:59:28 -0700353 return arrangeLLVMFunctionInfo(GetReturnType(MD->getReturnType()), false,
354 argTys, einfo, required);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000355}
356
John McCallde5d3c72012-02-17 03:33:10 +0000357const CGFunctionInfo &
358CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000359 // FIXME: Do we need to handle ObjCMethodDecl?
360 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000361
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000362 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000363 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000364
365 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000366 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000367
John McCallde5d3c72012-02-17 03:33:10 +0000368 return arrangeFunctionDeclaration(FD);
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000369}
370
John McCalle56bb362012-12-07 07:03:17 +0000371/// Arrange a call as unto a free function, except possibly with an
372/// additional number of formal parameters considered required.
373static const CGFunctionInfo &
374arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000375 CodeGenModule &CGM,
John McCalle56bb362012-12-07 07:03:17 +0000376 const CallArgList &args,
377 const FunctionType *fnType,
378 unsigned numExtraRequiredArgs) {
379 assert(args.size() >= numExtraRequiredArgs);
380
381 // In most cases, there are no optional arguments.
382 RequiredArgs required = RequiredArgs::All;
383
384 // If we have a variadic prototype, the required arguments are the
385 // extra prefix plus the arguments in the prototype.
386 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
387 if (proto->isVariadic())
Stephen Hines651f13c2014-04-23 16:59:28 -0700388 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCalle56bb362012-12-07 07:03:17 +0000389
390 // If we don't have a prototype at all, but we're supposed to
391 // explicitly use the variadic convention for unprototyped calls,
392 // treat all of the arguments as required but preserve the nominal
393 // possibility of variadics.
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000394 } else if (CGM.getTargetCodeGenInfo()
395 .isNoProtoCallVariadic(args,
396 cast<FunctionNoProtoType>(fnType))) {
John McCalle56bb362012-12-07 07:03:17 +0000397 required = RequiredArgs(args.size());
398 }
399
Stephen Hines651f13c2014-04-23 16:59:28 -0700400 return CGT.arrangeFreeFunctionCall(fnType->getReturnType(), args,
John McCalle56bb362012-12-07 07:03:17 +0000401 fnType->getExtInfo(), required);
402}
403
John McCallde5d3c72012-02-17 03:33:10 +0000404/// Figure out the rules for calling a function with the given formal
405/// type using the given arguments. The arguments are necessary
406/// because the function might be unprototyped, in which case it's
407/// target-dependent in crazy ways.
408const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000409CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
410 const FunctionType *fnType) {
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000411 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 0);
John McCalle56bb362012-12-07 07:03:17 +0000412}
John McCallde5d3c72012-02-17 03:33:10 +0000413
John McCalle56bb362012-12-07 07:03:17 +0000414/// A block function call is essentially a free-function call with an
415/// extra implicit argument.
416const CGFunctionInfo &
417CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
418 const FunctionType *fnType) {
Mark Laceyc3f7fd62013-10-10 20:57:00 +0000419 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1);
John McCallde5d3c72012-02-17 03:33:10 +0000420}
421
422const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000423CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
424 const CallArgList &args,
425 FunctionType::ExtInfo info,
426 RequiredArgs required) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000427 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000428 SmallVector<CanQualType, 16> argTypes;
429 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar725ad312009-01-31 02:19:00 +0000430 i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000431 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
Stephen Hines651f13c2014-04-23 16:59:28 -0700432 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes,
433 info, required);
John McCall0f3d0972012-07-07 06:41:13 +0000434}
435
436/// Arrange a call to a C++ method, passing the given arguments.
437const CGFunctionInfo &
438CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
439 const FunctionProtoType *FPT,
440 RequiredArgs required) {
441 // FIXME: Kill copy.
442 SmallVector<CanQualType, 16> argTypes;
443 for (CallArgList::const_iterator i = args.begin(), e = args.end();
444 i != e; ++i)
445 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
446
447 FunctionType::ExtInfo info = FPT->getExtInfo();
Stephen Hines651f13c2014-04-23 16:59:28 -0700448 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getReturnType()), true,
John McCall0f3d0972012-07-07 06:41:13 +0000449 argTypes, info, required);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000450}
451
Stephen Hines651f13c2014-04-23 16:59:28 -0700452const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
453 QualType resultType, const FunctionArgList &args,
454 const FunctionType::ExtInfo &info, bool isVariadic) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000455 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000456 SmallVector<CanQualType, 16> argTypes;
457 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000458 i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000459 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
460
461 RequiredArgs required =
462 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
Stephen Hines651f13c2014-04-23 16:59:28 -0700463 return arrangeLLVMFunctionInfo(GetReturnType(resultType), false, argTypes, info,
John McCall0f3d0972012-07-07 06:41:13 +0000464 required);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000465}
466
John McCallde5d3c72012-02-17 03:33:10 +0000467const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700468 return arrangeLLVMFunctionInfo(getContext().VoidTy, false, None,
John McCall0f3d0972012-07-07 06:41:13 +0000469 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalld26bc762011-03-09 04:27:21 +0000470}
471
John McCallde5d3c72012-02-17 03:33:10 +0000472/// Arrange the argument and result information for an abstract value
473/// of a given function type. This is the method which all of the
474/// above functions ultimately defer to.
475const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000476CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Stephen Hines651f13c2014-04-23 16:59:28 -0700477 bool IsInstanceMethod,
John McCall0f3d0972012-07-07 06:41:13 +0000478 ArrayRef<CanQualType> argTypes,
479 FunctionType::ExtInfo info,
480 RequiredArgs required) {
John McCallead608a2010-02-26 00:48:12 +0000481#ifndef NDEBUG
John McCallde5d3c72012-02-17 03:33:10 +0000482 for (ArrayRef<CanQualType>::const_iterator
483 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCallead608a2010-02-26 00:48:12 +0000484 assert(I->isCanonicalAsParam());
485#endif
486
John McCallde5d3c72012-02-17 03:33:10 +0000487 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000488
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000489 // Lookup or create unique function info.
490 llvm::FoldingSetNodeID ID;
Stephen Hines651f13c2014-04-23 16:59:28 -0700491 CGFunctionInfo::Profile(ID, IsInstanceMethod, info, required, resultType,
492 argTypes);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000493
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700494 void *insertPos = nullptr;
John McCallde5d3c72012-02-17 03:33:10 +0000495 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000496 if (FI)
497 return *FI;
498
John McCallde5d3c72012-02-17 03:33:10 +0000499 // Construct the function info. We co-allocate the ArgInfos.
Stephen Hines651f13c2014-04-23 16:59:28 -0700500 FI = CGFunctionInfo::create(CC, IsInstanceMethod, info, resultType, argTypes,
501 required);
John McCallde5d3c72012-02-17 03:33:10 +0000502 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000503
John McCallde5d3c72012-02-17 03:33:10 +0000504 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
505 assert(inserted && "Recursively being processed?");
Chris Lattner71305cc2011-07-15 05:16:14 +0000506
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000507 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000508 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000509
Chris Lattner800588f2010-07-29 06:26:06 +0000510 // Loop over all of the computed argument and return value info. If any of
511 // them are direct or extend without a specified coerce type, specify the
512 // default now.
John McCallde5d3c72012-02-17 03:33:10 +0000513 ABIArgInfo &retInfo = FI->getReturnInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700514 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCallde5d3c72012-02-17 03:33:10 +0000515 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000516
Stephen Hines651f13c2014-04-23 16:59:28 -0700517 for (auto &I : FI->arguments())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700518 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Stephen Hines651f13c2014-04-23 16:59:28 -0700519 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000520
John McCallde5d3c72012-02-17 03:33:10 +0000521 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
522 assert(erased && "Not in set?");
Chris Lattnerd26c0712011-07-15 06:41:05 +0000523
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000524 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000525}
526
John McCallde5d3c72012-02-17 03:33:10 +0000527CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Stephen Hines651f13c2014-04-23 16:59:28 -0700528 bool IsInstanceMethod,
John McCallde5d3c72012-02-17 03:33:10 +0000529 const FunctionType::ExtInfo &info,
530 CanQualType resultType,
531 ArrayRef<CanQualType> argTypes,
532 RequiredArgs required) {
533 void *buffer = operator new(sizeof(CGFunctionInfo) +
534 sizeof(ArgInfo) * (argTypes.size() + 1));
535 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
536 FI->CallingConvention = llvmCC;
537 FI->EffectiveCallingConvention = llvmCC;
538 FI->ASTCallingConvention = info.getCC();
Stephen Hines651f13c2014-04-23 16:59:28 -0700539 FI->InstanceMethod = IsInstanceMethod;
John McCallde5d3c72012-02-17 03:33:10 +0000540 FI->NoReturn = info.getNoReturn();
541 FI->ReturnsRetained = info.getProducesResult();
542 FI->Required = required;
543 FI->HasRegParm = info.getHasRegParm();
544 FI->RegParm = info.getRegParm();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700545 FI->ArgStruct = nullptr;
John McCallde5d3c72012-02-17 03:33:10 +0000546 FI->NumArgs = argTypes.size();
547 FI->getArgsBuffer()[0].type = resultType;
548 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
549 FI->getArgsBuffer()[i + 1].type = argTypes[i];
550 return FI;
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000551}
552
553/***/
554
John McCall42e06112011-05-15 02:19:42 +0000555void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000556 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000557 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
558 uint64_t NumElts = AT->getSize().getZExtValue();
559 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
560 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000561 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000562 const RecordDecl *RD = RT->getDecl();
563 assert(!RD->hasFlexibleArrayMember() &&
564 "Cannot expand structure with flexible array.");
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000565 if (RD->isUnion()) {
566 // Unions can be here only in degenerative cases - all the fields are same
567 // after flattening. Thus we have to use the "largest" field.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700568 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000569 CharUnits UnionSize = CharUnits::Zero();
570
Stephen Hines651f13c2014-04-23 16:59:28 -0700571 for (const auto *FD : RD->fields()) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000572 assert(!FD->isBitField() &&
573 "Cannot expand structure with bit-field members.");
574 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
575 if (UnionSize < FieldSize) {
576 UnionSize = FieldSize;
577 LargestFD = FD;
578 }
579 }
580 if (LargestFD)
581 GetExpandedTypes(LargestFD->getType(), expandedTypes);
582 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700583 for (const auto *I : RD->fields()) {
584 assert(!I->isBitField() &&
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000585 "Cannot expand structure with bit-field members.");
Stephen Hines651f13c2014-04-23 16:59:28 -0700586 GetExpandedTypes(I->getType(), expandedTypes);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000587 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000588 }
589 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
590 llvm::Type *EltTy = ConvertType(CT->getElementType());
591 expandedTypes.push_back(EltTy);
592 expandedTypes.push_back(EltTy);
593 } else
594 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar56273772008-09-17 00:51:38 +0000595}
596
Mike Stump1eb44332009-09-09 15:08:12 +0000597llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000598CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
599 llvm::Function::arg_iterator AI) {
Mike Stump1eb44332009-09-09 15:08:12 +0000600 assert(LV.isSimple() &&
601 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000602
Bob Wilson194f06a2011-08-03 05:58:22 +0000603 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
604 unsigned NumElts = AT->getSize().getZExtValue();
605 QualType EltTy = AT->getElementType();
606 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman377ecc72012-04-16 03:54:45 +0000607 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilson194f06a2011-08-03 05:58:22 +0000608 LValue LV = MakeAddrLValue(EltAddr, EltTy);
609 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar56273772008-09-17 00:51:38 +0000610 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000611 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000612 RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000613 if (RD->isUnion()) {
614 // Unions can be here only in degenerative cases - all the fields are same
615 // after flattening. Thus we have to use the "largest" field.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700616 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000617 CharUnits UnionSize = CharUnits::Zero();
Bob Wilson194f06a2011-08-03 05:58:22 +0000618
Stephen Hines651f13c2014-04-23 16:59:28 -0700619 for (const auto *FD : RD->fields()) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000620 assert(!FD->isBitField() &&
621 "Cannot expand structure with bit-field members.");
622 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
623 if (UnionSize < FieldSize) {
624 UnionSize = FieldSize;
625 LargestFD = FD;
626 }
627 }
628 if (LargestFD) {
629 // FIXME: What are the right qualifiers here?
Eli Friedman377ecc72012-04-16 03:54:45 +0000630 LValue SubLV = EmitLValueForField(LV, LargestFD);
631 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000632 }
633 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700634 for (const auto *FD : RD->fields()) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000635 QualType FT = FD->getType();
636
637 // FIXME: What are the right qualifiers here?
Eli Friedman377ecc72012-04-16 03:54:45 +0000638 LValue SubLV = EmitLValueForField(LV, FD);
639 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000640 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000641 }
642 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
643 QualType EltTy = CT->getElementType();
Eli Friedman377ecc72012-04-16 03:54:45 +0000644 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilson194f06a2011-08-03 05:58:22 +0000645 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman377ecc72012-04-16 03:54:45 +0000646 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilson194f06a2011-08-03 05:58:22 +0000647 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
648 } else {
649 EmitStoreThroughLValue(RValue::get(AI), LV);
650 ++AI;
Daniel Dunbar56273772008-09-17 00:51:38 +0000651 }
652
653 return AI;
654}
655
Chris Lattnere7bb7772010-06-27 06:04:18 +0000656/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-06-27 05:56:15 +0000657/// accessing some number of bytes out of it, try to gep into the struct to get
658/// at its inner goodness. Dive as deep as possible without entering an element
659/// with an in-memory size smaller than DstSize.
660static llvm::Value *
Chris Lattnere7bb7772010-06-27 06:04:18 +0000661EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000662 llvm::StructType *SrcSTy,
Chris Lattnere7bb7772010-06-27 06:04:18 +0000663 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000664 // We can't dive into a zero-element struct.
665 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000666
Chris Lattner2acc6e32011-07-18 04:24:23 +0000667 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000668
Chris Lattner08dd2a02010-06-27 05:56:15 +0000669 // If the first elt is at least as large as what we're looking for, or if the
670 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000671 uint64_t FirstEltSize =
Micah Villmow25a6a842012-10-08 16:25:52 +0000672 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000673 if (FirstEltSize < DstSize &&
Micah Villmow25a6a842012-10-08 16:25:52 +0000674 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner08dd2a02010-06-27 05:56:15 +0000675 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000676
Chris Lattner08dd2a02010-06-27 05:56:15 +0000677 // GEP into the first element.
678 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000679
Chris Lattner08dd2a02010-06-27 05:56:15 +0000680 // If the first element is a struct, recurse.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000681 llvm::Type *SrcTy =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000682 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000683 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000684 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000685
686 return SrcPtr;
687}
688
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000689/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
690/// are either integers or pointers. This does a truncation of the value if it
691/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000692///
693/// This behaves as if the value were coerced through memory, so on big-endian
694/// targets the high bits are preserved in a truncation, while little-endian
695/// targets preserve the low bits.
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000696static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000697 llvm::Type *Ty,
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000698 CodeGenFunction &CGF) {
699 if (Val->getType() == Ty)
700 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000701
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000702 if (isa<llvm::PointerType>(Val->getType())) {
703 // If this is Pointer->Pointer avoid conversion to and from int.
704 if (isa<llvm::PointerType>(Ty))
705 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000706
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000707 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000708 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000709 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000710
Chris Lattner2acc6e32011-07-18 04:24:23 +0000711 llvm::Type *DestIntTy = Ty;
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000712 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000713 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000714
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000715 if (Val->getType() != DestIntTy) {
716 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
717 if (DL.isBigEndian()) {
718 // Preserve the high bits on big-endian targets.
719 // That is what memory coercion does.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700720 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
721 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
722
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000723 if (SrcSize > DstSize) {
724 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
725 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
726 } else {
727 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
728 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
729 }
730 } else {
731 // Little-endian targets preserve the low bits. No shifts required.
732 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
733 }
734 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000735
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000736 if (isa<llvm::PointerType>(Ty))
737 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
738 return Val;
739}
740
Chris Lattner08dd2a02010-06-27 05:56:15 +0000741
742
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000743/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
744/// a pointer to an object of type \arg Ty.
745///
746/// This safely handles the case when the src type is smaller than the
747/// destination type; in this situation the values of bits which not
748/// present in the src are undefined.
749static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000750 llvm::Type *Ty,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000751 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000752 llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000753 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000754
Chris Lattner6ae00692010-06-28 22:51:39 +0000755 // If SrcTy and Ty are the same, just do a load.
756 if (SrcTy == Ty)
757 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000758
Micah Villmow25a6a842012-10-08 16:25:52 +0000759 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000760
Chris Lattner2acc6e32011-07-18 04:24:23 +0000761 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000762 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000763 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
764 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000765
Micah Villmow25a6a842012-10-08 16:25:52 +0000766 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000767
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000768 // If the source and destination are integer or pointer types, just do an
769 // extension or truncation to the desired type.
770 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
771 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
772 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
773 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
774 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000775
Daniel Dunbarb225be42009-02-03 05:59:18 +0000776 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000777 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000778 // Generally SrcSize is never greater than DstSize, since this means we are
779 // losing bits. However, this can happen in cases where the structure has
780 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000781 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000782 // FIXME: Assert that we aren't truncating non-padding bits when have access
783 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000784 llvm::Value *Casted =
785 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000786 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
787 // FIXME: Use better alignment / avoid requiring aligned load.
788 Load->setAlignment(1);
789 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000790 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000791
Chris Lattner35b21b82010-06-27 01:06:27 +0000792 // Otherwise do coercion through memory. This is stupid, but
793 // simple.
794 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Renf51c61c2012-11-28 22:08:52 +0000795 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
796 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
797 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren060f34d2012-11-28 22:29:41 +0000798 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000799 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
800 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
801 1, false);
Chris Lattner35b21b82010-06-27 01:06:27 +0000802 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000803}
804
Eli Friedmanbadea572011-05-17 21:08:01 +0000805// Function to store a first-class aggregate into memory. We prefer to
806// store the elements rather than the aggregate to be more friendly to
807// fast-isel.
808// FIXME: Do we need to recurse here?
809static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
810 llvm::Value *DestPtr, bool DestIsVolatile,
811 bool LowAlignment) {
812 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000813 if (llvm::StructType *STy =
Eli Friedmanbadea572011-05-17 21:08:01 +0000814 dyn_cast<llvm::StructType>(Val->getType())) {
815 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
816 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
817 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
818 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
819 DestIsVolatile);
820 if (LowAlignment)
821 SI->setAlignment(1);
822 }
823 } else {
Bill Wendling08212632012-03-16 21:45:12 +0000824 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
825 if (LowAlignment)
826 SI->setAlignment(1);
Eli Friedmanbadea572011-05-17 21:08:01 +0000827 }
828}
829
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000830/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
831/// where the source and destination may have different types.
832///
833/// This safely handles the case when the src type is larger than the
834/// destination type; the upper bits of the src will be lost.
835static void CreateCoercedStore(llvm::Value *Src,
836 llvm::Value *DstPtr,
Anders Carlssond2490a92009-12-24 20:40:36 +0000837 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000838 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000839 llvm::Type *SrcTy = Src->getType();
840 llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000841 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000842 if (SrcTy == DstTy) {
843 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
844 return;
845 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000846
Micah Villmow25a6a842012-10-08 16:25:52 +0000847 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000848
Chris Lattner2acc6e32011-07-18 04:24:23 +0000849 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000850 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
851 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
852 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000853
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000854 // If the source and destination are integer or pointer types, just do an
855 // extension or truncation to the desired type.
856 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
857 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
858 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
859 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
860 return;
861 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000862
Micah Villmow25a6a842012-10-08 16:25:52 +0000863 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000864
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000865 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000866 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000867 llvm::Value *Casted =
868 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000869 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000870 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000871 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000872 // Otherwise do coercion through memory. This is stupid, but
873 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000874
875 // Generally SrcSize is never greater than DstSize, since this means we are
876 // losing bits. However, this can happen in cases where the structure has
877 // additional padding, for example due to a user specified alignment.
878 //
879 // FIXME: Assert that we aren't truncating non-padding bits when have access
880 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000881 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
882 CGF.Builder.CreateStore(Src, Tmp);
Manman Renf51c61c2012-11-28 22:08:52 +0000883 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
884 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
885 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren060f34d2012-11-28 22:29:41 +0000886 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000887 CGF.Builder.CreateMemCpy(DstCasted, Casted,
888 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
889 1, false);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000890 }
891}
892
Daniel Dunbar56273772008-09-17 00:51:38 +0000893/***/
894
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000895bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000896 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000897}
898
Stephen Hines651f13c2014-04-23 16:59:28 -0700899bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
900 return ReturnTypeUsesSRet(FI) &&
901 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
902}
903
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000904bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
905 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
906 switch (BT->getKind()) {
907 default:
908 return false;
909 case BuiltinType::Float:
John McCall64aa4b32013-04-16 22:48:15 +0000910 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000911 case BuiltinType::Double:
John McCall64aa4b32013-04-16 22:48:15 +0000912 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000913 case BuiltinType::LongDouble:
John McCall64aa4b32013-04-16 22:48:15 +0000914 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000915 }
916 }
917
918 return false;
919}
920
Anders Carlssoneea64802011-10-31 16:27:11 +0000921bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
922 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
923 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
924 if (BT->getKind() == BuiltinType::LongDouble)
John McCall64aa4b32013-04-16 22:48:15 +0000925 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlssoneea64802011-10-31 16:27:11 +0000926 }
927 }
928
929 return false;
930}
931
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000932llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallde5d3c72012-02-17 03:33:10 +0000933 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
934 return GetFunctionType(FI);
John McCallc0bf4622010-02-23 00:48:20 +0000935}
936
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000937llvm::FunctionType *
John McCallde5d3c72012-02-17 03:33:10 +0000938CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner71305cc2011-07-15 05:16:14 +0000939
940 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
941 assert(Inserted && "Recursively being processed?");
942
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700943 bool SwapThisWithSRet = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000944 SmallVector<llvm::Type*, 8> argTypes;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700945 llvm::Type *resultType = nullptr;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000946
John McCall42e06112011-05-15 02:19:42 +0000947 const ABIArgInfo &retAI = FI.getReturnInfo();
948 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000949 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000950 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000951
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000952 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000953 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000954 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000955 break;
956
Stephen Hines651f13c2014-04-23 16:59:28 -0700957 case ABIArgInfo::InAlloca:
958 if (retAI.getInAllocaSRet()) {
959 // sret things on win32 aren't void, they return the sret pointer.
960 QualType ret = FI.getReturnType();
961 llvm::Type *ty = ConvertType(ret);
962 unsigned addressSpace = Context.getTargetAddressSpace(ret);
963 resultType = llvm::PointerType::get(ty, addressSpace);
964 } else {
965 resultType = llvm::Type::getVoidTy(getLLVMContext());
966 }
967 break;
968
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000969 case ABIArgInfo::Indirect: {
John McCall42e06112011-05-15 02:19:42 +0000970 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
971 resultType = llvm::Type::getVoidTy(getLLVMContext());
972
973 QualType ret = FI.getReturnType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000974 llvm::Type *ty = ConvertType(ret);
John McCall42e06112011-05-15 02:19:42 +0000975 unsigned addressSpace = Context.getTargetAddressSpace(ret);
976 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700977
978 SwapThisWithSRet = retAI.isSRetAfterThis();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000979 break;
980 }
981
Daniel Dunbar11434922009-01-26 21:26:08 +0000982 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000983 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000984 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
John McCalle56bb362012-12-07 07:03:17 +0000987 // Add in all of the required arguments.
988 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
989 if (FI.isVariadic()) {
990 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
991 } else {
992 ie = FI.arg_end();
993 }
994 for (; it != ie; ++it) {
John McCall42e06112011-05-15 02:19:42 +0000995 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000997 // Insert a padding type to ensure proper alignment.
998 if (llvm::Type *PaddingType = argAI.getPaddingType())
999 argTypes.push_back(PaddingType);
1000
John McCall42e06112011-05-15 02:19:42 +00001001 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +00001002 case ABIArgInfo::Ignore:
Stephen Hines651f13c2014-04-23 16:59:28 -07001003 case ABIArgInfo::InAlloca:
Daniel Dunbar11434922009-01-26 21:26:08 +00001004 break;
1005
Chris Lattner800588f2010-07-29 06:26:06 +00001006 case ABIArgInfo::Indirect: {
1007 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001008 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall42e06112011-05-15 02:19:42 +00001009 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +00001010 break;
1011 }
1012
1013 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +00001014 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-06-28 23:44:11 +00001015 // If the coerce-to type is a first class aggregate, flatten it. Either
1016 // way is semantically identical, but fast-isel and the optimizer
1017 // generally likes scalar values better than FCAs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001018 // We cannot do this for functions using the AAPCS calling convention,
1019 // as structures are treated differently by that calling convention.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001020 llvm::Type *argType = argAI.getCoerceToType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001021 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1022 if (st && !isAAPCSVFP(FI, getTarget())) {
John McCall42e06112011-05-15 02:19:42 +00001023 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1024 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +00001025 } else {
John McCall42e06112011-05-15 02:19:42 +00001026 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +00001027 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001028 break;
Chris Lattner1ed72672010-07-29 06:44:09 +00001029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001031 case ABIArgInfo::Expand:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001032 GetExpandedTypes(it->type, argTypes);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001033 break;
1034 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001035 }
1036
Stephen Hines651f13c2014-04-23 16:59:28 -07001037 // Add the inalloca struct as the last parameter type.
1038 if (llvm::StructType *ArgStruct = FI.getArgStruct())
1039 argTypes.push_back(ArgStruct->getPointerTo());
1040
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001041 if (SwapThisWithSRet)
1042 std::swap(argTypes[0], argTypes[1]);
1043
Chris Lattner71305cc2011-07-15 05:16:14 +00001044 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1045 assert(Erased && "Not in set?");
1046
John McCallde5d3c72012-02-17 03:33:10 +00001047 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar3913f182008-09-09 23:48:28 +00001048}
1049
Chris Lattner2acc6e32011-07-18 04:24:23 +00001050llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall4c40d982010-08-31 07:33:07 +00001051 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +00001052 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001053
Chris Lattnerf742eb02011-07-10 00:18:59 +00001054 if (!isFuncTypeConvertible(FPT))
1055 return llvm::StructType::get(getLLVMContext());
1056
1057 const CGFunctionInfo *Info;
1058 if (isa<CXXDestructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +00001059 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattnerf742eb02011-07-10 00:18:59 +00001060 else
John McCallde5d3c72012-02-17 03:33:10 +00001061 Info = &arrangeCXXMethodDeclaration(MD);
1062 return GetFunctionType(*Info);
Anders Carlssonecf282b2009-11-24 05:08:52 +00001063}
1064
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001065void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +00001066 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001067 AttributeListType &PAL,
Bill Wendling94236e72013-02-22 00:13:35 +00001068 unsigned &CallingConv,
1069 bool AttrOnCallSite) {
Bill Wendling0d583392012-10-15 20:36:26 +00001070 llvm::AttrBuilder FuncAttrs;
1071 llvm::AttrBuilder RetAttrs;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001072
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001073 CallingConv = FI.getEffectiveCallingConvention();
1074
John McCall04a67a62010-02-05 21:31:56 +00001075 if (FI.isNoReturn())
Bill Wendling72390b32012-12-20 19:27:06 +00001076 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall04a67a62010-02-05 21:31:56 +00001077
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001078 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001079 if (TargetDecl) {
Rafael Espindola67004152011-10-12 19:51:18 +00001080 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001081 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001082 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001083 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith7586a6e2013-01-30 05:45:05 +00001084 if (TargetDecl->hasAttr<NoReturnAttr>())
1085 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Stephen Hines651f13c2014-04-23 16:59:28 -07001086 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1087 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Richard Smith7586a6e2013-01-30 05:45:05 +00001088
1089 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCall9c0c1f32010-07-08 06:48:12 +00001090 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001091 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling72390b32012-12-20 19:27:06 +00001092 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith3c5cd152013-03-05 08:30:04 +00001093 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1094 // These attributes are not inherited by overloads.
1095 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1096 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smith7586a6e2013-01-30 05:45:05 +00001097 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall9c0c1f32010-07-08 06:48:12 +00001098 }
1099
Eric Christopher041087c2011-08-15 22:38:22 +00001100 // 'const' and 'pure' attribute functions are also nounwind.
1101 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001102 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1103 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001104 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001105 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1106 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001107 }
Ryan Flynn76168e22009-08-09 20:07:29 +00001108 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001109 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001110 }
1111
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001112 if (CodeGenOpts.OptimizeSize)
Bill Wendling72390b32012-12-20 19:27:06 +00001113 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet90467682012-10-26 00:29:48 +00001114 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling72390b32012-12-20 19:27:06 +00001115 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001116 if (CodeGenOpts.DisableRedZone)
Bill Wendling72390b32012-12-20 19:27:06 +00001117 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001118 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling72390b32012-12-20 19:27:06 +00001119 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001120 if (CodeGenOpts.EnableSegmentedStacks &&
1121 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
1122 FuncAttrs.addAttribute("split-stack");
Devang Patel24095da2009-06-04 23:32:02 +00001123
Bill Wendling93e4bff2013-02-22 20:53:29 +00001124 if (AttrOnCallSite) {
1125 // Attributes that should go on the call site only.
1126 if (!CodeGenOpts.SimplifyLibCalls)
1127 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001128 } else {
1129 // Attributes that should go on the function, but not the call site.
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001130 if (!CodeGenOpts.DisableFPElim) {
Bill Wendling4159f052013-03-13 22:24:33 +00001131 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001132 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendling4159f052013-03-13 22:24:33 +00001133 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001134 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001135 } else {
Bill Wendling4159f052013-03-13 22:24:33 +00001136 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001137 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001138 }
1139
Bill Wendling4159f052013-03-13 22:24:33 +00001140 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001141 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendling4159f052013-03-13 22:24:33 +00001142 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001143 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001144 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001145 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001146 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001147 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001148 FuncAttrs.addAttribute("use-soft-float",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001149 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendling45ccf282013-07-22 20:15:41 +00001150 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling8d230b42013-07-12 22:26:07 +00001151 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlingcab4a092013-07-25 00:32:41 +00001152
Bill Wendling1cf9ab82013-08-01 21:41:02 +00001153 if (!CodeGenOpts.StackRealignment)
1154 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +00001155 }
1156
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001157 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001158 unsigned Index = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001159 bool SwapThisWithSRet = false;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001160 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001161 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001162 case ABIArgInfo::Extend:
Jakob Stoklund Olesen5baefa82013-05-29 03:57:23 +00001163 if (RetTy->hasSignedIntegerRepresentation())
1164 RetAttrs.addAttribute(llvm::Attribute::SExt);
1165 else if (RetTy->hasUnsignedIntegerRepresentation())
1166 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001167 // FALL THROUGH
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001168 case ABIArgInfo::Direct:
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001169 if (RetAI.getInReg())
1170 RetAttrs.addAttribute(llvm::Attribute::InReg);
1171 break;
Chris Lattner800588f2010-07-29 06:26:06 +00001172 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001173 break;
1174
Stephen Hines651f13c2014-04-23 16:59:28 -07001175 case ABIArgInfo::InAlloca: {
1176 // inalloca disables readnone and readonly
1177 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1178 .removeAttribute(llvm::Attribute::ReadNone);
1179 break;
1180 }
1181
Rafael Espindolab48280b2012-07-31 02:44:24 +00001182 case ABIArgInfo::Indirect: {
Bill Wendling0d583392012-10-15 20:36:26 +00001183 llvm::AttrBuilder SRETAttrs;
Bill Wendling72390b32012-12-20 19:27:06 +00001184 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001185 if (RetAI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001186 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001187 SwapThisWithSRet = RetAI.isSRetAfterThis();
1188 PAL.push_back(llvm::AttributeSet::get(
1189 getLLVMContext(), SwapThisWithSRet ? 2 : Index, SRETAttrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001190
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001191 if (!SwapThisWithSRet)
1192 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001193 // sret disables readnone and readonly
Bill Wendling72390b32012-12-20 19:27:06 +00001194 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1195 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001196 break;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001197 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001198
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001199 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001200 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001201 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001202
Bill Wendling603571a2012-10-10 07:36:56 +00001203 if (RetAttrs.hasAttributes())
1204 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001205 AttributeSet::get(getLLVMContext(),
1206 llvm::AttributeSet::ReturnIndex,
1207 RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001208
Stephen Hines651f13c2014-04-23 16:59:28 -07001209 for (const auto &I : FI.arguments()) {
1210 QualType ParamType = I.type;
1211 const ABIArgInfo &AI = I.info;
Bill Wendling0d583392012-10-15 20:36:26 +00001212 llvm::AttrBuilder Attrs;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001213
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001214 // Skip over the sret parameter when it comes second. We already handled it
1215 // above.
1216 if (Index == 2 && SwapThisWithSRet)
1217 ++Index;
1218
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001219 if (AI.getPaddingType()) {
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001220 if (AI.getPaddingInReg())
1221 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1222 llvm::Attribute::InReg));
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001223 // Increment Index if there is padding.
1224 ++Index;
1225 }
1226
John McCalld8e10d22010-03-27 00:47:27 +00001227 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1228 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +00001229 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001230 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +00001231 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +00001232 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001233 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001234 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001235 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattner800588f2010-07-29 06:26:06 +00001236 // FALL THROUGH
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001237 case ABIArgInfo::Direct: {
Rafael Espindolab48280b2012-07-31 02:44:24 +00001238 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001239 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001240
Chris Lattner800588f2010-07-29 06:26:06 +00001241 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001242
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001243 llvm::StructType *STy =
1244 dyn_cast<llvm::StructType>(AI.getCoerceToType());
1245 if (!isAAPCSVFP(FI, getTarget()) && STy) {
Rafael Espindolab48280b2012-07-31 02:44:24 +00001246 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendling603571a2012-10-10 07:36:56 +00001247 if (Attrs.hasAttributes())
Rafael Espindolab48280b2012-07-31 02:44:24 +00001248 for (unsigned I = 0; I < Extra; ++I)
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001249 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1250 Attrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001251 Index += Extra;
1252 }
Chris Lattner800588f2010-07-29 06:26:06 +00001253 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001254 }
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001255 case ABIArgInfo::Indirect:
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001256 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001257 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001258
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001259 if (AI.getIndirectByVal())
Bill Wendling72390b32012-12-20 19:27:06 +00001260 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001261
Bill Wendling603571a2012-10-10 07:36:56 +00001262 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1263
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001264 // byval disables readnone and readonly.
Bill Wendling72390b32012-12-20 19:27:06 +00001265 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1266 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001267 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001268
Daniel Dunbar11434922009-01-26 21:26:08 +00001269 case ABIArgInfo::Ignore:
1270 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001271 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +00001272
Stephen Hines651f13c2014-04-23 16:59:28 -07001273 case ABIArgInfo::InAlloca:
1274 // inalloca disables readnone and readonly.
1275 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1276 .removeAttribute(llvm::Attribute::ReadNone);
1277 // Skip increment, no matching LLVM parameter.
1278 continue;
1279
Daniel Dunbar56273772008-09-17 00:51:38 +00001280 case ABIArgInfo::Expand: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001281 SmallVector<llvm::Type*, 8> types;
Mike Stumpf5408fe2009-05-16 07:57:57 +00001282 // FIXME: This is rather inefficient. Do we ever actually need to do
1283 // anything here? The result should be just reconstructed on the other
1284 // side, so extension should be a non-issue.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001285 getTypes().GetExpandedTypes(ParamType, types);
John McCall42e06112011-05-15 02:19:42 +00001286 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00001287 continue;
1288 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Bill Wendling603571a2012-10-10 07:36:56 +00001291 if (Attrs.hasAttributes())
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001292 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar56273772008-09-17 00:51:38 +00001293 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001294 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001295
1296 // Add the inalloca attribute to the trailing inalloca parameter if present.
1297 if (FI.usesInAlloca()) {
1298 llvm::AttrBuilder Attrs;
1299 Attrs.addAttribute(llvm::Attribute::InAlloca);
1300 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
1301 }
1302
Bill Wendling603571a2012-10-10 07:36:56 +00001303 if (FuncAttrs.hasAttributes())
Bill Wendling75d37b42012-10-15 07:31:59 +00001304 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001305 AttributeSet::get(getLLVMContext(),
1306 llvm::AttributeSet::FunctionIndex,
1307 FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001308}
1309
John McCalld26bc762011-03-09 04:27:21 +00001310/// An argument came in as a promoted argument; demote it back to its
1311/// declared type.
1312static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1313 const VarDecl *var,
1314 llvm::Value *value) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001315 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalld26bc762011-03-09 04:27:21 +00001316
1317 // This can happen with promotions that actually don't change the
1318 // underlying type, like the enum promotions.
1319 if (value->getType() == varType) return value;
1320
1321 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1322 && "unexpected promotion type");
1323
1324 if (isa<llvm::IntegerType>(varType))
1325 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1326
1327 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1328}
1329
Daniel Dunbar88b53962009-02-02 22:03:45 +00001330void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1331 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001332 const FunctionArgList &Args) {
John McCall0cfeb632009-07-28 01:00:58 +00001333 // If this is an implicit-return-zero function, go ahead and
1334 // initialize the return value. TODO: it might be nice to have
1335 // a more general mechanism for this that didn't require synthesized
1336 // return statements.
John McCallf5ebf9b2013-05-03 07:33:41 +00001337 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +00001338 if (FD->hasImplicitReturnZero()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001339 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001340 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001341 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +00001342 Builder.CreateStore(Zero, ReturnValue);
1343 }
1344 }
1345
Mike Stumpf5408fe2009-05-16 07:57:57 +00001346 // FIXME: We no longer need the types from FunctionArgList; lift up and
1347 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +00001348
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001349 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1350 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Stephen Hines651f13c2014-04-23 16:59:28 -07001352 // If we're using inalloca, all the memory arguments are GEPs off of the last
1353 // parameter, which is a pointer to the complete memory area.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001354 llvm::Value *ArgStruct = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001355 if (FI.usesInAlloca()) {
1356 llvm::Function::arg_iterator EI = Fn->arg_end();
1357 --EI;
1358 ArgStruct = EI;
1359 assert(ArgStruct->getType() == FI.getArgStruct()->getPointerTo());
1360 }
1361
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001362 // Name the struct return parameter, which can come first or second.
1363 const ABIArgInfo &RetAI = FI.getReturnInfo();
1364 bool SwapThisWithSRet = false;
1365 if (RetAI.isIndirect()) {
1366 SwapThisWithSRet = RetAI.isSRetAfterThis();
1367 if (SwapThisWithSRet)
1368 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001369 AI->setName("agg.result");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001370 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendling89530e42013-01-23 06:15:10 +00001371 llvm::Attribute::NoAlias));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001372 if (SwapThisWithSRet)
1373 --AI; // Go back to the beginning for 'this'.
1374 else
1375 ++AI; // Skip the sret parameter.
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001376 }
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Stephen Hines651f13c2014-04-23 16:59:28 -07001378 // Track if we received the parameter as a pointer (indirect, byval, or
1379 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
1380 // into a local alloca for us.
1381 enum ValOrPointer { HaveValue = 0, HavePointer = 1 };
1382 typedef llvm::PointerIntPair<llvm::Value *, 1> ValueAndIsPtr;
1383 SmallVector<ValueAndIsPtr, 16> ArgVals;
1384 ArgVals.reserve(Args.size());
1385
1386 // Create a pointer value for every parameter declaration. This usually
1387 // entails copying one or more LLVM IR arguments into an alloca. Don't push
1388 // any cleanups or do anything that might unwind. We do that separately, so
1389 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001390 assert(FI.arg_size() == Args.size() &&
1391 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +00001392 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001393 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +00001394 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1395 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +00001396 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001397 QualType Ty = info_it->type;
1398 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001399
John McCalld26bc762011-03-09 04:27:21 +00001400 bool isPromoted =
1401 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1402
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001403 // Skip the dummy padding argument.
1404 if (ArgI.getPaddingType())
1405 ++AI;
1406
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001407 switch (ArgI.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001408 case ABIArgInfo::InAlloca: {
1409 llvm::Value *V = Builder.CreateStructGEP(
1410 ArgStruct, ArgI.getInAllocaFieldIndex(), Arg->getName());
1411 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
1412 continue; // Don't increment AI!
1413 }
1414
Daniel Dunbar1f745982009-02-05 09:16:39 +00001415 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +00001416 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001417
John McCall9d232c82013-03-07 21:37:08 +00001418 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001419 // Aggregates and complex variables are accessed by reference. All we
1420 // need to do is realign the value, if requested
1421 if (ArgI.getIndirectRealign()) {
1422 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1423
1424 // Copy from the incoming argument pointer to the temporary with the
1425 // appropriate alignment.
1426 //
1427 // FIXME: We should have a common utility for generating an aggregate
1428 // copy.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001429 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +00001430 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +00001431 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1432 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1433 Builder.CreateMemCpy(Dst,
1434 Src,
Ken Dyckfe710082011-01-19 01:58:38 +00001435 llvm::ConstantInt::get(IntPtrTy,
1436 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +00001437 ArgI.getIndirectAlign(),
1438 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001439 V = AlignedTemp;
1440 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001441 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar1f745982009-02-05 09:16:39 +00001442 } else {
1443 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +00001444 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001445 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty,
1446 Arg->getLocStart());
John McCalld26bc762011-03-09 04:27:21 +00001447
1448 if (isPromoted)
1449 V = emitArgumentDemotion(*this, Arg, V);
Stephen Hines651f13c2014-04-23 16:59:28 -07001450 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Daniel Dunbar1f745982009-02-05 09:16:39 +00001451 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001452 break;
1453 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001454
1455 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001456 case ABIArgInfo::Direct: {
Akira Hatanaka4ba3fd42012-01-09 19:08:06 +00001457
Chris Lattner800588f2010-07-29 06:26:06 +00001458 // If we have the trivial case, handle it with no muss and fuss.
1459 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001460 ArgI.getCoerceToType() == ConvertType(Ty) &&
1461 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001462 assert(AI != Fn->arg_end() && "Argument mismatch!");
1463 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001464
Bill Wendlinga6375562012-10-16 05:23:44 +00001465 if (Arg->getType().isRestrictQualified())
Bill Wendling89530e42013-01-23 06:15:10 +00001466 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1467 AI->getArgNo() + 1,
1468 llvm::Attribute::NoAlias));
John McCalld8e10d22010-03-27 00:47:27 +00001469
Chris Lattnerb13eab92011-07-20 06:29:00 +00001470 // Ensure the argument is the correct type.
1471 if (V->getType() != ArgI.getCoerceToType())
1472 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1473
John McCalld26bc762011-03-09 04:27:21 +00001474 if (isPromoted)
1475 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001476
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001477 if (const CXXMethodDecl *MD =
1478 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001479 if (MD->isVirtual() && Arg == CXXABIThisDecl)
Nick Lewycky5d4a7552013-10-01 21:51:38 +00001480 V = CGM.getCXXABI().
1481 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001482 }
1483
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001484 // Because of merging of function types from multiple decls it is
1485 // possible for the type of an argument to not match the corresponding
1486 // type in the function type. Since we are codegening the callee
1487 // in here, add a cast to the argument type.
1488 llvm::Type *LTy = ConvertType(Arg->getType());
1489 if (V->getType() != LTy)
1490 V = Builder.CreateBitCast(V, LTy);
1491
Stephen Hines651f13c2014-04-23 16:59:28 -07001492 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
Chris Lattner800588f2010-07-29 06:26:06 +00001493 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001494 }
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001496 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001497
Chris Lattnerdeabde22010-07-28 18:24:28 +00001498 // The alignment we need to use is the max of the requested alignment for
1499 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001500 unsigned AlignmentToUse =
Micah Villmow25a6a842012-10-08 16:25:52 +00001501 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +00001502 AlignmentToUse = std::max(AlignmentToUse,
1503 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001504
Chris Lattnerdeabde22010-07-28 18:24:28 +00001505 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001506 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001507 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001508
Chris Lattner117e3f42010-07-30 04:02:24 +00001509 // If the value is offset in memory, apply the offset now.
1510 if (unsigned Offs = ArgI.getDirectOffset()) {
1511 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1512 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001513 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001514 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1515 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001516
Chris Lattner309c59f2010-06-29 00:06:42 +00001517 // If the coerce-to type is a first class aggregate, we flatten it and
1518 // pass the elements. Either way is semantically identical, but fast-isel
1519 // and the optimizer generally likes scalar values better than FCAs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001520 // We cannot do this for functions using the AAPCS calling convention,
1521 // as structures are treated differently by that calling convention.
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001522 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001523 if (!isAAPCSVFP(FI, getTarget()) && STy && STy->getNumElements() > 1) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001524 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001525 llvm::Type *DstTy =
1526 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00001527 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001528
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001529 if (SrcSize <= DstSize) {
1530 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1531
1532 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1533 assert(AI != Fn->arg_end() && "Argument mismatch!");
1534 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1535 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1536 Builder.CreateStore(AI++, EltPtr);
1537 }
1538 } else {
1539 llvm::AllocaInst *TempAlloca =
1540 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1541 TempAlloca->setAlignment(AlignmentToUse);
1542 llvm::Value *TempV = TempAlloca;
1543
1544 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1545 assert(AI != Fn->arg_end() && "Argument mismatch!");
1546 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1547 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1548 Builder.CreateStore(AI++, EltPtr);
1549 }
1550
1551 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner309c59f2010-06-29 00:06:42 +00001552 }
1553 } else {
1554 // Simple case, just do a coerced store of the argument into the alloca.
1555 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001556 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001557 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001558 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001559
1560
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001561 // Match to what EmitParmDecl is expecting for this type.
John McCall9d232c82013-03-07 21:37:08 +00001562 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001563 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty, Arg->getLocStart());
John McCalld26bc762011-03-09 04:27:21 +00001564 if (isPromoted)
1565 V = emitArgumentDemotion(*this, Arg, V);
Stephen Hines651f13c2014-04-23 16:59:28 -07001566 ArgVals.push_back(ValueAndIsPtr(V, HaveValue));
1567 } else {
1568 ArgVals.push_back(ValueAndIsPtr(V, HavePointer));
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001569 }
Chris Lattnerce700162010-06-28 23:44:11 +00001570 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001571 }
Chris Lattner800588f2010-07-29 06:26:06 +00001572
1573 case ABIArgInfo::Expand: {
1574 // If this structure was expanded into multiple arguments then
1575 // we need to create a temporary and reconstruct it from the
1576 // arguments.
Eli Friedman1bb94a42011-11-03 21:39:02 +00001577 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedman6da2c712011-12-03 04:14:32 +00001578 CharUnits Align = getContext().getDeclAlign(Arg);
1579 Alloca->setAlignment(Align.getQuantity());
1580 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman1bb94a42011-11-03 21:39:02 +00001581 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
Stephen Hines651f13c2014-04-23 16:59:28 -07001582 ArgVals.push_back(ValueAndIsPtr(Alloca, HavePointer));
Chris Lattner800588f2010-07-29 06:26:06 +00001583
1584 // Name the arguments used in expansion and increment AI.
1585 unsigned Index = 0;
1586 for (; AI != End; ++AI, ++Index)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001587 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattner800588f2010-07-29 06:26:06 +00001588 continue;
1589 }
1590
1591 case ABIArgInfo::Ignore:
1592 // Initialize the local variable appropriately.
Stephen Hines651f13c2014-04-23 16:59:28 -07001593 if (!hasScalarEvaluationKind(Ty)) {
1594 ArgVals.push_back(ValueAndIsPtr(CreateMemTemp(Ty), HavePointer));
1595 } else {
1596 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
1597 ArgVals.push_back(ValueAndIsPtr(U, HaveValue));
1598 }
Chris Lattner800588f2010-07-29 06:26:06 +00001599
1600 // Skip increment, no matching LLVM parameter.
1601 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001602 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001603
1604 ++AI;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001605
1606 if (ArgNo == 1 && SwapThisWithSRet)
1607 ++AI; // Skip the sret parameter.
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001608 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001609
1610 if (FI.usesInAlloca())
1611 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001612 assert(AI == Fn->arg_end() && "Argument mismatch!");
Stephen Hines651f13c2014-04-23 16:59:28 -07001613
1614 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1615 for (int I = Args.size() - 1; I >= 0; --I)
1616 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1617 I + 1);
1618 } else {
1619 for (unsigned I = 0, E = Args.size(); I != E; ++I)
1620 EmitParmDecl(*Args[I], ArgVals[I].getPointer(), ArgVals[I].getInt(),
1621 I + 1);
1622 }
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001623}
1624
John McCall77fe6cd2012-01-29 07:46:59 +00001625static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1626 while (insn->use_empty()) {
1627 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1628 if (!bitcast) return;
1629
1630 // This is "safe" because we would have used a ConstantExpr otherwise.
1631 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1632 bitcast->eraseFromParent();
1633 }
1634}
1635
John McCallf85e1932011-06-15 23:02:42 +00001636/// Try to emit a fused autorelease of a return result.
1637static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1638 llvm::Value *result) {
1639 // We must be immediately followed the cast.
1640 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001641 if (BB->empty()) return nullptr;
1642 if (&BB->back() != result) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001643
Chris Lattner2acc6e32011-07-18 04:24:23 +00001644 llvm::Type *resultType = result->getType();
John McCallf85e1932011-06-15 23:02:42 +00001645
1646 // result is in a BasicBlock and is therefore an Instruction.
1647 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1648
Chris Lattner5f9e2722011-07-23 10:55:15 +00001649 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCallf85e1932011-06-15 23:02:42 +00001650
1651 // Look for:
1652 // %generator = bitcast %type1* %generator2 to %type2*
1653 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1654 // We would have emitted this as a constant if the operand weren't
1655 // an Instruction.
1656 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1657
1658 // Require the generator to be immediately followed by the cast.
1659 if (generator->getNextNode() != bitcast)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001660 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001661
1662 insnsToKill.push_back(bitcast);
1663 }
1664
1665 // Look for:
1666 // %generator = call i8* @objc_retain(i8* %originalResult)
1667 // or
1668 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1669 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001670 if (!call) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001671
1672 bool doRetainAutorelease;
1673
1674 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1675 doRetainAutorelease = true;
1676 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1677 .objc_retainAutoreleasedReturnValue) {
1678 doRetainAutorelease = false;
1679
John McCallf9fdcc02012-09-07 23:30:50 +00001680 // If we emitted an assembly marker for this call (and the
1681 // ARCEntrypoints field should have been set if so), go looking
1682 // for that call. If we can't find it, we can't do this
1683 // optimization. But it should always be the immediately previous
1684 // instruction, unless we needed bitcasts around the call.
1685 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1686 llvm::Instruction *prev = call->getPrevNode();
1687 assert(prev);
1688 if (isa<llvm::BitCastInst>(prev)) {
1689 prev = prev->getPrevNode();
1690 assert(prev);
1691 }
1692 assert(isa<llvm::CallInst>(prev));
1693 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1694 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1695 insnsToKill.push_back(prev);
1696 }
John McCallf85e1932011-06-15 23:02:42 +00001697 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001698 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001699 }
1700
1701 result = call->getArgOperand(0);
1702 insnsToKill.push_back(call);
1703
1704 // Keep killing bitcasts, for sanity. Note that we no longer care
1705 // about precise ordering as long as there's exactly one use.
1706 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1707 if (!bitcast->hasOneUse()) break;
1708 insnsToKill.push_back(bitcast);
1709 result = bitcast->getOperand(0);
1710 }
1711
1712 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001713 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCallf85e1932011-06-15 23:02:42 +00001714 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1715 (*i)->eraseFromParent();
1716
1717 // Do the fused retain/autorelease if we were asked to.
1718 if (doRetainAutorelease)
1719 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1720
1721 // Cast back to the result type.
1722 return CGF.Builder.CreateBitCast(result, resultType);
1723}
1724
John McCall77fe6cd2012-01-29 07:46:59 +00001725/// If this is a +1 of the value of an immutable 'self', remove it.
1726static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1727 llvm::Value *result) {
1728 // This is only applicable to a method with an immutable 'self'.
John McCallbd9b65a2012-07-31 00:33:55 +00001729 const ObjCMethodDecl *method =
1730 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001731 if (!method) return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00001732 const VarDecl *self = method->getSelfDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001733 if (!self->getType().isConstQualified()) return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00001734
1735 // Look for a retain call.
1736 llvm::CallInst *retainCall =
1737 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1738 if (!retainCall ||
1739 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001740 return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00001741
1742 // Look for an ordinary load of 'self'.
1743 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1744 llvm::LoadInst *load =
1745 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1746 if (!load || load->isAtomic() || load->isVolatile() ||
1747 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001748 return nullptr;
John McCall77fe6cd2012-01-29 07:46:59 +00001749
1750 // Okay! Burn it all down. This relies for correctness on the
1751 // assumption that the retain is emitted as part of the return and
1752 // that thereafter everything is used "linearly".
1753 llvm::Type *resultType = result->getType();
1754 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1755 assert(retainCall->use_empty());
1756 retainCall->eraseFromParent();
1757 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1758
1759 return CGF.Builder.CreateBitCast(load, resultType);
1760}
1761
John McCallf85e1932011-06-15 23:02:42 +00001762/// Emit an ARC autorelease of the result of a function.
John McCall77fe6cd2012-01-29 07:46:59 +00001763///
1764/// \return the value to actually return from the function
John McCallf85e1932011-06-15 23:02:42 +00001765static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1766 llvm::Value *result) {
John McCall77fe6cd2012-01-29 07:46:59 +00001767 // If we're returning 'self', kill the initial retain. This is a
1768 // heuristic attempt to "encourage correctness" in the really unfortunate
1769 // case where we have a return of self during a dealloc and we desperately
1770 // need to avoid the possible autorelease.
1771 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1772 return self;
1773
John McCallf85e1932011-06-15 23:02:42 +00001774 // At -O0, try to emit a fused retain/autorelease.
1775 if (CGF.shouldUseFusedARCCalls())
1776 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1777 return fused;
1778
1779 return CGF.EmitARCAutoreleaseReturnValue(result);
1780}
1781
John McCallf48f7962012-01-29 02:35:02 +00001782/// Heuristically search for a dominating store to the return-value slot.
1783static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1784 // If there are multiple uses of the return-value slot, just check
1785 // for something immediately preceding the IP. Sometimes this can
1786 // happen with how we generate implicit-returns; it can also happen
1787 // with noreturn cleanups.
1788 if (!CGF.ReturnValue->hasOneUse()) {
1789 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001790 if (IP->empty()) return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00001791 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001792 if (!store) return nullptr;
1793 if (store->getPointerOperand() != CGF.ReturnValue) return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00001794 assert(!store->isAtomic() && !store->isVolatile()); // see below
1795 return store;
1796 }
1797
1798 llvm::StoreInst *store =
Stephen Hines651f13c2014-04-23 16:59:28 -07001799 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->user_back());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001800 if (!store) return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00001801
1802 // These aren't actually possible for non-coerced returns, and we
1803 // only care about non-coerced returns on this code path.
1804 assert(!store->isAtomic() && !store->isVolatile());
1805
1806 // Now do a first-and-dirty dominance check: just walk up the
1807 // single-predecessors chain from the current insertion point.
1808 llvm::BasicBlock *StoreBB = store->getParent();
1809 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1810 while (IP != StoreBB) {
1811 if (!(IP = IP->getSinglePredecessor()))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001812 return nullptr;
John McCallf48f7962012-01-29 02:35:02 +00001813 }
1814
1815 // Okay, the store's basic block dominates the insertion point; we
1816 // can do our thing.
1817 return store;
1818}
1819
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001820void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001821 bool EmitRetDbgLoc,
1822 SourceLocation EndLoc) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001823 // Functions with no result always return void.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001824 if (!ReturnValue) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001825 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001826 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001827 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001828
Dan Gohman4751a532010-07-20 20:13:52 +00001829 llvm::DebugLoc RetDbgLoc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001830 llvm::Value *RV = nullptr;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001831 QualType RetTy = FI.getReturnType();
1832 const ABIArgInfo &RetAI = FI.getReturnInfo();
1833
1834 switch (RetAI.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001835 case ABIArgInfo::InAlloca:
1836 // Aggregrates get evaluated directly into the destination. Sometimes we
1837 // need to return the sret value in a register, though.
1838 assert(hasAggregateEvaluationKind(RetTy));
1839 if (RetAI.getInAllocaSRet()) {
1840 llvm::Function::arg_iterator EI = CurFn->arg_end();
1841 --EI;
1842 llvm::Value *ArgStruct = EI;
1843 llvm::Value *SRet =
1844 Builder.CreateStructGEP(ArgStruct, RetAI.getInAllocaFieldIndex());
1845 RV = Builder.CreateLoad(SRet, "sret");
1846 }
1847 break;
1848
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001849 case ABIArgInfo::Indirect: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001850 auto AI = CurFn->arg_begin();
1851 if (RetAI.isSRetAfterThis())
1852 ++AI;
John McCall9d232c82013-03-07 21:37:08 +00001853 switch (getEvaluationKind(RetTy)) {
1854 case TEK_Complex: {
1855 ComplexPairTy RT =
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001856 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy),
1857 EndLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001858 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall9d232c82013-03-07 21:37:08 +00001859 /*isInit*/ true);
1860 break;
1861 }
1862 case TEK_Aggregate:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001863 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall9d232c82013-03-07 21:37:08 +00001864 break;
1865 case TEK_Scalar:
1866 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001867 MakeNaturalAlignAddrLValue(AI, RetTy),
John McCall9d232c82013-03-07 21:37:08 +00001868 /*isInit*/ true);
1869 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001870 }
1871 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001872 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001873
1874 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001875 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001876 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1877 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001878 // The internal return value temp always will have pointer-to-return-type
1879 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001880
John McCallf48f7962012-01-29 02:35:02 +00001881 // If there is a dominating store to ReturnValue, we can elide
1882 // the load, zap the store, and usually zap the alloca.
1883 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl7c731f52013-05-30 18:12:23 +00001884 // Reuse the debug location from the store unless there is
1885 // cleanup code to be emitted between the store and return
1886 // instruction.
1887 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001888 RetDbgLoc = SI->getDebugLoc();
Chris Lattner800588f2010-07-29 06:26:06 +00001889 // Get the stored value and nuke the now-dead store.
Chris Lattner800588f2010-07-29 06:26:06 +00001890 RV = SI->getValueOperand();
1891 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001892
Chris Lattner800588f2010-07-29 06:26:06 +00001893 // If that was the only use of the return value, nuke it as well now.
1894 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1895 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001896 ReturnValue = nullptr;
Chris Lattner800588f2010-07-29 06:26:06 +00001897 }
John McCallf48f7962012-01-29 02:35:02 +00001898
1899 // Otherwise, we have to do a simple load.
1900 } else {
1901 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner35b21b82010-06-27 01:06:27 +00001902 }
Chris Lattner800588f2010-07-29 06:26:06 +00001903 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001904 llvm::Value *V = ReturnValue;
1905 // If the value is offset in memory, apply the offset now.
1906 if (unsigned Offs = RetAI.getDirectOffset()) {
1907 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1908 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001909 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001910 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1911 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001912
Chris Lattner117e3f42010-07-30 04:02:24 +00001913 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001914 }
John McCallf85e1932011-06-15 23:02:42 +00001915
1916 // In ARC, end functions that return a retainable type with a call
1917 // to objc_autoreleaseReturnValue.
1918 if (AutoreleaseResult) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001919 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001920 !FI.isReturnsRetained() &&
1921 RetTy->isObjCRetainableType());
1922 RV = emitAutoreleaseOfResult(*this, RV);
1923 }
1924
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001925 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001926
Chris Lattner800588f2010-07-29 06:26:06 +00001927 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001928 break;
1929
1930 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001931 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001932 }
1933
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001934 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001935 if (!RetDbgLoc.isUnknown())
1936 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001937}
1938
Stephen Hines651f13c2014-04-23 16:59:28 -07001939static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
1940 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
1941 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
1942}
1943
1944static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty) {
1945 // FIXME: Generate IR in one pass, rather than going back and fixing up these
1946 // placeholders.
1947 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
1948 llvm::Value *Placeholder =
1949 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
1950 Placeholder = CGF.Builder.CreateLoad(Placeholder);
1951 return AggValueSlot::forAddr(Placeholder, CharUnits::Zero(),
1952 Ty.getQualifiers(),
1953 AggValueSlot::IsNotDestructed,
1954 AggValueSlot::DoesNotNeedGCBarriers,
1955 AggValueSlot::IsNotAliased);
1956}
1957
John McCall413ebdb2011-03-11 20:59:21 +00001958void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001959 const VarDecl *param,
1960 SourceLocation loc) {
John McCall27360712010-05-26 22:34:26 +00001961 // StartFunction converted the ABI-lowered parameter(s) into a
1962 // local alloca. We need to turn that into an r-value suitable
1963 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001964 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001965
John McCall413ebdb2011-03-11 20:59:21 +00001966 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001967
John McCall27360712010-05-26 22:34:26 +00001968 // For the most part, we just need to load the alloca, except:
1969 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall9d232c82013-03-07 21:37:08 +00001970 // 2) references to non-scalars are pointers directly to the aggregate.
1971 // I don't know why references to scalars are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001972 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall9d232c82013-03-07 21:37:08 +00001973 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall413ebdb2011-03-11 20:59:21 +00001974 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001975
1976 // Locals which are references to scalars are represented
1977 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001978 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001979 }
1980
Stephen Hines651f13c2014-04-23 16:59:28 -07001981 if (isInAllocaArgument(CGM.getCXXABI(), type)) {
1982 AggValueSlot Slot = createPlaceholderSlot(*this, type);
1983 Slot.setExternallyDestructed();
1984
1985 // FIXME: Either emit a copy constructor call, or figure out how to do
1986 // guaranteed tail calls with perfect forwarding in LLVM.
1987 CGM.ErrorUnsupported(param, "non-trivial argument copy for thunk");
1988 EmitNullInitialization(Slot.getAddr(), type);
1989
1990 RValue RV = Slot.asRValue();
1991 args.add(RV, type);
1992 return;
1993 }
1994
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001995 args.add(convertTempToRValue(local, type, loc), type);
John McCall27360712010-05-26 22:34:26 +00001996}
1997
John McCallf85e1932011-06-15 23:02:42 +00001998static bool isProvablyNull(llvm::Value *addr) {
1999 return isa<llvm::ConstantPointerNull>(addr);
2000}
2001
2002static bool isProvablyNonNull(llvm::Value *addr) {
2003 return isa<llvm::AllocaInst>(addr);
2004}
2005
2006/// Emit the actual writing-back of a writeback.
2007static void emitWriteback(CodeGenFunction &CGF,
2008 const CallArgList::Writeback &writeback) {
John McCallb6a60792013-03-23 02:35:54 +00002009 const LValue &srcLV = writeback.Source;
2010 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00002011 assert(!isProvablyNull(srcAddr) &&
2012 "shouldn't have writeback for provably null argument");
2013
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002014 llvm::BasicBlock *contBB = nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002015
2016 // If the argument wasn't provably non-null, we need to null check
2017 // before doing the store.
2018 bool provablyNonNull = isProvablyNonNull(srcAddr);
2019 if (!provablyNonNull) {
2020 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2021 contBB = CGF.createBasicBlock("icr.done");
2022
2023 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2024 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2025 CGF.EmitBlock(writebackBB);
2026 }
2027
2028 // Load the value to writeback.
2029 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
2030
2031 // Cast it back, in case we're writing an id to a Foo* or something.
2032 value = CGF.Builder.CreateBitCast(value,
2033 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
2034 "icr.writeback-cast");
2035
2036 // Perform the writeback.
John McCallb6a60792013-03-23 02:35:54 +00002037
2038 // If we have a "to use" value, it's something we need to emit a use
2039 // of. This has to be carefully threaded in: if it's done after the
2040 // release it's potentially undefined behavior (and the optimizer
2041 // will ignore it), and if it happens before the retain then the
2042 // optimizer could move the release there.
2043 if (writeback.ToUse) {
2044 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
2045
2046 // Retain the new value. No need to block-copy here: the block's
2047 // being passed up the stack.
2048 value = CGF.EmitARCRetainNonBlock(value);
2049
2050 // Emit the intrinsic use here.
2051 CGF.EmitARCIntrinsicUse(writeback.ToUse);
2052
2053 // Load the old value (primitively).
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002054 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCallb6a60792013-03-23 02:35:54 +00002055
2056 // Put the new value in place (primitively).
2057 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
2058
2059 // Release the old value.
2060 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
2061
2062 // Otherwise, we can just do a normal lvalue store.
2063 } else {
2064 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
2065 }
John McCallf85e1932011-06-15 23:02:42 +00002066
2067 // Jump to the continuation block.
2068 if (!provablyNonNull)
2069 CGF.EmitBlock(contBB);
2070}
2071
2072static void emitWritebacks(CodeGenFunction &CGF,
2073 const CallArgList &args) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002074 for (const auto &I : args.writebacks())
2075 emitWriteback(CGF, I);
John McCallf85e1932011-06-15 23:02:42 +00002076}
2077
Reid Kleckner9b601952013-06-21 12:45:15 +00002078static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
2079 const CallArgList &CallArgs) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002080 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner9b601952013-06-21 12:45:15 +00002081 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
2082 CallArgs.getCleanupsToDeactivate();
2083 // Iterate in reverse to increase the likelihood of popping the cleanup.
2084 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
2085 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
2086 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
2087 I->IsActiveIP->eraseFromParent();
2088 }
2089}
2090
John McCallb6a60792013-03-23 02:35:54 +00002091static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
2092 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
2093 if (uop->getOpcode() == UO_AddrOf)
2094 return uop->getSubExpr();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002095 return nullptr;
John McCallb6a60792013-03-23 02:35:54 +00002096}
2097
John McCallf85e1932011-06-15 23:02:42 +00002098/// Emit an argument that's being passed call-by-writeback. That is,
2099/// we are passing the address of
2100static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
2101 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCallb6a60792013-03-23 02:35:54 +00002102 LValue srcLV;
2103
2104 // Make an optimistic effort to emit the address as an l-value.
2105 // This can fail if the the argument expression is more complicated.
2106 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
2107 srcLV = CGF.EmitLValue(lvExpr);
2108
2109 // Otherwise, just emit it as a scalar.
2110 } else {
2111 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
2112
2113 QualType srcAddrType =
2114 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2115 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
2116 }
2117 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00002118
2119 // The dest and src types don't necessarily match in LLVM terms
2120 // because of the crazy ObjC compatibility rules.
2121
Chris Lattner2acc6e32011-07-18 04:24:23 +00002122 llvm::PointerType *destType =
John McCallf85e1932011-06-15 23:02:42 +00002123 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
2124
2125 // If the address is a constant null, just pass the appropriate null.
2126 if (isProvablyNull(srcAddr)) {
2127 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
2128 CRE->getType());
2129 return;
2130 }
2131
John McCallf85e1932011-06-15 23:02:42 +00002132 // Create the temporary.
2133 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
2134 "icr.temp");
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002135 // Loading an l-value can introduce a cleanup if the l-value is __weak,
2136 // and that cleanup will be conditional if we can't prove that the l-value
2137 // isn't null, so we need to register a dominating point so that the cleanups
2138 // system will make valid IR.
2139 CodeGenFunction::ConditionalEvaluation condEval(CGF);
2140
John McCallf85e1932011-06-15 23:02:42 +00002141 // Zero-initialize it if we're not doing a copy-initialization.
2142 bool shouldCopy = CRE->shouldCopy();
2143 if (!shouldCopy) {
2144 llvm::Value *null =
2145 llvm::ConstantPointerNull::get(
2146 cast<llvm::PointerType>(destType->getElementType()));
2147 CGF.Builder.CreateStore(null, temp);
2148 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002149
2150 llvm::BasicBlock *contBB = nullptr;
2151 llvm::BasicBlock *originBB = nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002152
2153 // If the address is *not* known to be non-null, we need to switch.
2154 llvm::Value *finalArgument;
2155
2156 bool provablyNonNull = isProvablyNonNull(srcAddr);
2157 if (provablyNonNull) {
2158 finalArgument = temp;
2159 } else {
2160 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
2161
2162 finalArgument = CGF.Builder.CreateSelect(isNull,
2163 llvm::ConstantPointerNull::get(destType),
2164 temp, "icr.argument");
2165
2166 // If we need to copy, then the load has to be conditional, which
2167 // means we need control flow.
2168 if (shouldCopy) {
John McCallb6a60792013-03-23 02:35:54 +00002169 originBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00002170 contBB = CGF.createBasicBlock("icr.cont");
2171 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
2172 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
2173 CGF.EmitBlock(copyBB);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002174 condEval.begin(CGF);
John McCallf85e1932011-06-15 23:02:42 +00002175 }
2176 }
2177
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002178 llvm::Value *valueToUse = nullptr;
John McCallb6a60792013-03-23 02:35:54 +00002179
John McCallf85e1932011-06-15 23:02:42 +00002180 // Perform a copy if necessary.
2181 if (shouldCopy) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002182 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00002183 assert(srcRV.isScalar());
2184
2185 llvm::Value *src = srcRV.getScalarVal();
2186 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
2187 "icr.cast");
2188
2189 // Use an ordinary store, not a store-to-lvalue.
2190 CGF.Builder.CreateStore(src, temp);
John McCallb6a60792013-03-23 02:35:54 +00002191
2192 // If optimization is enabled, and the value was held in a
2193 // __strong variable, we need to tell the optimizer that this
2194 // value has to stay alive until we're doing the store back.
2195 // This is because the temporary is effectively unretained,
2196 // and so otherwise we can violate the high-level semantics.
2197 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2198 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
2199 valueToUse = src;
2200 }
John McCallf85e1932011-06-15 23:02:42 +00002201 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002202
John McCallf85e1932011-06-15 23:02:42 +00002203 // Finish the control flow if we needed it.
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002204 if (shouldCopy && !provablyNonNull) {
John McCallb6a60792013-03-23 02:35:54 +00002205 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00002206 CGF.EmitBlock(contBB);
John McCallb6a60792013-03-23 02:35:54 +00002207
2208 // Make a phi for the value to intrinsically use.
2209 if (valueToUse) {
2210 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
2211 "icr.to-use");
2212 phiToUse->addIncoming(valueToUse, copyBB);
2213 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
2214 originBB);
2215 valueToUse = phiToUse;
2216 }
2217
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00002218 condEval.end(CGF);
2219 }
John McCallf85e1932011-06-15 23:02:42 +00002220
John McCallb6a60792013-03-23 02:35:54 +00002221 args.addWriteback(srcLV, temp, valueToUse);
John McCallf85e1932011-06-15 23:02:42 +00002222 args.add(RValue::get(finalArgument), CRE->getType());
2223}
2224
Stephen Hines651f13c2014-04-23 16:59:28 -07002225void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
2226 assert(!StackBase && !StackCleanup.isValid());
2227
2228 // Save the stack.
2229 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
2230 StackBase = CGF.Builder.CreateCall(F, "inalloca.save");
2231
2232 // Control gets really tied up in landing pads, so we have to spill the
2233 // stacksave to an alloca to avoid violating SSA form.
2234 // TODO: This is dead if we never emit the cleanup. We should create the
2235 // alloca and store lazily on the first cleanup emission.
2236 StackBaseMem = CGF.CreateTempAlloca(CGF.Int8PtrTy, "inalloca.spmem");
2237 CGF.Builder.CreateStore(StackBase, StackBaseMem);
2238 CGF.pushStackRestore(EHCleanup, StackBaseMem);
2239 StackCleanup = CGF.EHStack.getInnermostEHScope();
2240 assert(StackCleanup.isValid());
2241}
2242
2243void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
2244 if (StackBase) {
2245 CGF.DeactivateCleanupBlock(StackCleanup, StackBase);
2246 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
2247 // We could load StackBase from StackBaseMem, but in the non-exceptional
2248 // case we can skip it.
2249 CGF.Builder.CreateCall(F, StackBase);
2250 }
2251}
2252
2253void CodeGenFunction::EmitCallArgs(CallArgList &Args,
2254 ArrayRef<QualType> ArgTypes,
2255 CallExpr::const_arg_iterator ArgBeg,
2256 CallExpr::const_arg_iterator ArgEnd,
2257 bool ForceColumnInfo) {
2258 CGDebugInfo *DI = getDebugInfo();
2259 SourceLocation CallLoc;
2260 if (DI) CallLoc = DI->getLocation();
2261
2262 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
2263 // because arguments are destroyed left to right in the callee.
2264 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2265 // Insert a stack save if we're going to need any inalloca args.
2266 bool HasInAllocaArgs = false;
2267 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
2268 I != E && !HasInAllocaArgs; ++I)
2269 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
2270 if (HasInAllocaArgs) {
2271 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2272 Args.allocateArgumentMemory(*this);
2273 }
2274
2275 // Evaluate each argument.
2276 size_t CallArgsStart = Args.size();
2277 for (int I = ArgTypes.size() - 1; I >= 0; --I) {
2278 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2279 EmitCallArg(Args, *Arg, ArgTypes[I]);
2280 // Restore the debug location.
2281 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2282 }
2283
2284 // Un-reverse the arguments we just evaluated so they match up with the LLVM
2285 // IR function.
2286 std::reverse(Args.begin() + CallArgsStart, Args.end());
2287 return;
2288 }
2289
2290 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
2291 CallExpr::const_arg_iterator Arg = ArgBeg + I;
2292 assert(Arg != ArgEnd);
2293 EmitCallArg(Args, *Arg, ArgTypes[I]);
2294 // Restore the debug location.
2295 if (DI) DI->EmitLocation(Builder, CallLoc, ForceColumnInfo);
2296 }
2297}
2298
2299namespace {
2300
2301struct DestroyUnpassedArg : EHScopeStack::Cleanup {
2302 DestroyUnpassedArg(llvm::Value *Addr, QualType Ty)
2303 : Addr(Addr), Ty(Ty) {}
2304
2305 llvm::Value *Addr;
2306 QualType Ty;
2307
2308 void Emit(CodeGenFunction &CGF, Flags flags) override {
2309 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
2310 assert(!Dtor->isTrivial());
2311 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
2312 /*Delegating=*/false, Addr);
2313 }
2314};
2315
2316}
2317
John McCall413ebdb2011-03-11 20:59:21 +00002318void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
2319 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00002320 if (const ObjCIndirectCopyRestoreExpr *CRE
2321 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002322 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00002323 assert(getContext().hasSameType(E->getType(), type));
2324 return emitWritebackArg(*this, args, CRE);
2325 }
2326
John McCall8affed52011-08-26 18:42:59 +00002327 assert(type->isReferenceType() == E->isGLValue() &&
2328 "reference binding to unmaterialized r-value!");
2329
John McCallcec52f02011-08-26 21:08:13 +00002330 if (E->isGLValue()) {
2331 assert(E->getObjectKind() == OK_Ordinary);
Richard Smithd4ec5622013-06-12 23:38:09 +00002332 return args.add(EmitReferenceBindingToExpr(E), type);
John McCallcec52f02011-08-26 21:08:13 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Reid Kleckner9b601952013-06-21 12:45:15 +00002335 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2336
2337 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2338 // However, we still have to push an EH-only cleanup in case we unwind before
2339 // we make it to the call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002340 if (HasAggregateEvalKind &&
2341 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2342 // If we're using inalloca, use the argument memory. Otherwise, use a
2343 // temporary.
2344 AggValueSlot Slot;
2345 if (args.isUsingInAlloca())
2346 Slot = createPlaceholderSlot(*this, type);
2347 else
2348 Slot = CreateAggTemp(type, "agg.tmp");
2349
2350 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2351 bool DestroyedInCallee =
2352 RD && RD->hasNonTrivialDestructor() &&
2353 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
2354 if (DestroyedInCallee)
2355 Slot.setExternallyDestructed();
2356
Stephen Hines651f13c2014-04-23 16:59:28 -07002357 EmitAggExpr(E, Slot);
2358 RValue RV = Slot.asRValue();
2359 args.add(RV, type);
Reid Kleckner9b601952013-06-21 12:45:15 +00002360
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002361 if (DestroyedInCallee) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002362 // Create a no-op GEP between the placeholder and the cleanup so we can
2363 // RAUW it successfully. It also serves as a marker of the first
2364 // instruction where the cleanup is active.
2365 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddr(), type);
Reid Kleckner9b601952013-06-21 12:45:15 +00002366 // This unreachable is a temporary marker which will be removed later.
2367 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2368 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner9b601952013-06-21 12:45:15 +00002369 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002370 return;
Reid Kleckner9b601952013-06-21 12:45:15 +00002371 }
2372
2373 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00002374 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2375 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2376 assert(L.isSimple());
Eli Friedmand39083d2013-06-11 01:08:22 +00002377 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2378 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2379 } else {
2380 // We can't represent a misaligned lvalue in the CallArgList, so copy
2381 // to an aligned temporary now.
2382 llvm::Value *tmp = CreateMemTemp(type);
2383 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2384 L.getAlignment());
2385 args.add(RValue::getAggregate(tmp), type);
2386 }
Eli Friedman55d48482011-05-26 00:10:27 +00002387 return;
2388 }
2389
John McCall413ebdb2011-03-11 20:59:21 +00002390 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00002391}
2392
Dan Gohmanb49bd272012-02-16 00:57:37 +00002393// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2394// optimizer it can aggressively ignore unwind edges.
2395void
2396CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2397 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2398 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2399 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2400 CGM.getNoObjCARCExceptionsMetadata());
2401}
2402
John McCallbd7370a2013-02-28 19:01:20 +00002403/// Emits a call to the given no-arguments nounwind runtime function.
2404llvm::CallInst *
2405CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2406 const llvm::Twine &name) {
2407 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2408}
2409
2410/// Emits a call to the given nounwind runtime function.
2411llvm::CallInst *
2412CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2413 ArrayRef<llvm::Value*> args,
2414 const llvm::Twine &name) {
2415 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2416 call->setDoesNotThrow();
2417 return call;
2418}
2419
2420/// Emits a simple call (never an invoke) to the given no-arguments
2421/// runtime function.
2422llvm::CallInst *
2423CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2424 const llvm::Twine &name) {
2425 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2426}
2427
2428/// Emits a simple call (never an invoke) to the given runtime
2429/// function.
2430llvm::CallInst *
2431CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2432 ArrayRef<llvm::Value*> args,
2433 const llvm::Twine &name) {
2434 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2435 call->setCallingConv(getRuntimeCC());
2436 return call;
2437}
2438
2439/// Emits a call or invoke to the given noreturn runtime function.
2440void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2441 ArrayRef<llvm::Value*> args) {
2442 if (getInvokeDest()) {
2443 llvm::InvokeInst *invoke =
2444 Builder.CreateInvoke(callee,
2445 getUnreachableBlock(),
2446 getInvokeDest(),
2447 args);
2448 invoke->setDoesNotReturn();
2449 invoke->setCallingConv(getRuntimeCC());
2450 } else {
2451 llvm::CallInst *call = Builder.CreateCall(callee, args);
2452 call->setDoesNotReturn();
2453 call->setCallingConv(getRuntimeCC());
2454 Builder.CreateUnreachable();
2455 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002456 PGO.setCurrentRegionUnreachable();
John McCallbd7370a2013-02-28 19:01:20 +00002457}
2458
2459/// Emits a call or invoke instruction to the given nullary runtime
2460/// function.
2461llvm::CallSite
2462CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2463 const Twine &name) {
2464 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2465}
2466
2467/// Emits a call or invoke instruction to the given runtime function.
2468llvm::CallSite
2469CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2470 ArrayRef<llvm::Value*> args,
2471 const Twine &name) {
2472 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2473 callSite.setCallingConv(getRuntimeCC());
2474 return callSite;
2475}
2476
2477llvm::CallSite
2478CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2479 const Twine &Name) {
2480 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2481}
2482
John McCallf1549f62010-07-06 01:34:17 +00002483/// Emits a call or invoke instruction to the given function, depending
2484/// on the current state of the EH stack.
2485llvm::CallSite
2486CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002487 ArrayRef<llvm::Value *> Args,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002488 const Twine &Name) {
John McCallf1549f62010-07-06 01:34:17 +00002489 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallf1549f62010-07-06 01:34:17 +00002490
Dan Gohmanb49bd272012-02-16 00:57:37 +00002491 llvm::Instruction *Inst;
2492 if (!InvokeDest)
2493 Inst = Builder.CreateCall(Callee, Args, Name);
2494 else {
2495 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2496 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2497 EmitBlock(ContBB);
2498 }
2499
2500 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2501 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002502 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002503 AddObjCARCExceptionMetadata(Inst);
2504
2505 return Inst;
John McCallf1549f62010-07-06 01:34:17 +00002506}
2507
Chris Lattner70855442011-07-12 04:46:18 +00002508static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2509 llvm::FunctionType *FTy) {
2510 if (ArgNo < FTy->getNumParams())
2511 assert(Elt->getType() == FTy->getParamType(ArgNo));
2512 else
2513 assert(FTy->isVarArg());
2514 ++ArgNo;
2515}
2516
Chris Lattner811bf362011-07-12 06:29:11 +00002517void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper6b9240e2013-07-05 19:34:19 +00002518 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattner811bf362011-07-12 06:29:11 +00002519 llvm::FunctionType *IRFuncTy) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002520 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2521 unsigned NumElts = AT->getSize().getZExtValue();
2522 QualType EltTy = AT->getElementType();
2523 llvm::Value *Addr = RV.getAggregateAddr();
2524 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2525 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002526 RValue EltRV = convertTempToRValue(EltAddr, EltTy, SourceLocation());
Bob Wilson194f06a2011-08-03 05:58:22 +00002527 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattner811bf362011-07-12 06:29:11 +00002528 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002529 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002530 RecordDecl *RD = RT->getDecl();
2531 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman377ecc72012-04-16 03:54:45 +00002532 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002533
2534 if (RD->isUnion()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002535 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002536 CharUnits UnionSize = CharUnits::Zero();
2537
Stephen Hines651f13c2014-04-23 16:59:28 -07002538 for (const auto *FD : RD->fields()) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002539 assert(!FD->isBitField() &&
2540 "Cannot expand structure with bit-field members.");
2541 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2542 if (UnionSize < FieldSize) {
2543 UnionSize = FieldSize;
2544 LargestFD = FD;
2545 }
2546 }
2547 if (LargestFD) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002548 RValue FldRV = EmitRValueForField(LV, LargestFD, SourceLocation());
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002549 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2550 }
2551 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002552 for (const auto *FD : RD->fields()) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002553 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002554 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2555 }
Bob Wilson194f06a2011-08-03 05:58:22 +00002556 }
Eli Friedmanca3d3fc2011-11-15 02:46:03 +00002557 } else if (Ty->isAnyComplexType()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002558 ComplexPairTy CV = RV.getComplexVal();
2559 Args.push_back(CV.first);
2560 Args.push_back(CV.second);
2561 } else {
Chris Lattner811bf362011-07-12 06:29:11 +00002562 assert(RV.isScalar() &&
2563 "Unexpected non-scalar rvalue during struct expansion.");
2564
2565 // Insert a bitcast as needed.
2566 llvm::Value *V = RV.getScalarVal();
2567 if (Args.size() < IRFuncTy->getNumParams() &&
2568 V->getType() != IRFuncTy->getParamType(Args.size()))
2569 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2570
2571 Args.push_back(V);
2572 }
2573}
2574
Stephen Hines651f13c2014-04-23 16:59:28 -07002575/// \brief Store a non-aggregate value to an address to initialize it. For
2576/// initialization, a non-atomic store will be used.
2577static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
2578 LValue Dst) {
2579 if (Src.isScalar())
2580 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
2581 else
2582 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
2583}
2584
2585void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
2586 llvm::Value *New) {
2587 DeferredReplacements.push_back(std::make_pair(Old, New));
2588}
Chris Lattner811bf362011-07-12 06:29:11 +00002589
Daniel Dunbar88b53962009-02-02 22:03:45 +00002590RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002591 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00002592 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002593 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00002594 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00002595 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002596 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002597 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002598
2599 // Handle struct-return functions by passing a pointer to the
2600 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002601 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002602 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Chris Lattner70855442011-07-12 04:46:18 +00002604 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2605 unsigned IRArgNo = 0;
2606 llvm::FunctionType *IRFuncTy =
2607 cast<llvm::FunctionType>(
2608 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Stephen Hines651f13c2014-04-23 16:59:28 -07002610 // If we're using inalloca, insert the allocation after the stack save.
2611 // FIXME: Do this earlier rather than hacking it in here!
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002612 llvm::Value *ArgMemory = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002613 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002614 llvm::Instruction *IP = CallArgs.getStackBase();
2615 llvm::AllocaInst *AI;
2616 if (IP) {
2617 IP = IP->getNextNode();
2618 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
2619 } else {
2620 AI = CreateTempAlloca(ArgStruct, "argmem");
2621 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002622 AI->setUsedWithInAlloca(true);
2623 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
2624 ArgMemory = AI;
2625 }
2626
Chris Lattner5db7ae52009-06-13 00:26:38 +00002627 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00002628 // alloca to hold the result, unless one is given to us.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002629 llvm::Value *SRetPtr = nullptr;
2630 bool SwapThisWithSRet = false;
2631 if (RetAI.isIndirect() || RetAI.isInAlloca()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002632 SRetPtr = ReturnValue.getValue();
2633 if (!SRetPtr)
2634 SRetPtr = CreateMemTemp(RetTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002635 if (RetAI.isIndirect()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002636 Args.push_back(SRetPtr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002637 SwapThisWithSRet = RetAI.isSRetAfterThis();
2638 if (SwapThisWithSRet)
2639 IRArgNo = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07002640 checkArgMatches(SRetPtr, IRArgNo, IRFuncTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002641 if (SwapThisWithSRet)
2642 IRArgNo = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07002643 } else {
2644 llvm::Value *Addr =
2645 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
2646 Builder.CreateStore(SRetPtr, Addr);
2647 }
Anders Carlssond2490a92009-12-24 20:40:36 +00002648 }
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00002650 assert(CallInfo.arg_size() == CallArgs.size() &&
2651 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00002652 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00002653 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002654 I != E; ++I, ++info_it) {
2655 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00002656 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00002657
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002658 // Skip 'sret' if it came second.
2659 if (IRArgNo == 1 && SwapThisWithSRet)
2660 ++IRArgNo;
2661
John McCall9d232c82013-03-07 21:37:08 +00002662 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00002663
2664 // Insert a padding argument to ensure proper alignment.
2665 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2666 Args.push_back(llvm::UndefValue::get(PaddingType));
2667 ++IRArgNo;
2668 }
2669
Daniel Dunbar56273772008-09-17 00:51:38 +00002670 switch (ArgInfo.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002671 case ABIArgInfo::InAlloca: {
2672 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
2673 if (RV.isAggregate()) {
2674 // Replace the placeholder with the appropriate argument slot GEP.
2675 llvm::Instruction *Placeholder =
2676 cast<llvm::Instruction>(RV.getAggregateAddr());
2677 CGBuilderTy::InsertPoint IP = Builder.saveIP();
2678 Builder.SetInsertPoint(Placeholder);
2679 llvm::Value *Addr = Builder.CreateStructGEP(
2680 ArgMemory, ArgInfo.getInAllocaFieldIndex());
2681 Builder.restoreIP(IP);
2682 deferPlaceholderReplacement(Placeholder, Addr);
2683 } else {
2684 // Store the RValue into the argument struct.
2685 llvm::Value *Addr =
2686 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
2687 unsigned AS = Addr->getType()->getPointerAddressSpace();
2688 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
2689 // There are some cases where a trivial bitcast is not avoidable. The
2690 // definition of a type later in a translation unit may change it's type
2691 // from {}* to (%struct.foo*)*.
2692 if (Addr->getType() != MemType)
2693 Addr = Builder.CreateBitCast(Addr, MemType);
2694 LValue argLV = MakeAddrLValue(Addr, I->Ty, TypeAlign);
2695 EmitInitStoreOfNonAggregate(*this, RV, argLV);
2696 }
2697 break; // Don't increment IRArgNo!
2698 }
2699
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002700 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00002701 if (RV.isScalar() || RV.isComplex()) {
2702 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00002703 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2704 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2705 AI->setAlignment(ArgInfo.getIndirectAlign());
2706 Args.push_back(AI);
John McCall9d232c82013-03-07 21:37:08 +00002707
Stephen Hines651f13c2014-04-23 16:59:28 -07002708 LValue argLV = MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
2709 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Chris Lattner70855442011-07-12 04:46:18 +00002710
2711 // Validate argument match.
2712 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002713 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002714 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyeid436c992013-03-10 12:59:00 +00002715 // however, we need one in three cases:
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002716 // 1. If the argument is not byval, and we are required to copy the
2717 // source. (This case doesn't occur on any common architecture.)
2718 // 2. If the argument is byval, RV is not sufficiently aligned, and
2719 // we cannot force it to be sufficiently aligned.
Guy Benyeid436c992013-03-10 12:59:00 +00002720 // 3. If the argument is byval, but RV is located in an address space
2721 // different than that of the argument (0).
Eli Friedman97cb5a42011-06-15 22:09:18 +00002722 llvm::Value *Addr = RV.getAggregateAddr();
2723 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmow25a6a842012-10-08 16:25:52 +00002724 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyeid436c992013-03-10 12:59:00 +00002725 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2726 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2727 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedman97cb5a42011-06-15 22:09:18 +00002728 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall9d232c82013-03-07 21:37:08 +00002729 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyeid436c992013-03-10 12:59:00 +00002730 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2731 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002732 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002733 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2734 if (Align > AI->getAlignment())
2735 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002736 Args.push_back(AI);
Chad Rosier649b4a12012-03-29 17:37:10 +00002737 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattner70855442011-07-12 04:46:18 +00002738
2739 // Validate argument match.
2740 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002741 } else {
2742 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002743 Args.push_back(Addr);
Chris Lattner70855442011-07-12 04:46:18 +00002744
2745 // Validate argument match.
2746 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002747 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002748 }
2749 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002750 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002751
Daniel Dunbar11434922009-01-26 21:26:08 +00002752 case ABIArgInfo::Ignore:
2753 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002754
Chris Lattner800588f2010-07-29 06:26:06 +00002755 case ABIArgInfo::Extend:
2756 case ABIArgInfo::Direct: {
2757 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00002758 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2759 ArgInfo.getDirectOffset() == 0) {
Chris Lattner70855442011-07-12 04:46:18 +00002760 llvm::Value *V;
Chris Lattner800588f2010-07-29 06:26:06 +00002761 if (RV.isScalar())
Chris Lattner70855442011-07-12 04:46:18 +00002762 V = RV.getScalarVal();
Chris Lattner800588f2010-07-29 06:26:06 +00002763 else
Chris Lattner70855442011-07-12 04:46:18 +00002764 V = Builder.CreateLoad(RV.getAggregateAddr());
2765
Chris Lattner21ca1fd2011-07-12 04:53:39 +00002766 // If the argument doesn't match, perform a bitcast to coerce it. This
2767 // can happen due to trivial type mismatches.
2768 if (IRArgNo < IRFuncTy->getNumParams() &&
2769 V->getType() != IRFuncTy->getParamType(IRArgNo))
2770 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattner70855442011-07-12 04:46:18 +00002771 Args.push_back(V);
2772
Chris Lattner70855442011-07-12 04:46:18 +00002773 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattner800588f2010-07-29 06:26:06 +00002774 break;
2775 }
Daniel Dunbar11434922009-01-26 21:26:08 +00002776
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002777 // FIXME: Avoid the conversion through memory if possible.
2778 llvm::Value *SrcPtr;
John McCall9d232c82013-03-07 21:37:08 +00002779 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00002780 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall9d232c82013-03-07 21:37:08 +00002781 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
Stephen Hines651f13c2014-04-23 16:59:28 -07002782 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Mike Stump1eb44332009-09-09 15:08:12 +00002783 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002784 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002785
Chris Lattner117e3f42010-07-30 04:02:24 +00002786 // If the value is offset in memory, apply the offset now.
2787 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2788 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2789 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002790 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002791 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2792
2793 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002794
Chris Lattnerce700162010-06-28 23:44:11 +00002795 // If the coerce-to type is a first class aggregate, we flatten it and
2796 // pass the elements. Either way is semantically identical, but fast-isel
2797 // and the optimizer generally likes scalar values better than FCAs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002798 // We cannot do this for functions using the AAPCS calling convention,
2799 // as structures are treated differently by that calling convention.
2800 llvm::StructType *STy =
2801 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
2802 if (STy && !isAAPCSVFP(CallInfo, getTarget())) {
Chandler Carruthf82232c2012-10-10 11:29:08 +00002803 llvm::Type *SrcTy =
2804 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2805 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2806 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2807
2808 // If the source type is smaller than the destination type of the
2809 // coerce-to logic, copy the source value into a temp alloca the size
2810 // of the destination type to allow loading all of it. The bits past
2811 // the source value are left undef.
2812 if (SrcSize < DstSize) {
2813 llvm::AllocaInst *TempAlloca
2814 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2815 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2816 SrcPtr = TempAlloca;
2817 } else {
2818 SrcPtr = Builder.CreateBitCast(SrcPtr,
2819 llvm::PointerType::getUnqual(STy));
2820 }
2821
Chris Lattner92826882010-07-05 20:41:41 +00002822 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2823 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00002824 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2825 // We don't know what we're loading from.
2826 LI->setAlignment(1);
2827 Args.push_back(LI);
Chris Lattner70855442011-07-12 04:46:18 +00002828
2829 // Validate argument match.
2830 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner309c59f2010-06-29 00:06:42 +00002831 }
Chris Lattnerce700162010-06-28 23:44:11 +00002832 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00002833 // In the simple case, just pass the coerced loaded value.
2834 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2835 *this));
Chris Lattner70855442011-07-12 04:46:18 +00002836
2837 // Validate argument match.
2838 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattnerce700162010-06-28 23:44:11 +00002839 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002840
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002841 break;
2842 }
2843
Daniel Dunbar56273772008-09-17 00:51:38 +00002844 case ABIArgInfo::Expand:
Chris Lattner811bf362011-07-12 06:29:11 +00002845 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattner70855442011-07-12 04:46:18 +00002846 IRArgNo = Args.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00002847 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002848 }
2849 }
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002851 if (SwapThisWithSRet)
2852 std::swap(Args[0], Args[1]);
2853
Stephen Hines651f13c2014-04-23 16:59:28 -07002854 if (ArgMemory) {
2855 llvm::Value *Arg = ArgMemory;
2856 llvm::Type *LastParamTy =
2857 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
2858 if (Arg->getType() != LastParamTy) {
2859#ifndef NDEBUG
2860 // Assert that these structs have equivalent element types.
2861 llvm::StructType *FullTy = CallInfo.getArgStruct();
2862 llvm::StructType *Prefix = cast<llvm::StructType>(
2863 cast<llvm::PointerType>(LastParamTy)->getElementType());
2864
2865 // For variadic functions, the caller might supply a larger struct than
2866 // the callee expects, and that's OK.
2867 assert(Prefix->getNumElements() == FullTy->getNumElements() ||
2868 (CallInfo.isVariadic() &&
2869 Prefix->getNumElements() <= FullTy->getNumElements()));
2870
2871 for (llvm::StructType::element_iterator PI = Prefix->element_begin(),
2872 PE = Prefix->element_end(),
2873 FI = FullTy->element_begin();
2874 PI != PE; ++PI, ++FI)
2875 assert(*PI == *FI);
2876#endif
2877 Arg = Builder.CreateBitCast(Arg, LastParamTy);
2878 }
2879 Args.push_back(Arg);
2880 }
2881
Reid Kleckner9b601952013-06-21 12:45:15 +00002882 if (!CallArgs.getCleanupsToDeactivate().empty())
2883 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2884
Chris Lattner5db7ae52009-06-13 00:26:38 +00002885 // If the callee is a bitcast of a function to a varargs pointer to function
2886 // type, check to see if we can remove the bitcast. This handles some cases
2887 // with unprototyped functions.
2888 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2889 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002890 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2891 llvm::FunctionType *CurFT =
Chris Lattner5db7ae52009-06-13 00:26:38 +00002892 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002893 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Chris Lattner5db7ae52009-06-13 00:26:38 +00002895 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2896 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00002897 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00002898 ActualFT->getNumParams() == Args.size() &&
2899 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00002900 bool ArgsMatch = true;
2901 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2902 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2903 ArgsMatch = false;
2904 break;
2905 }
Mike Stump1eb44332009-09-09 15:08:12 +00002906
Chris Lattner5db7ae52009-06-13 00:26:38 +00002907 // Strip the cast if we can get away with it. This is a nice cleanup,
2908 // but also allows us to inline the function at -O0 if it is marked
2909 // always_inline.
2910 if (ArgsMatch)
2911 Callee = CalleeF;
2912 }
2913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002915 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00002916 CodeGen::AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +00002917 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2918 CallingConv, true);
Bill Wendling785b7782012-12-07 23:17:26 +00002919 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendling94236e72013-02-22 00:13:35 +00002920 AttributeList);
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002922 llvm::BasicBlock *InvokeDest = nullptr;
Bill Wendling01ad9542012-12-30 10:32:17 +00002923 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2924 llvm::Attribute::NoUnwind))
John McCallf1549f62010-07-06 01:34:17 +00002925 InvokeDest = getInvokeDest();
2926
Daniel Dunbard14151d2009-03-02 04:32:35 +00002927 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00002928 if (!InvokeDest) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002929 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002930 } else {
2931 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad4c7d9f12011-07-15 08:37:34 +00002932 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002933 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002934 }
Chris Lattnerce933992010-06-29 16:40:28 +00002935 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00002936 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002937
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002938 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
2939 !CS.hasFnAttr(llvm::Attribute::NoInline))
2940 Attrs =
2941 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
2942 llvm::Attribute::AlwaysInline);
2943
Daniel Dunbard14151d2009-03-02 04:32:35 +00002944 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002945 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00002946
Dan Gohmanb49bd272012-02-16 00:57:37 +00002947 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2948 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002949 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002950 AddObjCARCExceptionMetadata(CS.getInstruction());
2951
Daniel Dunbard14151d2009-03-02 04:32:35 +00002952 // If the call doesn't return, finish the basic block and clear the
2953 // insertion point; this allows the rest of IRgen to discard
2954 // unreachable code.
2955 if (CS.doesNotReturn()) {
2956 Builder.CreateUnreachable();
2957 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Mike Stumpf5408fe2009-05-16 07:57:57 +00002959 // FIXME: For now, emit a dummy basic block because expr emitters in
2960 // generally are not ready to handle emitting expressions at unreachable
2961 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00002962 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Daniel Dunbard14151d2009-03-02 04:32:35 +00002964 // Return a reasonable RValue.
2965 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002966 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00002967
2968 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00002969 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002970 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002971
John McCallf85e1932011-06-15 23:02:42 +00002972 // Emit any writebacks immediately. Arguably this should happen
2973 // after any return-value munging.
2974 if (CallArgs.hasWritebacks())
2975 emitWritebacks(*this, CallArgs);
2976
Stephen Hines651f13c2014-04-23 16:59:28 -07002977 // The stack cleanup for inalloca arguments has to run out of the normal
2978 // lexical order, so deactivate it and run it manually here.
2979 CallArgs.freeArgumentMemory(*this);
2980
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002981 switch (RetAI.getKind()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002982 case ABIArgInfo::InAlloca:
John McCall9d232c82013-03-07 21:37:08 +00002983 case ABIArgInfo::Indirect:
Stephen Hines651f13c2014-04-23 16:59:28 -07002984 return convertTempToRValue(SRetPtr, RetTy, SourceLocation());
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002985
Daniel Dunbar11434922009-01-26 21:26:08 +00002986 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00002987 // If we are ignoring an argument that had a result, make sure to
2988 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00002989 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002990
Chris Lattner800588f2010-07-29 06:26:06 +00002991 case ABIArgInfo::Extend:
2992 case ABIArgInfo::Direct: {
Chris Lattner6af13f32011-07-13 03:59:32 +00002993 llvm::Type *RetIRTy = ConvertType(RetTy);
2994 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall9d232c82013-03-07 21:37:08 +00002995 switch (getEvaluationKind(RetTy)) {
2996 case TEK_Complex: {
Chris Lattner800588f2010-07-29 06:26:06 +00002997 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2998 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2999 return RValue::getComplex(std::make_pair(Real, Imag));
3000 }
John McCall9d232c82013-03-07 21:37:08 +00003001 case TEK_Aggregate: {
Chris Lattner800588f2010-07-29 06:26:06 +00003002 llvm::Value *DestPtr = ReturnValue.getValue();
3003 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00003004
Chris Lattner800588f2010-07-29 06:26:06 +00003005 if (!DestPtr) {
3006 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
3007 DestIsVolatile = false;
3008 }
Eli Friedmanbadea572011-05-17 21:08:01 +00003009 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00003010 return RValue::getAggregate(DestPtr);
3011 }
John McCall9d232c82013-03-07 21:37:08 +00003012 case TEK_Scalar: {
3013 // If the argument doesn't match, perform a bitcast to coerce it. This
3014 // can happen due to trivial type mismatches.
3015 llvm::Value *V = CI;
3016 if (V->getType() != RetIRTy)
3017 V = Builder.CreateBitCast(V, RetIRTy);
3018 return RValue::get(V);
3019 }
3020 }
3021 llvm_unreachable("bad evaluation kind");
Chris Lattner800588f2010-07-29 06:26:06 +00003022 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003023
Anders Carlssond2490a92009-12-24 20:40:36 +00003024 llvm::Value *DestPtr = ReturnValue.getValue();
3025 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003026
Anders Carlssond2490a92009-12-24 20:40:36 +00003027 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00003028 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00003029 DestIsVolatile = false;
3030 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003031
Chris Lattner117e3f42010-07-30 04:02:24 +00003032 // If the value is offset in memory, apply the offset now.
3033 llvm::Value *StorePtr = DestPtr;
3034 if (unsigned Offs = RetAI.getDirectOffset()) {
3035 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
3036 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003037 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00003038 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
3039 }
3040 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00003041
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00003042 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Daniel Dunbar639ffe42008-09-10 07:04:09 +00003043 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00003044
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00003045 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00003046 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00003047 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00003048
David Blaikieb219cfc2011-09-23 05:06:16 +00003049 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00003050}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00003051
3052/* VarArg handling */
3053
3054llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
3055 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
3056}