blob: b65b659fcc2e03cc7fa18b949eef8b5608b8b603 [file] [log] [blame]
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001//===--- CGCall.cpp - Encapsulate calling convention details --------------===//
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnere70a0072010-06-29 16:40:28 +000016#include "ABIInfo.h"
Akira Hatanaka9d8ac612016-02-17 21:09:50 +000017#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCXXABI.h"
David Majnemer4e52d6f2015-12-12 05:39:21 +000019#include "CGCleanup.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000020#include "CodeGenFunction.h"
Daniel Dunbarc68897d2008-09-10 00:41:16 +000021#include "CodeGenModule.h"
John McCalla729c622012-02-17 03:33:10 +000022#include "TargetInfo.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000023#include "clang/AST/Decl.h"
Anders Carlssonb15b55c2009-04-03 22:48:58 +000024#include "clang/AST/DeclCXX.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000025#include "clang/AST/DeclObjC.h"
Eric Christopher15709992015-10-15 23:47:11 +000026#include "clang/Basic/TargetBuiltins.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000029#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Bill Wendling706469b2013-02-28 22:49:57 +000031#include "llvm/ADT/StringExtras.h"
Nick Lewyckyd9bce502016-09-20 15:49:58 +000032#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Attributes.h"
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000034#include "llvm/IR/CallingConv.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000035#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000036#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/InlineAsm.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000038#include "llvm/IR/Intrinsics.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000039#include "llvm/IR/IntrinsicInst.h"
Eli Friedmanf7456192011-06-15 22:09:18 +000040#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000041using namespace clang;
42using namespace CodeGen;
43
44/***/
45
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000046unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
John McCallab26cfa2010-02-05 21:31:56 +000047 switch (CC) {
48 default: return llvm::CallingConv::C;
49 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
50 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Erich Keane757d3172016-11-02 18:29:35 +000051 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
Douglas Gregora941dca2010-05-18 16:57:00 +000052 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Charles Davisb5a214e2013-08-30 04:39:01 +000053 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
54 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
Anton Korobeynikov231e8752011-04-14 20:06:49 +000055 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
56 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyeif0a014b2012-12-25 08:53:55 +000057 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Reid Klecknerd7857f02014-10-24 17:42:17 +000058 // TODO: Add support for __pascal to LLVM.
59 case CC_X86Pascal: return llvm::CallingConv::C;
60 // TODO: Add support for __vectorcall to LLVM.
Reid Kleckner80944df2014-10-31 22:00:51 +000061 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
Alexander Kornienko21de0ae2015-01-20 11:20:41 +000062 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +000063 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
Roman Levenstein35aa5ce2016-03-16 18:00:46 +000064 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
65 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
John McCall12f23522016-04-04 18:33:08 +000066 case CC_Swift: return llvm::CallingConv::Swift;
John McCallab26cfa2010-02-05 21:31:56 +000067 }
68}
69
John McCall8ee376f2010-02-24 07:14:12 +000070/// Derives the 'this' type for codegen purposes, i.e. ignoring method
71/// qualification.
72/// FIXME: address space qualification?
John McCall2da83a32010-02-26 00:48:12 +000073static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
74 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
75 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar7a95ca32008-09-10 04:01:49 +000076}
77
John McCall8ee376f2010-02-24 07:14:12 +000078/// Returns the canonical formal type of the given C++ method.
John McCall2da83a32010-02-26 00:48:12 +000079static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
80 return MD->getType()->getCanonicalTypeUnqualified()
81 .getAs<FunctionProtoType>();
John McCall8ee376f2010-02-24 07:14:12 +000082}
83
84/// Returns the "extra-canonicalized" return type, which discards
85/// qualifiers on the return type. Codegen doesn't care about them,
86/// and it makes ABI code a little easier to be able to assume that
87/// all parameter and return types are top-level unqualified.
John McCall2da83a32010-02-26 00:48:12 +000088static CanQualType GetReturnType(QualType RetTy) {
89 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall8ee376f2010-02-24 07:14:12 +000090}
91
John McCall8dda7b22012-07-07 06:41:13 +000092/// Arrange the argument and result information for a value of the given
93/// unprototyped freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +000094const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +000095CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCalla729c622012-02-17 03:33:10 +000096 // When translating an unprototyped function type, always use a
97 // variadic type.
Alp Toker314cc812014-01-25 16:55:45 +000098 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
Peter Collingbournef7706832014-12-12 23:41:25 +000099 /*instanceMethod=*/false,
100 /*chainCall=*/false, None,
John McCallc56a8b32016-03-11 04:30:31 +0000101 FTNP->getExtInfo(), {}, RequiredArgs(0));
John McCall8ee376f2010-02-24 07:14:12 +0000102}
103
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000104/// Adds the formal parameters in FPT to the given prefix. If any parameter in
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000105/// FPT has pass_object_size attrs, then we'll add parameters for those, too.
106static void appendParameterTypes(const CodeGenTypes &CGT,
107 SmallVectorImpl<CanQualType> &prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000108 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
109 CanQual<FunctionProtoType> FPT,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000110 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000111 // Fill out paramInfos.
112 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) {
113 assert(paramInfos.size() <= prefix.size());
114 auto protoParamInfos = FPT->getExtParameterInfos();
115 paramInfos.reserve(prefix.size() + protoParamInfos.size());
116 paramInfos.resize(prefix.size());
John McCall12f23522016-04-04 18:33:08 +0000117 paramInfos.append(protoParamInfos.begin(), protoParamInfos.end());
John McCallc56a8b32016-03-11 04:30:31 +0000118 }
119
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000120 // Fast path: unknown target.
121 if (FD == nullptr) {
122 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
123 return;
124 }
125
126 // In the vast majority cases, we'll have precisely FPT->getNumParams()
127 // parameters; the only thing that can change this is the presence of
128 // pass_object_size. So, we preallocate for the common case.
129 prefix.reserve(prefix.size() + FPT->getNumParams());
130
131 assert(FD->getNumParams() == FPT->getNumParams());
132 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
133 prefix.push_back(FPT->getParamType(I));
134 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>())
135 prefix.push_back(CGT.getContext().getSizeType());
136 }
137}
138
John McCall8dda7b22012-07-07 06:41:13 +0000139/// Arrange the LLVM function layout for a value of the given function
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000140/// type, on top of any implicit parameters already stored.
141static const CGFunctionInfo &
Peter Collingbournef7706832014-12-12 23:41:25 +0000142arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000143 SmallVectorImpl<CanQualType> &prefix,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000144 CanQual<FunctionProtoType> FTP,
145 const FunctionDecl *FD) {
John McCallc56a8b32016-03-11 04:30:31 +0000146 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
George Burgess IV419996c2016-06-16 23:06:04 +0000147 RequiredArgs Required =
148 RequiredArgs::forPrototypePlus(FTP, prefix.size(), FD);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000149 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000150 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD);
Alp Toker314cc812014-01-25 16:55:45 +0000151 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
John McCallc56a8b32016-03-11 04:30:31 +0000152
Peter Collingbournef7706832014-12-12 23:41:25 +0000153 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
154 /*chainCall=*/false, prefix,
John McCallc56a8b32016-03-11 04:30:31 +0000155 FTP->getExtInfo(), paramInfos,
George Burgess IV419996c2016-06-16 23:06:04 +0000156 Required);
John McCall8ee376f2010-02-24 07:14:12 +0000157}
158
John McCalla729c622012-02-17 03:33:10 +0000159/// Arrange the argument and result information for a value of the
John McCall8dda7b22012-07-07 06:41:13 +0000160/// given freestanding function type.
John McCall8ee376f2010-02-24 07:14:12 +0000161const CGFunctionInfo &
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000162CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP,
163 const FunctionDecl *FD) {
John McCalla729c622012-02-17 03:33:10 +0000164 SmallVector<CanQualType, 16> argTypes;
Peter Collingbournef7706832014-12-12 23:41:25 +0000165 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000166 FTP, FD);
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000167}
168
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000169static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000170 // Set the appropriate calling convention for the Function.
171 if (D->hasAttr<StdCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000172 return CC_X86StdCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000173
174 if (D->hasAttr<FastCallAttr>())
John McCallab26cfa2010-02-05 21:31:56 +0000175 return CC_X86FastCall;
Daniel Dunbar7feafc72009-09-11 22:24:53 +0000176
Erich Keane757d3172016-11-02 18:29:35 +0000177 if (D->hasAttr<RegCallAttr>())
178 return CC_X86RegCall;
179
Douglas Gregora941dca2010-05-18 16:57:00 +0000180 if (D->hasAttr<ThisCallAttr>())
181 return CC_X86ThisCall;
182
Reid Klecknerd7857f02014-10-24 17:42:17 +0000183 if (D->hasAttr<VectorCallAttr>())
184 return CC_X86VectorCall;
185
Dawn Perchik335e16b2010-09-03 01:29:35 +0000186 if (D->hasAttr<PascalAttr>())
187 return CC_X86Pascal;
188
Anton Korobeynikov231e8752011-04-14 20:06:49 +0000189 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
190 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
191
Guy Benyeif0a014b2012-12-25 08:53:55 +0000192 if (D->hasAttr<IntelOclBiccAttr>())
193 return CC_IntelOclBicc;
194
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000195 if (D->hasAttr<MSABIAttr>())
196 return IsWindows ? CC_C : CC_X86_64Win64;
197
198 if (D->hasAttr<SysVABIAttr>())
199 return IsWindows ? CC_X86_64SysV : CC_C;
200
Roman Levenstein35aa5ce2016-03-16 18:00:46 +0000201 if (D->hasAttr<PreserveMostAttr>())
202 return CC_PreserveMost;
203
204 if (D->hasAttr<PreserveAllAttr>())
205 return CC_PreserveAll;
206
John McCallab26cfa2010-02-05 21:31:56 +0000207 return CC_C;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +0000208}
209
John McCalla729c622012-02-17 03:33:10 +0000210/// Arrange the argument and result information for a call to an
211/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000212/// (Zero value of RD means we don't have any meaningful "this" argument type,
213/// so fall back to a generic pointer type).
John McCalla729c622012-02-17 03:33:10 +0000214/// The member function must be an ordinary function, i.e. not a
215/// constructor or destructor.
216const CGFunctionInfo &
217CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000218 const FunctionProtoType *FTP,
219 const CXXMethodDecl *MD) {
John McCalla729c622012-02-17 03:33:10 +0000220 SmallVector<CanQualType, 16> argTypes;
John McCall8ee376f2010-02-24 07:14:12 +0000221
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000222 // Add the 'this' pointer.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000223 if (RD)
224 argTypes.push_back(GetThisType(Context, RD));
225 else
226 argTypes.push_back(Context.VoidPtrTy);
John McCall8ee376f2010-02-24 07:14:12 +0000227
Alexey Samsonove5ef3ca2014-08-13 23:55:54 +0000228 return ::arrangeLLVMFunctionInfo(
229 *this, true, argTypes,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000230 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD);
Anders Carlsson2ee3c012009-10-03 19:43:08 +0000231}
232
John McCalla729c622012-02-17 03:33:10 +0000233/// Arrange the argument and result information for a declaration or
234/// definition of the given C++ non-static member function. The
235/// member function must be an ordinary function, i.e. not a
236/// constructor or destructor.
237const CGFunctionInfo &
238CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
Benjamin Kramer60509af2013-09-09 14:48:42 +0000239 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
John McCall0d635f52010-09-03 01:26:39 +0000240 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
241
John McCalla729c622012-02-17 03:33:10 +0000242 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000243
John McCalla729c622012-02-17 03:33:10 +0000244 if (MD->isInstance()) {
245 // The abstract case is perfectly fine.
Mark Lacey5ea993b2013-10-02 20:35:23 +0000246 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000247 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
John McCalla729c622012-02-17 03:33:10 +0000248 }
249
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000250 return arrangeFreeFunctionType(prototype, MD);
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000251}
252
Richard Smith5179eb72016-06-28 19:03:57 +0000253bool CodeGenTypes::inheritingCtorHasParams(
254 const InheritedConstructor &Inherited, CXXCtorType Type) {
255 // Parameters are unnecessary if we're constructing a base class subobject
256 // and the inherited constructor lives in a virtual base.
257 return Type == Ctor_Complete ||
258 !Inherited.getShadowDecl()->constructsVirtualBase() ||
259 !Target.getCXXABI().hasConstructorVariants();
260 }
261
John McCalla729c622012-02-17 03:33:10 +0000262const CGFunctionInfo &
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000263CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
264 StructorType Type) {
265
John McCalla729c622012-02-17 03:33:10 +0000266 SmallVector<CanQualType, 16> argTypes;
John McCallc56a8b32016-03-11 04:30:31 +0000267 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000268 argTypes.push_back(GetThisType(Context, MD->getParent()));
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000269
Richard Smith5179eb72016-06-28 19:03:57 +0000270 bool PassParams = true;
271
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000272 GlobalDecl GD;
273 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
274 GD = GlobalDecl(CD, toCXXCtorType(Type));
Richard Smith5179eb72016-06-28 19:03:57 +0000275
276 // A base class inheriting constructor doesn't get forwarded arguments
277 // needed to construct a virtual base (or base class thereof).
278 if (auto Inherited = CD->getInheritedConstructor())
279 PassParams = inheritingCtorHasParams(Inherited, toCXXCtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000280 } else {
281 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
282 GD = GlobalDecl(DD, toCXXDtorType(Type));
283 }
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000284
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000285 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
John McCall5d865c322010-08-31 07:33:07 +0000286
287 // Add the formal parameters.
Richard Smith5179eb72016-06-28 19:03:57 +0000288 if (PassParams)
289 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD);
John McCall5d865c322010-08-31 07:33:07 +0000290
George Burgess IV75b34a92017-02-22 22:38:25 +0000291 CGCXXABI::AddedStructorArgs AddedArgs =
292 TheCXXABI.buildStructorSignature(MD, Type, argTypes);
293 if (!paramInfos.empty()) {
294 // Note: prefix implies after the first param.
295 if (AddedArgs.Prefix)
296 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
297 FunctionProtoType::ExtParameterInfo{});
298 if (AddedArgs.Suffix)
299 paramInfos.append(AddedArgs.Suffix,
300 FunctionProtoType::ExtParameterInfo{});
301 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000302
303 RequiredArgs required =
Richard Smith5179eb72016-06-28 19:03:57 +0000304 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
305 : RequiredArgs::All);
Reid Kleckner89077a12013-12-17 19:46:40 +0000306
John McCall8dda7b22012-07-07 06:41:13 +0000307 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000308 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
309 ? argTypes.front()
310 : TheCXXABI.hasMostDerivedReturn(GD)
311 ? CGM.getContext().VoidPtrTy
312 : Context.VoidTy;
Peter Collingbournef7706832014-12-12 23:41:25 +0000313 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
314 /*chainCall=*/false, argTypes, extInfo,
John McCallc56a8b32016-03-11 04:30:31 +0000315 paramInfos, required);
316}
317
318static SmallVector<CanQualType, 16>
319getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
320 SmallVector<CanQualType, 16> argTypes;
321 for (auto &arg : args)
322 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
323 return argTypes;
324}
325
326static SmallVector<CanQualType, 16>
327getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
328 SmallVector<CanQualType, 16> argTypes;
329 for (auto &arg : args)
330 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
331 return argTypes;
332}
333
334static void addExtParameterInfosForCall(
335 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
336 const FunctionProtoType *proto,
337 unsigned prefixArgs,
338 unsigned totalArgs) {
339 assert(proto->hasExtParameterInfos());
340 assert(paramInfos.size() <= prefixArgs);
341 assert(proto->getNumParams() + prefixArgs <= totalArgs);
342
343 // Add default infos for any prefix args that don't already have infos.
344 paramInfos.resize(prefixArgs);
345
346 // Add infos for the prototype.
347 auto protoInfos = proto->getExtParameterInfos();
348 paramInfos.append(protoInfos.begin(), protoInfos.end());
349
350 // Add default infos for the variadic arguments.
351 paramInfos.resize(totalArgs);
352}
353
354static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
355getExtParameterInfosForCall(const FunctionProtoType *proto,
356 unsigned prefixArgs, unsigned totalArgs) {
357 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
358 if (proto->hasExtParameterInfos()) {
359 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
360 }
361 return result;
Anders Carlsson82ba57c2009-11-25 03:15:49 +0000362}
363
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000364/// Arrange a call to a C++ method, passing the given arguments.
365const CGFunctionInfo &
366CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
367 const CXXConstructorDecl *D,
368 CXXCtorType CtorKind,
369 unsigned ExtraArgs) {
370 // FIXME: Kill copy.
371 SmallVector<CanQualType, 16> ArgTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000372 for (const auto &Arg : args)
373 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000374
375 CanQual<FunctionProtoType> FPT = GetFormalType(D);
George Burgess IV419996c2016-06-16 23:06:04 +0000376 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs, D);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000377 GlobalDecl GD(D, CtorKind);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000378 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
379 ? ArgTypes.front()
380 : TheCXXABI.hasMostDerivedReturn(GD)
381 ? CGM.getContext().VoidPtrTy
382 : Context.VoidTy;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000383
384 FunctionType::ExtInfo Info = FPT->getExtInfo();
John McCallc56a8b32016-03-11 04:30:31 +0000385 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs,
386 ArgTypes.size());
Peter Collingbournef7706832014-12-12 23:41:25 +0000387 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
388 /*chainCall=*/false, ArgTypes, Info,
John McCallc56a8b32016-03-11 04:30:31 +0000389 ParamInfos, Required);
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000390}
391
John McCalla729c622012-02-17 03:33:10 +0000392/// Arrange the argument and result information for the declaration or
393/// definition of the given function.
394const CGFunctionInfo &
395CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattnerbea5b622009-05-12 20:27:19 +0000396 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonb15b55c2009-04-03 22:48:58 +0000397 if (MD->isInstance())
John McCalla729c622012-02-17 03:33:10 +0000398 return arrangeCXXMethodDeclaration(MD);
Mike Stump11289f42009-09-09 15:08:12 +0000399
John McCall2da83a32010-02-26 00:48:12 +0000400 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCalla729c622012-02-17 03:33:10 +0000401
John McCall2da83a32010-02-26 00:48:12 +0000402 assert(isa<FunctionType>(FTy));
John McCalla729c622012-02-17 03:33:10 +0000403
404 // When declaring a function without a prototype, always use a
405 // non-variadic type.
George Burgess IV35cfca22017-01-06 19:10:48 +0000406 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000407 return arrangeLLVMFunctionInfo(
408 noProto->getReturnType(), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000409 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
John McCalla729c622012-02-17 03:33:10 +0000410 }
411
George Burgess IV35cfca22017-01-06 19:10:48 +0000412 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>(), FD);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000413}
414
John McCalla729c622012-02-17 03:33:10 +0000415/// Arrange the argument and result information for the declaration or
416/// definition of an Objective-C method.
417const CGFunctionInfo &
418CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
419 // It happens that this is the same as a call with no optional
420 // arguments, except also using the formal 'self' type.
421 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
422}
423
424/// Arrange the argument and result information for the function type
425/// through which to perform a send to the given Objective-C method,
426/// using the given receiver type. The receiver type is not always
427/// the 'self' type of the method or even an Objective-C pointer type.
428/// This is *not* the right method for actually performing such a
429/// message send, due to the possibility of optional arguments.
430const CGFunctionInfo &
431CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
432 QualType receiverType) {
433 SmallVector<CanQualType, 16> argTys;
434 argTys.push_back(Context.getCanonicalParamType(receiverType));
435 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000436 // FIXME: Kill copy?
David Majnemer59f77922016-06-24 04:05:48 +0000437 for (const auto *I : MD->parameters()) {
Aaron Ballman43b68be2014-03-07 17:50:17 +0000438 argTys.push_back(Context.getCanonicalParamType(I->getType()));
John McCall8ee376f2010-02-24 07:14:12 +0000439 }
John McCall31168b02011-06-15 23:02:42 +0000440
441 FunctionType::ExtInfo einfo;
Aaron Ballman0362a6d2013-12-18 16:23:37 +0000442 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
443 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
John McCall31168b02011-06-15 23:02:42 +0000444
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000446 MD->hasAttr<NSReturnsRetainedAttr>())
447 einfo = einfo.withProducesResult(true);
448
John McCalla729c622012-02-17 03:33:10 +0000449 RequiredArgs required =
450 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
451
Peter Collingbournef7706832014-12-12 23:41:25 +0000452 return arrangeLLVMFunctionInfo(
453 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000454 /*chainCall=*/false, argTys, einfo, {}, required);
455}
456
457const CGFunctionInfo &
458CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
459 const CallArgList &args) {
460 auto argTypes = getArgTypesForCall(Context, args);
461 FunctionType::ExtInfo einfo;
462
463 return arrangeLLVMFunctionInfo(
464 GetReturnType(returnType), /*instanceMethod=*/false,
465 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +0000466}
467
John McCalla729c622012-02-17 03:33:10 +0000468const CGFunctionInfo &
469CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000470 // FIXME: Do we need to handle ObjCMethodDecl?
471 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000472
Anders Carlsson6710c532010-02-06 02:44:09 +0000473 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000474 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
Anders Carlsson6710c532010-02-06 02:44:09 +0000475
476 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000477 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000478
John McCalla729c622012-02-17 03:33:10 +0000479 return arrangeFunctionDeclaration(FD);
Anders Carlsson6710c532010-02-06 02:44:09 +0000480}
481
Reid Klecknerc3473512014-08-29 21:43:29 +0000482/// Arrange a thunk that takes 'this' as the first parameter followed by
483/// varargs. Return a void pointer, regardless of the actual return type.
484/// The body of the thunk will end in a musttail call to a function of the
485/// correct type, and the caller will bitcast the function to the correct
486/// prototype.
487const CGFunctionInfo &
488CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
489 assert(MD->isVirtual() && "only virtual memptrs have thunks");
490 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
491 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
Peter Collingbournef7706832014-12-12 23:41:25 +0000492 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
493 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000494 FTP->getExtInfo(), {}, RequiredArgs(1));
Reid Klecknerc3473512014-08-29 21:43:29 +0000495}
496
David Majnemerdfa6d202015-03-11 18:36:39 +0000497const CGFunctionInfo &
David Majnemer37fd66e2015-03-13 22:36:55 +0000498CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
499 CXXCtorType CT) {
500 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
501
David Majnemerdfa6d202015-03-11 18:36:39 +0000502 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
503 SmallVector<CanQualType, 2> ArgTys;
504 const CXXRecordDecl *RD = CD->getParent();
505 ArgTys.push_back(GetThisType(Context, RD));
David Majnemer37fd66e2015-03-13 22:36:55 +0000506 if (CT == Ctor_CopyingClosure)
507 ArgTys.push_back(*FTP->param_type_begin());
David Majnemerdfa6d202015-03-11 18:36:39 +0000508 if (RD->getNumVBases() > 0)
509 ArgTys.push_back(Context.IntTy);
510 CallingConv CC = Context.getDefaultCallingConvention(
511 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
512 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
513 /*chainCall=*/false, ArgTys,
John McCallc56a8b32016-03-11 04:30:31 +0000514 FunctionType::ExtInfo(CC), {},
515 RequiredArgs::All);
David Majnemerdfa6d202015-03-11 18:36:39 +0000516}
517
John McCallc818bbb2012-12-07 07:03:17 +0000518/// Arrange a call as unto a free function, except possibly with an
519/// additional number of formal parameters considered required.
520static const CGFunctionInfo &
521arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
Mark Lacey23455752013-10-10 20:57:00 +0000522 CodeGenModule &CGM,
John McCallc818bbb2012-12-07 07:03:17 +0000523 const CallArgList &args,
524 const FunctionType *fnType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000525 unsigned numExtraRequiredArgs,
526 bool chainCall) {
John McCallc818bbb2012-12-07 07:03:17 +0000527 assert(args.size() >= numExtraRequiredArgs);
528
John McCallc56a8b32016-03-11 04:30:31 +0000529 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
530
John McCallc818bbb2012-12-07 07:03:17 +0000531 // In most cases, there are no optional arguments.
532 RequiredArgs required = RequiredArgs::All;
533
534 // If we have a variadic prototype, the required arguments are the
535 // extra prefix plus the arguments in the prototype.
536 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
537 if (proto->isVariadic())
Alp Toker9cacbab2014-01-20 20:26:09 +0000538 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
John McCallc818bbb2012-12-07 07:03:17 +0000539
John McCallc56a8b32016-03-11 04:30:31 +0000540 if (proto->hasExtParameterInfos())
541 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
542 args.size());
543
John McCallc818bbb2012-12-07 07:03:17 +0000544 // If we don't have a prototype at all, but we're supposed to
545 // explicitly use the variadic convention for unprototyped calls,
546 // treat all of the arguments as required but preserve the nominal
547 // possibility of variadics.
Mark Lacey23455752013-10-10 20:57:00 +0000548 } else if (CGM.getTargetCodeGenInfo()
549 .isNoProtoCallVariadic(args,
550 cast<FunctionNoProtoType>(fnType))) {
John McCallc818bbb2012-12-07 07:03:17 +0000551 required = RequiredArgs(args.size());
552 }
553
Peter Collingbournef7706832014-12-12 23:41:25 +0000554 // FIXME: Kill copy.
555 SmallVector<CanQualType, 16> argTypes;
556 for (const auto &arg : args)
557 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
558 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
559 /*instanceMethod=*/false, chainCall,
John McCallc56a8b32016-03-11 04:30:31 +0000560 argTypes, fnType->getExtInfo(), paramInfos,
561 required);
John McCallc818bbb2012-12-07 07:03:17 +0000562}
563
John McCalla729c622012-02-17 03:33:10 +0000564/// Figure out the rules for calling a function with the given formal
565/// type using the given arguments. The arguments are necessary
566/// because the function might be unprototyped, in which case it's
567/// target-dependent in crazy ways.
568const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000569CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
Peter Collingbournef7706832014-12-12 23:41:25 +0000570 const FunctionType *fnType,
571 bool chainCall) {
572 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
573 chainCall ? 1 : 0, chainCall);
John McCallc818bbb2012-12-07 07:03:17 +0000574}
John McCalla729c622012-02-17 03:33:10 +0000575
John McCallc56a8b32016-03-11 04:30:31 +0000576/// A block function is essentially a free function with an
John McCallc818bbb2012-12-07 07:03:17 +0000577/// extra implicit argument.
578const CGFunctionInfo &
579CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
580 const FunctionType *fnType) {
Peter Collingbournef7706832014-12-12 23:41:25 +0000581 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
582 /*chainCall=*/false);
John McCalla729c622012-02-17 03:33:10 +0000583}
584
585const CGFunctionInfo &
John McCallc56a8b32016-03-11 04:30:31 +0000586CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
587 const FunctionArgList &params) {
588 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
589 auto argTypes = getArgTypesForDeclaration(Context, params);
590
George Burgess IV419996c2016-06-16 23:06:04 +0000591 return arrangeLLVMFunctionInfo(
592 GetReturnType(proto->getReturnType()),
593 /*instanceMethod*/ false, /*chainCall*/ false, argTypes,
594 proto->getExtInfo(), paramInfos,
595 RequiredArgs::forPrototypePlus(proto, 1, nullptr));
John McCallc56a8b32016-03-11 04:30:31 +0000596}
597
598const CGFunctionInfo &
599CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
600 const CallArgList &args) {
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000601 // FIXME: Kill copy.
John McCalla729c622012-02-17 03:33:10 +0000602 SmallVector<CanQualType, 16> argTypes;
Alexey Samsonov3551e312014-08-13 20:06:24 +0000603 for (const auto &Arg : args)
604 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
Peter Collingbournef7706832014-12-12 23:41:25 +0000605 return arrangeLLVMFunctionInfo(
606 GetReturnType(resultType), /*instanceMethod=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000607 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
608 /*paramInfos=*/ {}, RequiredArgs::All);
John McCall8dda7b22012-07-07 06:41:13 +0000609}
610
John McCallc56a8b32016-03-11 04:30:31 +0000611const CGFunctionInfo &
612CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
613 const FunctionArgList &args) {
614 auto argTypes = getArgTypesForDeclaration(Context, args);
615
616 return arrangeLLVMFunctionInfo(
617 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
618 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
619}
620
621const CGFunctionInfo &
622CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
623 ArrayRef<CanQualType> argTypes) {
624 return arrangeLLVMFunctionInfo(
625 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
626 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
627}
628
John McCall8dda7b22012-07-07 06:41:13 +0000629/// Arrange a call to a C++ method, passing the given arguments.
630const CGFunctionInfo &
631CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
John McCallc56a8b32016-03-11 04:30:31 +0000632 const FunctionProtoType *proto,
John McCall8dda7b22012-07-07 06:41:13 +0000633 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000634 unsigned numRequiredArgs =
635 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size());
636 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams();
637 auto paramInfos =
638 getExtParameterInfosForCall(proto, numPrefixArgs, args.size());
639
John McCall8dda7b22012-07-07 06:41:13 +0000640 // FIXME: Kill copy.
John McCallc56a8b32016-03-11 04:30:31 +0000641 auto argTypes = getArgTypesForCall(Context, args);
John McCall8dda7b22012-07-07 06:41:13 +0000642
John McCallc56a8b32016-03-11 04:30:31 +0000643 FunctionType::ExtInfo info = proto->getExtInfo();
Peter Collingbournef7706832014-12-12 23:41:25 +0000644 return arrangeLLVMFunctionInfo(
John McCallc56a8b32016-03-11 04:30:31 +0000645 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
646 /*chainCall=*/false, argTypes, info, paramInfos, required);
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000647}
648
John McCalla729c622012-02-17 03:33:10 +0000649const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Peter Collingbournef7706832014-12-12 23:41:25 +0000650 return arrangeLLVMFunctionInfo(
651 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
John McCallc56a8b32016-03-11 04:30:31 +0000652 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
653}
654
655const CGFunctionInfo &
656CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
657 const CallArgList &args) {
658 assert(signature.arg_size() <= args.size());
659 if (signature.arg_size() == args.size())
660 return signature;
661
662 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
663 auto sigParamInfos = signature.getExtParameterInfos();
664 if (!sigParamInfos.empty()) {
665 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
666 paramInfos.resize(args.size());
667 }
668
669 auto argTypes = getArgTypesForCall(Context, args);
670
671 assert(signature.getRequiredArgs().allowsOptionalArgs());
672 return arrangeLLVMFunctionInfo(signature.getReturnType(),
673 signature.isInstanceMethod(),
674 signature.isChainCall(),
675 argTypes,
676 signature.getExtInfo(),
677 paramInfos,
678 signature.getRequiredArgs());
John McCalla738c252011-03-09 04:27:21 +0000679}
680
John McCalla729c622012-02-17 03:33:10 +0000681/// Arrange the argument and result information for an abstract value
682/// of a given function type. This is the method which all of the
683/// above functions ultimately defer to.
684const CGFunctionInfo &
John McCall8dda7b22012-07-07 06:41:13 +0000685CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
Peter Collingbournef7706832014-12-12 23:41:25 +0000686 bool instanceMethod,
687 bool chainCall,
John McCall8dda7b22012-07-07 06:41:13 +0000688 ArrayRef<CanQualType> argTypes,
689 FunctionType::ExtInfo info,
John McCallc56a8b32016-03-11 04:30:31 +0000690 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
John McCall8dda7b22012-07-07 06:41:13 +0000691 RequiredArgs required) {
Saleem Abdulrasool32d1a962014-11-25 03:49:50 +0000692 assert(std::all_of(argTypes.begin(), argTypes.end(),
693 std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
John McCall2da83a32010-02-26 00:48:12 +0000694
Daniel Dunbare0be8292009-02-03 00:07:12 +0000695 // Lookup or create unique function info.
696 llvm::FoldingSetNodeID ID;
John McCallc56a8b32016-03-11 04:30:31 +0000697 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
698 required, resultType, argTypes);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000699
Craig Topper8a13c412014-05-21 05:09:00 +0000700 void *insertPos = nullptr;
John McCalla729c622012-02-17 03:33:10 +0000701 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbare0be8292009-02-03 00:07:12 +0000702 if (FI)
703 return *FI;
704
John McCallc56a8b32016-03-11 04:30:31 +0000705 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
706
John McCalla729c622012-02-17 03:33:10 +0000707 // Construct the function info. We co-allocate the ArgInfos.
Peter Collingbournef7706832014-12-12 23:41:25 +0000708 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
John McCallc56a8b32016-03-11 04:30:31 +0000709 paramInfos, resultType, argTypes, required);
John McCalla729c622012-02-17 03:33:10 +0000710 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar313321e2009-02-03 05:31:23 +0000711
David Blaikie82e95a32014-11-19 07:49:47 +0000712 bool inserted = FunctionsBeingProcessed.insert(FI).second;
713 (void)inserted;
John McCalla729c622012-02-17 03:33:10 +0000714 assert(inserted && "Recursively being processed?");
Chris Lattner6fb0ccf2011-07-15 05:16:14 +0000715
Daniel Dunbar313321e2009-02-03 05:31:23 +0000716 // Compute ABI information.
John McCall12f23522016-04-04 18:33:08 +0000717 if (info.getCC() != CC_Swift) {
718 getABIInfo().computeInfo(*FI);
719 } else {
720 swiftcall::computeABIInfo(CGM, *FI);
721 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000722
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000723 // Loop over all of the computed argument and return value info. If any of
724 // them are direct or extend without a specified coerce type, specify the
725 // default now.
John McCalla729c622012-02-17 03:33:10 +0000726 ABIArgInfo &retInfo = FI->getReturnInfo();
Craig Topper8a13c412014-05-21 05:09:00 +0000727 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
John McCalla729c622012-02-17 03:33:10 +0000728 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000729
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000730 for (auto &I : FI->arguments())
Craig Topper8a13c412014-05-21 05:09:00 +0000731 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000732 I.info.setCoerceToType(ConvertType(I.type));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +0000733
John McCalla729c622012-02-17 03:33:10 +0000734 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
735 assert(erased && "Not in set?");
Chris Lattner1a651332011-07-15 06:41:05 +0000736
Daniel Dunbare0be8292009-02-03 00:07:12 +0000737 return *FI;
Daniel Dunbarbf8c24a2009-02-02 23:23:47 +0000738}
739
John McCalla729c622012-02-17 03:33:10 +0000740CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
Peter Collingbournef7706832014-12-12 23:41:25 +0000741 bool instanceMethod,
742 bool chainCall,
John McCalla729c622012-02-17 03:33:10 +0000743 const FunctionType::ExtInfo &info,
John McCallc56a8b32016-03-11 04:30:31 +0000744 ArrayRef<ExtParameterInfo> paramInfos,
John McCalla729c622012-02-17 03:33:10 +0000745 CanQualType resultType,
746 ArrayRef<CanQualType> argTypes,
747 RequiredArgs required) {
John McCallc56a8b32016-03-11 04:30:31 +0000748 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
749
750 void *buffer =
751 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
752 argTypes.size() + 1, paramInfos.size()));
753
John McCalla729c622012-02-17 03:33:10 +0000754 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
755 FI->CallingConvention = llvmCC;
756 FI->EffectiveCallingConvention = llvmCC;
757 FI->ASTCallingConvention = info.getCC();
Peter Collingbournef7706832014-12-12 23:41:25 +0000758 FI->InstanceMethod = instanceMethod;
759 FI->ChainCall = chainCall;
John McCalla729c622012-02-17 03:33:10 +0000760 FI->NoReturn = info.getNoReturn();
761 FI->ReturnsRetained = info.getProducesResult();
762 FI->Required = required;
763 FI->HasRegParm = info.getHasRegParm();
764 FI->RegParm = info.getRegParm();
Craig Topper8a13c412014-05-21 05:09:00 +0000765 FI->ArgStruct = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000766 FI->ArgStructAlign = 0;
John McCalla729c622012-02-17 03:33:10 +0000767 FI->NumArgs = argTypes.size();
John McCallc56a8b32016-03-11 04:30:31 +0000768 FI->HasExtParameterInfos = !paramInfos.empty();
John McCalla729c622012-02-17 03:33:10 +0000769 FI->getArgsBuffer()[0].type = resultType;
770 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
771 FI->getArgsBuffer()[i + 1].type = argTypes[i];
John McCallc56a8b32016-03-11 04:30:31 +0000772 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
773 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
John McCalla729c622012-02-17 03:33:10 +0000774 return FI;
Daniel Dunbar313321e2009-02-03 05:31:23 +0000775}
776
777/***/
778
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000779namespace {
780// ABIArgInfo::Expand implementation.
781
782// Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
783struct TypeExpansion {
784 enum TypeExpansionKind {
785 // Elements of constant arrays are expanded recursively.
786 TEK_ConstantArray,
787 // Record fields are expanded recursively (but if record is a union, only
788 // the field with the largest size is expanded).
789 TEK_Record,
790 // For complex types, real and imaginary parts are expanded recursively.
791 TEK_Complex,
792 // All other types are not expandable.
793 TEK_None
794 };
795
796 const TypeExpansionKind Kind;
797
798 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000799 virtual ~TypeExpansion() {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000800};
801
802struct ConstantArrayExpansion : TypeExpansion {
803 QualType EltTy;
804 uint64_t NumElts;
805
806 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
807 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
808 static bool classof(const TypeExpansion *TE) {
809 return TE->Kind == TEK_ConstantArray;
810 }
811};
812
813struct RecordExpansion : TypeExpansion {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000814 SmallVector<const CXXBaseSpecifier *, 1> Bases;
815
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000816 SmallVector<const FieldDecl *, 1> Fields;
817
Reid Klecknere9f6a712014-10-31 17:10:41 +0000818 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
819 SmallVector<const FieldDecl *, 1> &&Fields)
Benjamin Kramer0bb97742016-02-13 16:00:13 +0000820 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
821 Fields(std::move(Fields)) {}
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000822 static bool classof(const TypeExpansion *TE) {
823 return TE->Kind == TEK_Record;
824 }
825};
826
827struct ComplexExpansion : TypeExpansion {
828 QualType EltTy;
829
830 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
831 static bool classof(const TypeExpansion *TE) {
832 return TE->Kind == TEK_Complex;
833 }
834};
835
836struct NoExpansion : TypeExpansion {
837 NoExpansion() : TypeExpansion(TEK_None) {}
838 static bool classof(const TypeExpansion *TE) {
839 return TE->Kind == TEK_None;
840 }
841};
842} // namespace
843
844static std::unique_ptr<TypeExpansion>
845getTypeExpansion(QualType Ty, const ASTContext &Context) {
846 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
847 return llvm::make_unique<ConstantArrayExpansion>(
848 AT->getElementType(), AT->getSize().getZExtValue());
849 }
850 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000851 SmallVector<const CXXBaseSpecifier *, 1> Bases;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000852 SmallVector<const FieldDecl *, 1> Fields;
Bob Wilsone826a2a2011-08-03 05:58:22 +0000853 const RecordDecl *RD = RT->getDecl();
854 assert(!RD->hasFlexibleArrayMember() &&
855 "Cannot expand structure with flexible array.");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000856 if (RD->isUnion()) {
857 // Unions can be here only in degenerative cases - all the fields are same
858 // after flattening. Thus we have to use the "largest" field.
Craig Topper8a13c412014-05-21 05:09:00 +0000859 const FieldDecl *LargestFD = nullptr;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000860 CharUnits UnionSize = CharUnits::Zero();
861
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000862 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000863 // Skip zero length bitfields.
864 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
865 continue;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000866 assert(!FD->isBitField() &&
867 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000868 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000869 if (UnionSize < FieldSize) {
870 UnionSize = FieldSize;
871 LargestFD = FD;
872 }
873 }
874 if (LargestFD)
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000875 Fields.push_back(LargestFD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000876 } else {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000877 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
878 assert(!CXXRD->isDynamicClass() &&
879 "cannot expand vtable pointers in dynamic classes");
880 for (const CXXBaseSpecifier &BS : CXXRD->bases())
881 Bases.push_back(&BS);
882 }
883
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000884 for (const auto *FD : RD->fields()) {
Reid Kleckner80944df2014-10-31 22:00:51 +0000885 // Skip zero length bitfields.
886 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
887 continue;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000888 assert(!FD->isBitField() &&
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000889 "Cannot expand structure with bit-field members.");
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000890 Fields.push_back(FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +0000891 }
Bob Wilsone826a2a2011-08-03 05:58:22 +0000892 }
Reid Klecknere9f6a712014-10-31 17:10:41 +0000893 return llvm::make_unique<RecordExpansion>(std::move(Bases),
894 std::move(Fields));
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000895 }
896 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
897 return llvm::make_unique<ComplexExpansion>(CT->getElementType());
898 }
899 return llvm::make_unique<NoExpansion>();
900}
901
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000902static int getExpansionSize(QualType Ty, const ASTContext &Context) {
903 auto Exp = getTypeExpansion(Ty, Context);
904 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
905 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
906 }
907 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
908 int Res = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +0000909 for (auto BS : RExp->Bases)
910 Res += getExpansionSize(BS->getType(), Context);
Alexey Samsonov52c0f6a2014-09-29 20:30:22 +0000911 for (auto FD : RExp->Fields)
912 Res += getExpansionSize(FD->getType(), Context);
913 return Res;
914 }
915 if (isa<ComplexExpansion>(Exp.get()))
916 return 2;
917 assert(isa<NoExpansion>(Exp.get()));
918 return 1;
919}
920
Alexey Samsonov153004f2014-09-29 22:08:00 +0000921void
922CodeGenTypes::getExpandedTypes(QualType Ty,
923 SmallVectorImpl<llvm::Type *>::iterator &TI) {
924 auto Exp = getTypeExpansion(Ty, Context);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000925 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
926 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
Alexey Samsonov153004f2014-09-29 22:08:00 +0000927 getExpandedTypes(CAExp->EltTy, TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000928 }
929 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
Reid Klecknere9f6a712014-10-31 17:10:41 +0000930 for (auto BS : RExp->Bases)
931 getExpandedTypes(BS->getType(), TI);
932 for (auto FD : RExp->Fields)
Alexey Samsonov153004f2014-09-29 22:08:00 +0000933 getExpandedTypes(FD->getType(), TI);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000934 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
935 llvm::Type *EltTy = ConvertType(CExp->EltTy);
Alexey Samsonov153004f2014-09-29 22:08:00 +0000936 *TI++ = EltTy;
937 *TI++ = EltTy;
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000938 } else {
939 assert(isa<NoExpansion>(Exp.get()));
Alexey Samsonov153004f2014-09-29 22:08:00 +0000940 *TI++ = ConvertType(Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000941 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000942}
943
John McCall7f416cc2015-09-08 08:05:57 +0000944static void forConstantArrayExpansion(CodeGenFunction &CGF,
945 ConstantArrayExpansion *CAE,
946 Address BaseAddr,
947 llvm::function_ref<void(Address)> Fn) {
948 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
949 CharUnits EltAlign =
950 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
951
952 for (int i = 0, n = CAE->NumElts; i < n; i++) {
953 llvm::Value *EltAddr =
954 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
955 Fn(Address(EltAddr, EltAlign));
956 }
957}
958
Alexey Samsonov91cf4552014-08-22 01:06:06 +0000959void CodeGenFunction::ExpandTypeFromArgs(
John McCall12f23522016-04-04 18:33:08 +0000960 QualType Ty, LValue LV, SmallVectorImpl<llvm::Value *>::iterator &AI) {
Mike Stump11289f42009-09-09 15:08:12 +0000961 assert(LV.isSimple() &&
962 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000963
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000964 auto Exp = getTypeExpansion(Ty, getContext());
965 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000966 forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
967 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000968 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
969 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
John McCall7f416cc2015-09-08 08:05:57 +0000970 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000971 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +0000972 Address This = LV.getAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +0000973 for (const CXXBaseSpecifier *BS : RExp->Bases) {
974 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +0000975 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +0000976 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
977 /*NullCheckValue=*/false, SourceLocation());
978 LValue SubLV = MakeAddrLValue(Base, BS->getType());
979
980 // Recurse onto bases.
981 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
982 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000983 for (auto FD : RExp->Fields) {
984 // FIXME: What are the right qualifiers here?
Reid Kleckner9d031092016-05-02 22:42:34 +0000985 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000986 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
Bob Wilsone826a2a2011-08-03 05:58:22 +0000987 }
John McCall7f416cc2015-09-08 08:05:57 +0000988 } else if (isa<ComplexExpansion>(Exp.get())) {
989 auto realValue = *AI++;
990 auto imagValue = *AI++;
991 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000992 } else {
993 assert(isa<NoExpansion>(Exp.get()));
994 EmitStoreThroughLValue(RValue::get(*AI++), LV);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +0000995 }
Alexey Samsonov8a0bad02014-09-29 18:41:28 +0000996}
997
998void CodeGenFunction::ExpandTypeToArgs(
999 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
1000 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1001 auto Exp = getTypeExpansion(Ty, getContext());
1002 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001003 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
1004 [&](Address EltAddr) {
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001005 RValue EltRV =
1006 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
1007 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
John McCall7f416cc2015-09-08 08:05:57 +00001008 });
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001009 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
John McCall7f416cc2015-09-08 08:05:57 +00001010 Address This = RV.getAggregateAddress();
Reid Klecknere9f6a712014-10-31 17:10:41 +00001011 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1012 // Perform a single step derived-to-base conversion.
John McCall7f416cc2015-09-08 08:05:57 +00001013 Address Base =
Reid Klecknere9f6a712014-10-31 17:10:41 +00001014 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1015 /*NullCheckValue=*/false, SourceLocation());
1016 RValue BaseRV = RValue::getAggregate(Base);
1017
1018 // Recurse onto bases.
1019 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
1020 IRCallArgPos);
1021 }
1022
1023 LValue LV = MakeAddrLValue(This, Ty);
Alexey Samsonov8a0bad02014-09-29 18:41:28 +00001024 for (auto FD : RExp->Fields) {
1025 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
1026 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
1027 IRCallArgPos);
1028 }
1029 } else if (isa<ComplexExpansion>(Exp.get())) {
1030 ComplexPairTy CV = RV.getComplexVal();
1031 IRCallArgs[IRCallArgPos++] = CV.first;
1032 IRCallArgs[IRCallArgPos++] = CV.second;
1033 } else {
1034 assert(isa<NoExpansion>(Exp.get()));
1035 assert(RV.isScalar() &&
1036 "Unexpected non-scalar rvalue during struct expansion.");
1037
1038 // Insert a bitcast as needed.
1039 llvm::Value *V = RV.getScalarVal();
1040 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1041 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1042 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1043
1044 IRCallArgs[IRCallArgPos++] = V;
1045 }
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001046}
1047
John McCall7f416cc2015-09-08 08:05:57 +00001048/// Create a temporary allocation for the purposes of coercion.
1049static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1050 CharUnits MinAlign) {
1051 // Don't use an alignment that's worse than what LLVM would prefer.
1052 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1053 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1054
1055 return CGF.CreateTempAlloca(Ty, Align);
1056}
1057
Chris Lattner895c52b2010-06-27 06:04:18 +00001058/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner1cd66982010-06-27 05:56:15 +00001059/// accessing some number of bytes out of it, try to gep into the struct to get
1060/// at its inner goodness. Dive as deep as possible without entering an element
1061/// with an in-memory size smaller than DstSize.
John McCall7f416cc2015-09-08 08:05:57 +00001062static Address
1063EnterStructPointerForCoercedAccess(Address SrcPtr,
Chris Lattner2192fe52011-07-18 04:24:23 +00001064 llvm::StructType *SrcSTy,
Chris Lattner895c52b2010-06-27 06:04:18 +00001065 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner1cd66982010-06-27 05:56:15 +00001066 // We can't dive into a zero-element struct.
1067 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001068
Chris Lattner2192fe52011-07-18 04:24:23 +00001069 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001070
Chris Lattner1cd66982010-06-27 05:56:15 +00001071 // If the first elt is at least as large as what we're looking for, or if the
James Molloy90d61012014-08-29 10:17:52 +00001072 // first element is the same size as the whole struct, we can enter it. The
1073 // comparison must be made on the store size and not the alloca size. Using
1074 // the alloca size may overstate the size of the load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001075 uint64_t FirstEltSize =
James Molloy90d61012014-08-29 10:17:52 +00001076 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001077 if (FirstEltSize < DstSize &&
James Molloy90d61012014-08-29 10:17:52 +00001078 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
Chris Lattner1cd66982010-06-27 05:56:15 +00001079 return SrcPtr;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001080
Chris Lattner1cd66982010-06-27 05:56:15 +00001081 // GEP into the first element.
John McCall7f416cc2015-09-08 08:05:57 +00001082 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001083
Chris Lattner1cd66982010-06-27 05:56:15 +00001084 // If the first element is a struct, recurse.
John McCall7f416cc2015-09-08 08:05:57 +00001085 llvm::Type *SrcTy = SrcPtr.getElementType();
Chris Lattner2192fe52011-07-18 04:24:23 +00001086 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattner895c52b2010-06-27 06:04:18 +00001087 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner1cd66982010-06-27 05:56:15 +00001088
1089 return SrcPtr;
1090}
1091
Chris Lattner055097f2010-06-27 06:26:04 +00001092/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1093/// are either integers or pointers. This does a truncation of the value if it
1094/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001095///
1096/// This behaves as if the value were coerced through memory, so on big-endian
1097/// targets the high bits are preserved in a truncation, while little-endian
1098/// targets preserve the low bits.
Chris Lattner055097f2010-06-27 06:26:04 +00001099static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2192fe52011-07-18 04:24:23 +00001100 llvm::Type *Ty,
Chris Lattner055097f2010-06-27 06:26:04 +00001101 CodeGenFunction &CGF) {
1102 if (Val->getType() == Ty)
1103 return Val;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001104
Chris Lattner055097f2010-06-27 06:26:04 +00001105 if (isa<llvm::PointerType>(Val->getType())) {
1106 // If this is Pointer->Pointer avoid conversion to and from int.
1107 if (isa<llvm::PointerType>(Ty))
1108 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001109
Chris Lattner055097f2010-06-27 06:26:04 +00001110 // Convert the pointer to an integer so we can play with its width.
Chris Lattner5e016ae2010-06-27 07:15:29 +00001111 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner055097f2010-06-27 06:26:04 +00001112 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001113
Chris Lattner2192fe52011-07-18 04:24:23 +00001114 llvm::Type *DestIntTy = Ty;
Chris Lattner055097f2010-06-27 06:26:04 +00001115 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner5e016ae2010-06-27 07:15:29 +00001116 DestIntTy = CGF.IntPtrTy;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001117
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001118 if (Val->getType() != DestIntTy) {
1119 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1120 if (DL.isBigEndian()) {
1121 // Preserve the high bits on big-endian targets.
1122 // That is what memory coercion does.
James Molloy491cefb2014-05-07 17:41:15 +00001123 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1124 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1125
Jakob Stoklund Olesen36af2522013-06-05 03:00:13 +00001126 if (SrcSize > DstSize) {
1127 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1128 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1129 } else {
1130 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1131 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1132 }
1133 } else {
1134 // Little-endian targets preserve the low bits. No shifts required.
1135 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1136 }
1137 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001138
Chris Lattner055097f2010-06-27 06:26:04 +00001139 if (isa<llvm::PointerType>(Ty))
1140 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1141 return Val;
1142}
1143
Chris Lattner1cd66982010-06-27 05:56:15 +00001144
1145
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001146/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001147/// a pointer to an object of type \arg Ty, known to be aligned to
1148/// \arg SrcAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001149///
1150/// This safely handles the case when the src type is smaller than the
1151/// destination type; in this situation the values of bits which not
1152/// present in the src are undefined.
John McCall7f416cc2015-09-08 08:05:57 +00001153static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001154 CodeGenFunction &CGF) {
John McCall7f416cc2015-09-08 08:05:57 +00001155 llvm::Type *SrcTy = Src.getElementType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001156
Chris Lattnerd200eda2010-06-28 22:51:39 +00001157 // If SrcTy and Ty are the same, just do a load.
1158 if (SrcTy == Ty)
John McCall7f416cc2015-09-08 08:05:57 +00001159 return CGF.Builder.CreateLoad(Src);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001160
Micah Villmowdd31ca12012-10-08 16:25:52 +00001161 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001162
Chris Lattner2192fe52011-07-18 04:24:23 +00001163 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001164 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
1165 SrcTy = Src.getType()->getElementType();
Chris Lattner1cd66982010-06-27 05:56:15 +00001166 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001167
Micah Villmowdd31ca12012-10-08 16:25:52 +00001168 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001169
Chris Lattner055097f2010-06-27 06:26:04 +00001170 // If the source and destination are integer or pointer types, just do an
1171 // extension or truncation to the desired type.
1172 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1173 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
John McCall7f416cc2015-09-08 08:05:57 +00001174 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
Chris Lattner055097f2010-06-27 06:26:04 +00001175 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1176 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001177
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001178 // If load is legal, just bitcast the src pointer.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001179 if (SrcSize >= DstSize) {
Mike Stump18bb9282009-05-16 07:57:57 +00001180 // Generally SrcSize is never greater than DstSize, since this means we are
1181 // losing bits. However, this can happen in cases where the structure has
1182 // additional padding, for example due to a user specified alignment.
Daniel Dunbarffdb8432009-05-13 18:54:26 +00001183 //
Mike Stump18bb9282009-05-16 07:57:57 +00001184 // FIXME: Assert that we aren't truncating non-padding bits when have access
1185 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001186 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
1187 return CGF.Builder.CreateLoad(Src);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001188 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001189
John McCall7f416cc2015-09-08 08:05:57 +00001190 // Otherwise do coercion through memory. This is stupid, but simple.
1191 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
1192 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1193 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001194 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
1195 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
John McCall7f416cc2015-09-08 08:05:57 +00001196 false);
1197 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001198}
1199
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001200// Function to store a first-class aggregate into memory. We prefer to
1201// store the elements rather than the aggregate to be more friendly to
1202// fast-isel.
1203// FIXME: Do we need to recurse here?
1204static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
John McCall7f416cc2015-09-08 08:05:57 +00001205 Address Dest, bool DestIsVolatile) {
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001206 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2192fe52011-07-18 04:24:23 +00001207 if (llvm::StructType *STy =
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001208 dyn_cast<llvm::StructType>(Val->getType())) {
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001209 const llvm::StructLayout *Layout =
1210 CGF.CGM.getDataLayout().getStructLayout(STy);
1211
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001212 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00001213 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
1214 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001215 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
John McCall7f416cc2015-09-08 08:05:57 +00001216 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001217 }
1218 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001219 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
Eli Friedmanaf9b3252011-05-17 21:08:01 +00001220 }
1221}
1222
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001223/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00001224/// where the source and destination may have different types. The
1225/// destination is known to be aligned to \arg DstAlign bytes.
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001226///
1227/// This safely handles the case when the src type is larger than the
1228/// destination type; the upper bits of the src will be lost.
1229static void CreateCoercedStore(llvm::Value *Src,
John McCall7f416cc2015-09-08 08:05:57 +00001230 Address Dst,
Anders Carlsson17490832009-12-24 20:40:36 +00001231 bool DstIsVolatile,
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001232 CodeGenFunction &CGF) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001233 llvm::Type *SrcTy = Src->getType();
John McCall7f416cc2015-09-08 08:05:57 +00001234 llvm::Type *DstTy = Dst.getType()->getElementType();
Chris Lattnerd200eda2010-06-28 22:51:39 +00001235 if (SrcTy == DstTy) {
John McCall7f416cc2015-09-08 08:05:57 +00001236 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattnerd200eda2010-06-28 22:51:39 +00001237 return;
1238 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001239
Micah Villmowdd31ca12012-10-08 16:25:52 +00001240 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001241
Chris Lattner2192fe52011-07-18 04:24:23 +00001242 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
John McCall7f416cc2015-09-08 08:05:57 +00001243 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
1244 DstTy = Dst.getType()->getElementType();
Chris Lattner895c52b2010-06-27 06:04:18 +00001245 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001246
Chris Lattner055097f2010-06-27 06:26:04 +00001247 // If the source and destination are integer or pointer types, just do an
1248 // extension or truncation to the desired type.
1249 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1250 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1251 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001252 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
Chris Lattner055097f2010-06-27 06:26:04 +00001253 return;
1254 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001255
Micah Villmowdd31ca12012-10-08 16:25:52 +00001256 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001257
Daniel Dunbar313321e2009-02-03 05:31:23 +00001258 // If store is legal, just bitcast the src pointer.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001259 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00001260 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
1261 BuildAggStore(CGF, Src, Dst, DstIsVolatile);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001262 } else {
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001263 // Otherwise do coercion through memory. This is stupid, but
1264 // simple.
Daniel Dunbar4be99ff2009-06-05 07:58:54 +00001265
1266 // Generally SrcSize is never greater than DstSize, since this means we are
1267 // losing bits. However, this can happen in cases where the structure has
1268 // additional padding, for example due to a user specified alignment.
1269 //
1270 // FIXME: Assert that we aren't truncating non-padding bits when have access
1271 // to that information.
John McCall7f416cc2015-09-08 08:05:57 +00001272 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1273 CGF.Builder.CreateStore(Src, Tmp);
1274 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
1275 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
Manman Ren84b921f2012-11-28 22:08:52 +00001276 CGF.Builder.CreateMemCpy(DstCasted, Casted,
1277 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
John McCall7f416cc2015-09-08 08:05:57 +00001278 false);
Daniel Dunbarf5589ac2009-02-02 19:06:38 +00001279 }
1280}
1281
John McCall7f416cc2015-09-08 08:05:57 +00001282static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1283 const ABIArgInfo &info) {
1284 if (unsigned offset = info.getDirectOffset()) {
1285 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1286 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1287 CharUnits::fromQuantity(offset));
1288 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1289 }
1290 return addr;
1291}
1292
Alexey Samsonov153004f2014-09-29 22:08:00 +00001293namespace {
1294
1295/// Encapsulates information about the way function arguments from
1296/// CGFunctionInfo should be passed to actual LLVM IR function.
1297class ClangToLLVMArgMapping {
1298 static const unsigned InvalidIndex = ~0U;
1299 unsigned InallocaArgNo;
1300 unsigned SRetArgNo;
1301 unsigned TotalIRArgs;
1302
1303 /// Arguments of LLVM IR function corresponding to single Clang argument.
1304 struct IRArgs {
1305 unsigned PaddingArgIndex;
1306 // Argument is expanded to IR arguments at positions
1307 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1308 unsigned FirstArgIndex;
1309 unsigned NumberOfArgs;
1310
1311 IRArgs()
1312 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1313 NumberOfArgs(0) {}
1314 };
1315
1316 SmallVector<IRArgs, 8> ArgInfo;
1317
1318public:
1319 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1320 bool OnlyRequiredArgs = false)
1321 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1322 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1323 construct(Context, FI, OnlyRequiredArgs);
1324 }
1325
1326 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
1327 unsigned getInallocaArgNo() const {
1328 assert(hasInallocaArg());
1329 return InallocaArgNo;
1330 }
1331
1332 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
1333 unsigned getSRetArgNo() const {
1334 assert(hasSRetArg());
1335 return SRetArgNo;
1336 }
1337
1338 unsigned totalIRArgs() const { return TotalIRArgs; }
1339
1340 bool hasPaddingArg(unsigned ArgNo) const {
1341 assert(ArgNo < ArgInfo.size());
1342 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1343 }
1344 unsigned getPaddingArgNo(unsigned ArgNo) const {
1345 assert(hasPaddingArg(ArgNo));
1346 return ArgInfo[ArgNo].PaddingArgIndex;
1347 }
1348
1349 /// Returns index of first IR argument corresponding to ArgNo, and their
1350 /// quantity.
1351 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1352 assert(ArgNo < ArgInfo.size());
1353 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1354 ArgInfo[ArgNo].NumberOfArgs);
1355 }
1356
1357private:
1358 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1359 bool OnlyRequiredArgs);
1360};
1361
1362void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1363 const CGFunctionInfo &FI,
1364 bool OnlyRequiredArgs) {
1365 unsigned IRArgNo = 0;
1366 bool SwapThisWithSRet = false;
1367 const ABIArgInfo &RetAI = FI.getReturnInfo();
1368
1369 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1370 SwapThisWithSRet = RetAI.isSRetAfterThis();
1371 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1372 }
1373
1374 unsigned ArgNo = 0;
1375 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1376 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1377 ++I, ++ArgNo) {
1378 assert(I != FI.arg_end());
1379 QualType ArgType = I->type;
1380 const ABIArgInfo &AI = I->info;
1381 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1382 auto &IRArgs = ArgInfo[ArgNo];
1383
1384 if (AI.getPaddingType())
1385 IRArgs.PaddingArgIndex = IRArgNo++;
1386
1387 switch (AI.getKind()) {
1388 case ABIArgInfo::Extend:
1389 case ABIArgInfo::Direct: {
1390 // FIXME: handle sseregparm someday...
1391 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1392 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1393 IRArgs.NumberOfArgs = STy->getNumElements();
1394 } else {
1395 IRArgs.NumberOfArgs = 1;
1396 }
1397 break;
1398 }
1399 case ABIArgInfo::Indirect:
1400 IRArgs.NumberOfArgs = 1;
1401 break;
1402 case ABIArgInfo::Ignore:
1403 case ABIArgInfo::InAlloca:
1404 // ignore and inalloca doesn't have matching LLVM parameters.
1405 IRArgs.NumberOfArgs = 0;
1406 break;
John McCallf26e73d2016-03-11 04:30:43 +00001407 case ABIArgInfo::CoerceAndExpand:
1408 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1409 break;
1410 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001411 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1412 break;
1413 }
Alexey Samsonov153004f2014-09-29 22:08:00 +00001414
1415 if (IRArgs.NumberOfArgs > 0) {
1416 IRArgs.FirstArgIndex = IRArgNo;
1417 IRArgNo += IRArgs.NumberOfArgs;
1418 }
1419
1420 // Skip over the sret parameter when it comes second. We already handled it
1421 // above.
1422 if (IRArgNo == 1 && SwapThisWithSRet)
1423 IRArgNo++;
1424 }
1425 assert(ArgNo == ArgInfo.size());
1426
1427 if (FI.usesInAlloca())
1428 InallocaArgNo = IRArgNo++;
1429
1430 TotalIRArgs = IRArgNo;
1431}
1432} // namespace
1433
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00001434/***/
1435
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001436bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbarb8b1c672009-02-05 08:00:50 +00001437 return FI.getReturnInfo().isIndirect();
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00001438}
1439
Tim Northovere77cc392014-03-29 13:28:05 +00001440bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1441 return ReturnTypeUsesSRet(FI) &&
1442 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1443}
1444
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001445bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1446 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1447 switch (BT->getKind()) {
1448 default:
1449 return false;
1450 case BuiltinType::Float:
John McCallc8e01702013-04-16 22:48:15 +00001451 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001452 case BuiltinType::Double:
John McCallc8e01702013-04-16 22:48:15 +00001453 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001454 case BuiltinType::LongDouble:
John McCallc8e01702013-04-16 22:48:15 +00001455 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbar6f2e8392010-07-14 23:39:36 +00001456 }
1457 }
1458
1459 return false;
1460}
1461
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001462bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1463 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1464 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1465 if (BT->getKind() == BuiltinType::LongDouble)
John McCallc8e01702013-04-16 22:48:15 +00001466 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlsson2f1a6c32011-10-31 16:27:11 +00001467 }
1468 }
1469
1470 return false;
1471}
1472
Chris Lattnera5f58b02011-07-09 17:41:47 +00001473llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCalla729c622012-02-17 03:33:10 +00001474 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1475 return GetFunctionType(FI);
John McCallf8ff7b92010-02-23 00:48:20 +00001476}
1477
Chris Lattnera5f58b02011-07-09 17:41:47 +00001478llvm::FunctionType *
John McCalla729c622012-02-17 03:33:10 +00001479CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001480
David Blaikie82e95a32014-11-19 07:49:47 +00001481 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1482 (void)Inserted;
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001483 assert(Inserted && "Recursively being processed?");
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001484
Alexey Samsonov153004f2014-09-29 22:08:00 +00001485 llvm::Type *resultType = nullptr;
John McCall85dd2c52011-05-15 02:19:42 +00001486 const ABIArgInfo &retAI = FI.getReturnInfo();
1487 switch (retAI.getKind()) {
Daniel Dunbard3674e62008-09-11 01:48:57 +00001488 case ABIArgInfo::Expand:
John McCall85dd2c52011-05-15 02:19:42 +00001489 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbard3674e62008-09-11 01:48:57 +00001490
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001491 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00001492 case ABIArgInfo::Direct:
John McCall85dd2c52011-05-15 02:19:42 +00001493 resultType = retAI.getCoerceToType();
Daniel Dunbar67dace892009-02-03 06:17:37 +00001494 break;
1495
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001496 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00001497 if (retAI.getInAllocaSRet()) {
1498 // sret things on win32 aren't void, they return the sret pointer.
1499 QualType ret = FI.getReturnType();
1500 llvm::Type *ty = ConvertType(ret);
1501 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1502 resultType = llvm::PointerType::get(ty, addressSpace);
1503 } else {
1504 resultType = llvm::Type::getVoidTy(getLLVMContext());
1505 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001506 break;
1507
John McCall7f416cc2015-09-08 08:05:57 +00001508 case ABIArgInfo::Indirect:
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001509 case ABIArgInfo::Ignore:
John McCall85dd2c52011-05-15 02:19:42 +00001510 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001511 break;
John McCallf26e73d2016-03-11 04:30:43 +00001512
1513 case ABIArgInfo::CoerceAndExpand:
1514 resultType = retAI.getUnpaddedCoerceAndExpandType();
1515 break;
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Alexey Samsonov153004f2014-09-29 22:08:00 +00001518 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1519 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1520
1521 // Add type for sret argument.
1522 if (IRFunctionArgs.hasSRetArg()) {
1523 QualType Ret = FI.getReturnType();
1524 llvm::Type *Ty = ConvertType(Ret);
1525 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1526 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1527 llvm::PointerType::get(Ty, AddressSpace);
1528 }
1529
1530 // Add type for inalloca argument.
1531 if (IRFunctionArgs.hasInallocaArg()) {
1532 auto ArgStruct = FI.getArgStruct();
1533 assert(ArgStruct);
1534 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1535 }
1536
John McCallc818bbb2012-12-07 07:03:17 +00001537 // Add in all of the required arguments.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001538 unsigned ArgNo = 0;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00001539 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1540 ie = it + FI.getNumRequiredArgs();
Alexey Samsonov153004f2014-09-29 22:08:00 +00001541 for (; it != ie; ++it, ++ArgNo) {
1542 const ABIArgInfo &ArgInfo = it->info;
Mike Stump11289f42009-09-09 15:08:12 +00001543
Rafael Espindolafad28de2012-10-24 01:59:00 +00001544 // Insert a padding type to ensure proper alignment.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001545 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1546 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1547 ArgInfo.getPaddingType();
Rafael Espindolafad28de2012-10-24 01:59:00 +00001548
Alexey Samsonov153004f2014-09-29 22:08:00 +00001549 unsigned FirstIRArg, NumIRArgs;
1550 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1551
1552 switch (ArgInfo.getKind()) {
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001553 case ABIArgInfo::Ignore:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001554 case ABIArgInfo::InAlloca:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001555 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001556 break;
1557
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001558 case ABIArgInfo::Indirect: {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001559 assert(NumIRArgs == 1);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001560 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2192fe52011-07-18 04:24:23 +00001561 llvm::Type *LTy = ConvertTypeForMem(it->type);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001562 ArgTypes[FirstIRArg] = LTy->getPointerTo();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001563 break;
1564 }
1565
1566 case ABIArgInfo::Extend:
Chris Lattner2cdfda42010-07-29 06:44:09 +00001567 case ABIArgInfo::Direct: {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00001568 // Fast-isel and the optimizer generally like scalar values better than
1569 // FCAs, so we flatten them if this is safe to do for this argument.
Alexey Samsonov153004f2014-09-29 22:08:00 +00001570 llvm::Type *argType = ArgInfo.getCoerceToType();
James Molloy6f244b62014-05-09 16:21:39 +00001571 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
Alexey Samsonov153004f2014-09-29 22:08:00 +00001572 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1573 assert(NumIRArgs == st->getNumElements());
John McCall85dd2c52011-05-15 02:19:42 +00001574 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
Alexey Samsonov153004f2014-09-29 22:08:00 +00001575 ArgTypes[FirstIRArg + i] = st->getElementType(i);
Chris Lattner3dd716c2010-06-28 23:44:11 +00001576 } else {
Alexey Samsonov153004f2014-09-29 22:08:00 +00001577 assert(NumIRArgs == 1);
1578 ArgTypes[FirstIRArg] = argType;
Chris Lattner3dd716c2010-06-28 23:44:11 +00001579 }
Daniel Dunbar2f219b02009-02-03 19:12:28 +00001580 break;
Chris Lattner2cdfda42010-07-29 06:44:09 +00001581 }
Mike Stump11289f42009-09-09 15:08:12 +00001582
John McCallf26e73d2016-03-11 04:30:43 +00001583 case ABIArgInfo::CoerceAndExpand: {
1584 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1585 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1586 *ArgTypesIter++ = EltTy;
1587 }
1588 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1589 break;
1590 }
1591
Daniel Dunbard3674e62008-09-11 01:48:57 +00001592 case ABIArgInfo::Expand:
Alexey Samsonov153004f2014-09-29 22:08:00 +00001593 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1594 getExpandedTypes(it->type, ArgTypesIter);
1595 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001596 break;
1597 }
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001598 }
1599
Chris Lattner6fb0ccf2011-07-15 05:16:14 +00001600 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1601 assert(Erased && "Not in set?");
Alexey Samsonov153004f2014-09-29 22:08:00 +00001602
1603 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
Daniel Dunbar81cf67f2008-09-09 23:48:28 +00001604}
1605
Chris Lattner2192fe52011-07-18 04:24:23 +00001606llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall5d865c322010-08-31 07:33:07 +00001607 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson64457732009-11-24 05:08:52 +00001608 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001609
Chris Lattner8806e322011-07-10 00:18:59 +00001610 if (!isFuncTypeConvertible(FPT))
1611 return llvm::StructType::get(getLLVMContext());
1612
1613 const CGFunctionInfo *Info;
1614 if (isa<CXXDestructorDecl>(MD))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001615 Info =
1616 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
Chris Lattner8806e322011-07-10 00:18:59 +00001617 else
John McCalla729c622012-02-17 03:33:10 +00001618 Info = &arrangeCXXMethodDeclaration(MD);
1619 return GetFunctionType(*Info);
Anders Carlsson64457732009-11-24 05:08:52 +00001620}
1621
Samuel Antao798f11c2015-11-23 22:04:44 +00001622static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1623 llvm::AttrBuilder &FuncAttrs,
1624 const FunctionProtoType *FPT) {
1625 if (!FPT)
1626 return;
1627
1628 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1629 FPT->isNothrow(Ctx))
1630 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1631}
1632
Justin Lebarb080b632017-01-25 21:29:48 +00001633void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone,
1634 bool AttrOnCallSite,
1635 llvm::AttrBuilder &FuncAttrs) {
1636 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1637 if (!HasOptnone) {
1638 if (CodeGenOpts.OptimizeSize)
1639 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1640 if (CodeGenOpts.OptimizeSize == 2)
1641 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1642 }
1643
1644 if (CodeGenOpts.DisableRedZone)
1645 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1646 if (CodeGenOpts.NoImplicitFloat)
1647 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1648
1649 if (AttrOnCallSite) {
1650 // Attributes that should go on the call site only.
1651 if (!CodeGenOpts.SimplifyLibCalls ||
1652 CodeGenOpts.isNoBuiltinFunc(Name.data()))
1653 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1654 if (!CodeGenOpts.TrapFuncName.empty())
1655 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1656 } else {
1657 // Attributes that should go on the function, but not the call site.
1658 if (!CodeGenOpts.DisableFPElim) {
1659 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1660 } else if (CodeGenOpts.OmitLeafFramePointer) {
1661 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
1662 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1663 } else {
1664 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
1665 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
1666 }
1667
1668 FuncAttrs.addAttribute("less-precise-fpmad",
1669 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
1670
1671 if (!CodeGenOpts.FPDenormalMode.empty())
1672 FuncAttrs.addAttribute("denormal-fp-math", CodeGenOpts.FPDenormalMode);
1673
1674 FuncAttrs.addAttribute("no-trapping-math",
1675 llvm::toStringRef(CodeGenOpts.NoTrappingMath));
1676
1677 // TODO: Are these all needed?
1678 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1679 FuncAttrs.addAttribute("no-infs-fp-math",
1680 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
1681 FuncAttrs.addAttribute("no-nans-fp-math",
1682 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
1683 FuncAttrs.addAttribute("unsafe-fp-math",
1684 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
1685 FuncAttrs.addAttribute("use-soft-float",
1686 llvm::toStringRef(CodeGenOpts.SoftFloat));
1687 FuncAttrs.addAttribute("stack-protector-buffer-size",
1688 llvm::utostr(CodeGenOpts.SSPBufferSize));
1689 FuncAttrs.addAttribute("no-signed-zeros-fp-math",
1690 llvm::toStringRef(CodeGenOpts.NoSignedZeros));
1691 FuncAttrs.addAttribute(
1692 "correctly-rounded-divide-sqrt-fp-math",
1693 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt));
1694
1695 // TODO: Reciprocal estimate codegen options should apply to instructions?
1696 std::vector<std::string> &Recips = getTarget().getTargetOpts().Reciprocals;
1697 if (!Recips.empty())
1698 FuncAttrs.addAttribute("reciprocal-estimates",
1699 llvm::join(Recips.begin(), Recips.end(), ","));
1700
1701 if (CodeGenOpts.StackRealignment)
1702 FuncAttrs.addAttribute("stackrealign");
1703 if (CodeGenOpts.Backchain)
1704 FuncAttrs.addAttribute("backchain");
1705 }
1706
1707 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1708 // Conservatively, mark all functions and calls in CUDA as convergent
1709 // (meaning, they may call an intrinsically convergent op, such as
1710 // __syncthreads(), and so can't have certain optimizations applied around
1711 // them). LLVM will remove this attribute where it safely can.
1712 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1713
1714 // Exceptions aren't supported in CUDA device code.
1715 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1716
1717 // Respect -fcuda-flush-denormals-to-zero.
1718 if (getLangOpts().CUDADeviceFlushDenormalsToZero)
1719 FuncAttrs.addAttribute("nvptx-f32ftz", "true");
1720 }
1721}
1722
1723void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) {
1724 llvm::AttrBuilder FuncAttrs;
1725 ConstructDefaultFnAttrList(F.getName(),
1726 F.hasFnAttribute(llvm::Attribute::OptimizeNone),
1727 /* AttrOnCallsite = */ false, FuncAttrs);
1728 llvm::AttributeSet AS = llvm::AttributeSet::get(
1729 getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1730 F.addAttributes(llvm::AttributeSet::FunctionIndex, AS);
1731}
1732
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00001733void CodeGenModule::ConstructAttributeList(
1734 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
1735 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) {
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001736 llvm::AttrBuilder FuncAttrs;
1737 llvm::AttrBuilder RetAttrs;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001738
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001739 CallingConv = FI.getEffectiveCallingConvention();
John McCallab26cfa2010-02-05 21:31:56 +00001740 if (FI.isNoReturn())
Bill Wendling207f0532012-12-20 19:27:06 +00001741 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallab26cfa2010-02-05 21:31:56 +00001742
Samuel Antao798f11c2015-11-23 22:04:44 +00001743 // If we have information about the function prototype, we can learn
1744 // attributes form there.
1745 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
1746 CalleeInfo.getCalleeFunctionProtoType());
1747
1748 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
1749
Justin Lebarb080b632017-01-25 21:29:48 +00001750 bool HasOptnone = false;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001751 // FIXME: handle sseregparm someday...
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001752 if (TargetDecl) {
Rafael Espindola2d21ab02011-10-12 19:51:18 +00001753 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001754 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001755 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001756 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smithdebc59d2013-01-30 05:45:05 +00001757 if (TargetDecl->hasAttr<NoReturnAttr>())
1758 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001759 if (TargetDecl->hasAttr<NoDuplicateAttr>())
1760 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
Yaxun Liu7d07ae72016-11-01 18:45:32 +00001761 if (TargetDecl->hasAttr<ConvergentAttr>())
1762 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
Richard Smithdebc59d2013-01-30 05:45:05 +00001763
1764 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
Samuel Antao798f11c2015-11-23 22:04:44 +00001765 AddAttributesFromFunctionProtoType(
1766 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
Richard Smith49af6292013-03-05 08:30:04 +00001767 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1768 // These attributes are not inherited by overloads.
1769 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1770 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smithdebc59d2013-01-30 05:45:05 +00001771 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCallbe349de2010-07-08 06:48:12 +00001772 }
1773
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001774 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
Eric Christopherbf005ec2011-08-15 22:38:22 +00001775 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001776 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1777 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001778 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling207f0532012-12-20 19:27:06 +00001779 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1780 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
David Majnemer1bf0f8e2015-07-20 22:51:52 +00001781 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
1782 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
1783 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopherbf005ec2011-08-15 22:38:22 +00001784 }
David Majnemer631a90b2015-02-04 07:23:21 +00001785 if (TargetDecl->hasAttr<RestrictAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +00001786 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Hal Finkeld8442b12014-07-12 04:51:04 +00001787 if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
1788 RetAttrs.addAttribute(llvm::Attribute::NonNull);
Paul Robinson08556952014-12-11 20:14:04 +00001789
1790 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
George Burgess IVe3763372016-12-22 02:50:20 +00001791 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
1792 Optional<unsigned> NumElemsParam;
1793 // alloc_size args are base-1, 0 means not present.
1794 if (unsigned N = AllocSize->getNumElemsParam())
1795 NumElemsParam = N - 1;
1796 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam() - 1,
1797 NumElemsParam);
1798 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001799 }
1800
Justin Lebarb080b632017-01-25 21:29:48 +00001801 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
Paul Robinson08556952014-12-11 20:14:04 +00001802
Peter Collingbourneb4728c12014-05-19 22:14:34 +00001803 if (CodeGenOpts.EnableSegmentedStacks &&
1804 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
Reid Klecknerfb873af2014-04-10 22:59:13 +00001805 FuncAttrs.addAttribute("split-stack");
Devang Patel6e467b12009-06-04 23:32:02 +00001806
Justin Lebarb080b632017-01-25 21:29:48 +00001807 if (!AttrOnCallSite) {
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001808 bool DisableTailCalls =
Justin Lebarb080b632017-01-25 21:29:48 +00001809 CodeGenOpts.DisableTailCalls ||
1810 (TargetDecl && (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
1811 TargetDecl->hasAttr<AnyX86InterruptAttr>()));
1812 FuncAttrs.addAttribute("disable-tail-calls",
1813 llvm::toStringRef(DisableTailCalls));
Eric Christopher70c16652015-03-25 23:14:47 +00001814
Eric Christopher11acf732015-06-12 01:35:52 +00001815 // Add target-cpu and target-features attributes to functions. If
1816 // we have a decl for the function and it has a target attribute then
1817 // parse that and add it to the feature set.
1818 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
Eric Christopher11acf732015-06-12 01:35:52 +00001819 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
Eric Christopherb57804a2015-09-01 22:03:56 +00001820 if (FD && FD->hasAttr<TargetAttr>()) {
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001821 llvm::StringMap<bool> FeatureMap;
Eric Christopher2b90a642015-11-11 23:05:08 +00001822 getFunctionFeatureMap(FeatureMap, FD);
Eric Christopher11acf732015-06-12 01:35:52 +00001823
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001824 // Produce the canonical string for this set of features.
1825 std::vector<std::string> Features;
1826 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
1827 ie = FeatureMap.end();
1828 it != ie; ++it)
1829 Features.push_back((it->second ? "+" : "-") + it->first().str());
Eric Christopher2249b812015-07-01 00:08:29 +00001830
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001831 // Now add the target-cpu and target-features to the function.
Eric Christopher2b90a642015-11-11 23:05:08 +00001832 // While we populated the feature map above, we still need to
1833 // get and parse the target attribute so we can get the cpu for
1834 // the function.
1835 const auto *TD = FD->getAttr<TargetAttr>();
1836 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1837 if (ParsedAttr.second != "")
1838 TargetCPU = ParsedAttr.second;
Eric Christopher3a98b3c2015-08-27 19:59:34 +00001839 if (TargetCPU != "")
1840 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1841 if (!Features.empty()) {
1842 std::sort(Features.begin(), Features.end());
1843 FuncAttrs.addAttribute(
1844 "target-features",
1845 llvm::join(Features.begin(), Features.end(), ","));
1846 }
1847 } else {
1848 // Otherwise just add the existing target cpu and target features to the
1849 // function.
1850 std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
1851 if (TargetCPU != "")
1852 FuncAttrs.addAttribute("target-cpu", TargetCPU);
1853 if (!Features.empty()) {
1854 std::sort(Features.begin(), Features.end());
1855 FuncAttrs.addAttribute(
1856 "target-features",
1857 llvm::join(Features.begin(), Features.end(), ","));
1858 }
Eric Christopher70c16652015-03-25 23:14:47 +00001859 }
Bill Wendling985d1c52013-02-15 21:30:01 +00001860 }
1861
Alexey Samsonov153004f2014-09-29 22:08:00 +00001862 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001863
Daniel Dunbar3668cb22009-02-02 23:43:58 +00001864 QualType RetTy = FI.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00001865 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar7a95ca32008-09-10 04:01:49 +00001866 switch (RetAI.getKind()) {
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001867 case ABIArgInfo::Extend:
Jakob Stoklund Olesend7bf2932013-05-29 03:57:23 +00001868 if (RetTy->hasSignedIntegerRepresentation())
1869 RetAttrs.addAttribute(llvm::Attribute::SExt);
1870 else if (RetTy->hasUnsignedIntegerRepresentation())
1871 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001872 // FALL THROUGH
Daniel Dunbar67dace892009-02-03 06:17:37 +00001873 case ABIArgInfo::Direct:
Jakob Stoklund Olesena3661142013-06-05 03:00:09 +00001874 if (RetAI.getInReg())
1875 RetAttrs.addAttribute(llvm::Attribute::InReg);
1876 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001877 case ABIArgInfo::Ignore:
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001878 break;
1879
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001880 case ABIArgInfo::InAlloca:
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001881 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001882 // inalloca and sret disable readnone and readonly
Bill Wendling207f0532012-12-20 19:27:06 +00001883 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1884 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001885 break;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001886 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001887
John McCallf26e73d2016-03-11 04:30:43 +00001888 case ABIArgInfo::CoerceAndExpand:
1889 break;
1890
Daniel Dunbard3674e62008-09-11 01:48:57 +00001891 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00001892 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00001893 }
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00001894
Hal Finkela2347ba2014-07-18 15:52:10 +00001895 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
1896 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00001897 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00001898 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
1899 .getQuantity());
1900 else if (getContext().getTargetAddressSpace(PTy) == 0)
1901 RetAttrs.addAttribute(llvm::Attribute::NonNull);
1902 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00001903
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001904 // Attach return attributes.
1905 if (RetAttrs.hasAttributes()) {
1906 PAL.push_back(llvm::AttributeSet::get(
1907 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
1908 }
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001909
John McCall12f23522016-04-04 18:33:08 +00001910 bool hasUsedSRet = false;
1911
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001912 // Attach attributes to sret.
1913 if (IRFunctionArgs.hasSRetArg()) {
1914 llvm::AttrBuilder SRETAttrs;
1915 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
John McCall12f23522016-04-04 18:33:08 +00001916 hasUsedSRet = true;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001917 if (RetAI.getInReg())
1918 SRETAttrs.addAttribute(llvm::Attribute::InReg);
1919 PAL.push_back(llvm::AttributeSet::get(
1920 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
1921 }
1922
1923 // Attach attributes to inalloca argument.
1924 if (IRFunctionArgs.hasInallocaArg()) {
1925 llvm::AttrBuilder Attrs;
1926 Attrs.addAttribute(llvm::Attribute::InAlloca);
1927 PAL.push_back(llvm::AttributeSet::get(
1928 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
1929 }
1930
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001931 unsigned ArgNo = 0;
1932 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
1933 E = FI.arg_end();
1934 I != E; ++I, ++ArgNo) {
1935 QualType ParamType = I->type;
1936 const ABIArgInfo &AI = I->info;
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001937 llvm::AttrBuilder Attrs;
Anton Korobeynikovc8478242009-04-04 00:49:24 +00001938
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001939 // Add attribute for padding argument, if necessary.
1940 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
Bill Wendling290d9522013-01-27 02:46:53 +00001941 if (AI.getPaddingInReg())
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001942 PAL.push_back(llvm::AttributeSet::get(
1943 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
1944 llvm::Attribute::InReg));
Rafael Espindolafad28de2012-10-24 01:59:00 +00001945 }
1946
John McCall39ec71f2010-03-27 00:47:27 +00001947 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1948 // have the corresponding parameter variable. It doesn't make
Daniel Dunbarcb2b3d02011-02-10 18:10:07 +00001949 // sense to do it here because parameters are so messed up.
Daniel Dunbard3674e62008-09-11 01:48:57 +00001950 switch (AI.getKind()) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001951 case ABIArgInfo::Extend:
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001952 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling207f0532012-12-20 19:27:06 +00001953 Attrs.addAttribute(llvm::Attribute::SExt);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00001954 else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
1955 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
1956 Attrs.addAttribute(llvm::Attribute::SExt);
1957 else
1958 Attrs.addAttribute(llvm::Attribute::ZExt);
1959 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001960 // FALL THROUGH
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001961 case ABIArgInfo::Direct:
Peter Collingbournef7706832014-12-12 23:41:25 +00001962 if (ArgNo == 0 && FI.isChainCall())
1963 Attrs.addAttribute(llvm::Attribute::Nest);
1964 else if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001965 Attrs.addAttribute(llvm::Attribute::InReg);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001966 break;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00001967
James Y Knight71608572015-08-21 18:19:06 +00001968 case ABIArgInfo::Indirect: {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001969 if (AI.getInReg())
Bill Wendling207f0532012-12-20 19:27:06 +00001970 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001971
Anders Carlsson20759ad2009-09-16 15:53:40 +00001972 if (AI.getIndirectByVal())
Bill Wendling207f0532012-12-20 19:27:06 +00001973 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001974
John McCall7f416cc2015-09-08 08:05:57 +00001975 CharUnits Align = AI.getIndirectAlign();
James Y Knight71608572015-08-21 18:19:06 +00001976
1977 // In a byval argument, it is important that the required
1978 // alignment of the type is honored, as LLVM might be creating a
1979 // *new* stack object, and needs to know what alignment to give
1980 // it. (Sometimes it can deduce a sensible alignment on its own,
1981 // but not if clang decides it must emit a packed struct, or the
1982 // user specifies increased alignment requirements.)
1983 //
1984 // This is different from indirect *not* byval, where the object
1985 // exists already, and the align attribute is purely
1986 // informative.
John McCall7f416cc2015-09-08 08:05:57 +00001987 assert(!Align.isZero());
James Y Knight71608572015-08-21 18:19:06 +00001988
John McCall7f416cc2015-09-08 08:05:57 +00001989 // For now, only add this when we have a byval argument.
1990 // TODO: be less lazy about updating test cases.
1991 if (AI.getIndirectByVal())
1992 Attrs.addAlignmentAttr(Align.getQuantity());
Bill Wendlinga7912f82012-10-10 07:36:56 +00001993
Daniel Dunbarc2304432009-03-18 19:51:01 +00001994 // byval disables readnone and readonly.
Bill Wendling207f0532012-12-20 19:27:06 +00001995 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1996 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbard3674e62008-09-11 01:48:57 +00001997 break;
James Y Knight71608572015-08-21 18:19:06 +00001998 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00001999 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002000 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00002001 case ABIArgInfo::CoerceAndExpand:
2002 break;
Daniel Dunbar94a6f252009-01-26 21:26:08 +00002003
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002004 case ABIArgInfo::InAlloca:
2005 // inalloca disables readnone and readonly.
2006 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2007 .removeAttribute(llvm::Attribute::ReadNone);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002008 continue;
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Hal Finkela2347ba2014-07-18 15:52:10 +00002011 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2012 QualType PTy = RefTy->getPointeeType();
David Majnemer9df56372015-09-10 21:52:00 +00002013 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
Hal Finkela2347ba2014-07-18 15:52:10 +00002014 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
2015 .getQuantity());
2016 else if (getContext().getTargetAddressSpace(PTy) == 0)
2017 Attrs.addAttribute(llvm::Attribute::NonNull);
2018 }
Nick Lewycky9b46eb82014-05-28 09:56:42 +00002019
John McCall12f23522016-04-04 18:33:08 +00002020 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2021 case ParameterABI::Ordinary:
2022 break;
2023
2024 case ParameterABI::SwiftIndirectResult: {
2025 // Add 'sret' if we haven't already used it for something, but
2026 // only if the result is void.
2027 if (!hasUsedSRet && RetTy->isVoidType()) {
2028 Attrs.addAttribute(llvm::Attribute::StructRet);
2029 hasUsedSRet = true;
2030 }
2031
2032 // Add 'noalias' in either case.
2033 Attrs.addAttribute(llvm::Attribute::NoAlias);
2034
2035 // Add 'dereferenceable' and 'alignment'.
2036 auto PTy = ParamType->getPointeeType();
2037 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2038 auto info = getContext().getTypeInfoInChars(PTy);
2039 Attrs.addDereferenceableAttr(info.first.getQuantity());
2040 Attrs.addAttribute(llvm::Attribute::getWithAlignment(getLLVMContext(),
2041 info.second.getQuantity()));
2042 }
2043 break;
2044 }
2045
2046 case ParameterABI::SwiftErrorResult:
2047 Attrs.addAttribute(llvm::Attribute::SwiftError);
2048 break;
2049
2050 case ParameterABI::SwiftContext:
2051 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2052 break;
2053 }
2054
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002055 if (Attrs.hasAttributes()) {
2056 unsigned FirstIRArg, NumIRArgs;
2057 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2058 for (unsigned i = 0; i < NumIRArgs; i++)
2059 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
2060 FirstIRArg + i + 1, Attrs));
2061 }
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002062 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002063 assert(ArgNo == FI.arg_size());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002064
Bill Wendlinga7912f82012-10-10 07:36:56 +00002065 if (FuncAttrs.hasAttributes())
Bill Wendling4f0c0802012-10-15 07:31:59 +00002066 PAL.push_back(llvm::
Bill Wendling290d9522013-01-27 02:46:53 +00002067 AttributeSet::get(getLLVMContext(),
2068 llvm::AttributeSet::FunctionIndex,
2069 FuncAttrs));
Daniel Dunbar76c8eb72008-09-10 00:32:18 +00002070}
2071
John McCalla738c252011-03-09 04:27:21 +00002072/// An argument came in as a promoted argument; demote it back to its
2073/// declared type.
2074static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2075 const VarDecl *var,
2076 llvm::Value *value) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002077 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalla738c252011-03-09 04:27:21 +00002078
2079 // This can happen with promotions that actually don't change the
2080 // underlying type, like the enum promotions.
2081 if (value->getType() == varType) return value;
2082
2083 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2084 && "unexpected promotion type");
2085
2086 if (isa<llvm::IntegerType>(varType))
2087 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2088
2089 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2090}
2091
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002092/// Returns the attribute (either parameter attribute, or function
2093/// attribute), which declares argument ArgNo to be non-null.
2094static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2095 QualType ArgType, unsigned ArgNo) {
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002096 // FIXME: __attribute__((nonnull)) can also be applied to:
2097 // - references to pointers, where the pointee is known to be
2098 // nonnull (apparently a Clang extension)
2099 // - transparent unions containing pointers
2100 // In the former case, LLVM IR cannot represent the constraint. In
2101 // the latter case, we have no guarantee that the transparent union
2102 // is in fact passed as a pointer.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002103 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2104 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002105 // First, check attribute on parameter itself.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002106 if (PVD) {
2107 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2108 return ParmNNAttr;
2109 }
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002110 // Check function attributes.
2111 if (!FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002112 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002113 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002114 if (NNAttr->isNonNull(ArgNo))
2115 return NNAttr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002116 }
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002117 return nullptr;
Alexey Samsonov9fc9bf82014-08-28 00:53:20 +00002118}
2119
John McCall12f23522016-04-04 18:33:08 +00002120namespace {
2121 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2122 Address Temp;
2123 Address Arg;
2124 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
2125 void Emit(CodeGenFunction &CGF, Flags flags) override {
2126 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2127 CGF.Builder.CreateStore(errorValue, Arg);
2128 }
2129 };
2130}
2131
Daniel Dunbard931a872009-02-02 22:03:45 +00002132void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2133 llvm::Function *Fn,
Daniel Dunbar613855c2008-09-09 23:27:19 +00002134 const FunctionArgList &Args) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002135 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2136 // Naked functions don't have prologues.
2137 return;
2138
John McCallcaa19452009-07-28 01:00:58 +00002139 // If this is an implicit-return-zero function, go ahead and
2140 // initialize the return value. TODO: it might be nice to have
2141 // a more general mechanism for this that didn't require synthesized
2142 // return statements.
John McCalldec348f72013-05-03 07:33:41 +00002143 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCallcaa19452009-07-28 01:00:58 +00002144 if (FD->hasImplicitReturnZero()) {
Alp Toker314cc812014-01-25 16:55:45 +00002145 QualType RetTy = FD->getReturnType().getUnqualifiedType();
Chris Lattner2192fe52011-07-18 04:24:23 +00002146 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Anderson0b75f232009-07-31 20:28:54 +00002147 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCallcaa19452009-07-28 01:00:58 +00002148 Builder.CreateStore(Zero, ReturnValue);
2149 }
2150 }
2151
Mike Stump18bb9282009-05-16 07:57:57 +00002152 // FIXME: We no longer need the types from FunctionArgList; lift up and
2153 // simplify.
Daniel Dunbar5a0acdc92009-02-03 06:02:10 +00002154
Alexey Samsonov153004f2014-09-29 22:08:00 +00002155 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002156 // Flattened function arguments.
John McCall12f23522016-04-04 18:33:08 +00002157 SmallVector<llvm::Value *, 16> FnArgs;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002158 FnArgs.reserve(IRFunctionArgs.totalIRArgs());
2159 for (auto &Arg : Fn->args()) {
2160 FnArgs.push_back(&Arg);
2161 }
2162 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
Mike Stump11289f42009-09-09 15:08:12 +00002163
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002164 // If we're using inalloca, all the memory arguments are GEPs off of the last
2165 // parameter, which is a pointer to the complete memory area.
John McCall7f416cc2015-09-08 08:05:57 +00002166 Address ArgStruct = Address::invalid();
2167 const llvm::StructLayout *ArgStructLayout = nullptr;
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002168 if (IRFunctionArgs.hasInallocaArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00002169 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
2170 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
2171 FI.getArgStructAlignment());
2172
2173 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002174 }
2175
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002176 // Name the struct return parameter.
2177 if (IRFunctionArgs.hasSRetArg()) {
John McCall12f23522016-04-04 18:33:08 +00002178 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]);
Daniel Dunbar613855c2008-09-09 23:27:19 +00002179 AI->setName("agg.result");
Reid Kleckner37abaca2014-05-09 22:46:15 +00002180 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002181 llvm::Attribute::NoAlias));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002184 // Track if we received the parameter as a pointer (indirect, byval, or
2185 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2186 // into a local alloca for us.
John McCall7f416cc2015-09-08 08:05:57 +00002187 SmallVector<ParamValue, 16> ArgVals;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002188 ArgVals.reserve(Args.size());
2189
Reid Kleckner739756c2013-12-04 19:23:12 +00002190 // Create a pointer value for every parameter declaration. This usually
2191 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2192 // any cleanups or do anything that might unwind. We do that separately, so
2193 // we can push the cleanups in the correct order for the ABI.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00002194 assert(FI.arg_size() == Args.size() &&
2195 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002196 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002197 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002198 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Devang Patel68a15252011-03-03 20:13:15 +00002199 i != e; ++i, ++info_it, ++ArgNo) {
John McCalla738c252011-03-09 04:27:21 +00002200 const VarDecl *Arg = *i;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00002201 QualType Ty = info_it->type;
2202 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002203
John McCalla738c252011-03-09 04:27:21 +00002204 bool isPromoted =
2205 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2206
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002207 unsigned FirstIRArg, NumIRArgs;
2208 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00002209
Daniel Dunbard3674e62008-09-11 01:48:57 +00002210 switch (ArgI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002211 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002212 assert(NumIRArgs == 0);
John McCall7f416cc2015-09-08 08:05:57 +00002213 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2214 CharUnits FieldOffset =
2215 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
2216 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
2217 Arg->getName());
2218 ArgVals.push_back(ParamValue::forIndirect(V));
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002219 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002220 }
2221
Daniel Dunbar747865a2009-02-05 09:16:39 +00002222 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002223 assert(NumIRArgs == 1);
John McCall7f416cc2015-09-08 08:05:57 +00002224 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002225
John McCall47fb9502013-03-07 21:37:08 +00002226 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002227 // Aggregates and complex variables are accessed by reference. All we
John McCall7f416cc2015-09-08 08:05:57 +00002228 // need to do is realign the value, if requested.
2229 Address V = ParamAddr;
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002230 if (ArgI.getIndirectRealign()) {
John McCall7f416cc2015-09-08 08:05:57 +00002231 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002232
2233 // Copy from the incoming argument pointer to the temporary with the
2234 // appropriate alignment.
2235 //
2236 // FIXME: We should have a common utility for generating an aggregate
2237 // copy.
Ken Dyck705ba072011-01-19 01:58:38 +00002238 CharUnits Size = getContext().getTypeSizeInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002239 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
2240 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
2241 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
2242 Builder.CreateMemCpy(Dst, Src, SizeVal, false);
Daniel Dunbar7b7c2932010-09-16 20:42:02 +00002243 V = AlignedTemp;
2244 }
John McCall7f416cc2015-09-08 08:05:57 +00002245 ArgVals.push_back(ParamValue::forIndirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002246 } else {
2247 // Load scalar value from indirect argument.
John McCall7f416cc2015-09-08 08:05:57 +00002248 llvm::Value *V =
2249 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002250
2251 if (isPromoted)
2252 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002253 ArgVals.push_back(ParamValue::forDirect(V));
Daniel Dunbar747865a2009-02-05 09:16:39 +00002254 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00002255 break;
2256 }
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002257
2258 case ABIArgInfo::Extend:
Daniel Dunbar67dace892009-02-03 06:17:37 +00002259 case ABIArgInfo::Direct: {
Akira Hatanaka18334dd2012-01-09 19:08:06 +00002260
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002261 // If we have the trivial case, handle it with no muss and fuss.
2262 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002263 ArgI.getCoerceToType() == ConvertType(Ty) &&
2264 ArgI.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002265 assert(NumIRArgs == 1);
John McCall12f23522016-04-04 18:33:08 +00002266 llvm::Value *V = FnArgs[FirstIRArg];
2267 auto AI = cast<llvm::Argument>(V);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002268
Hal Finkel48d53e22014-07-19 01:41:07 +00002269 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00002270 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2271 PVD->getFunctionScopeIndex()))
Hal Finkel82504f02014-07-11 17:35:21 +00002272 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2273 AI->getArgNo() + 1,
2274 llvm::Attribute::NonNull));
2275
Hal Finkel48d53e22014-07-19 01:41:07 +00002276 QualType OTy = PVD->getOriginalType();
2277 if (const auto *ArrTy =
2278 getContext().getAsConstantArrayType(OTy)) {
2279 // A C99 array parameter declaration with the static keyword also
2280 // indicates dereferenceability, and if the size is constant we can
2281 // use the dereferenceable attribute (which requires the size in
2282 // bytes).
Hal Finkel16e394a2014-07-19 02:13:40 +00002283 if (ArrTy->getSizeModifier() == ArrayType::Static) {
Hal Finkel48d53e22014-07-19 01:41:07 +00002284 QualType ETy = ArrTy->getElementType();
2285 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2286 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2287 ArrSize) {
2288 llvm::AttrBuilder Attrs;
2289 Attrs.addDereferenceableAttr(
2290 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
2291 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2292 AI->getArgNo() + 1, Attrs));
2293 } else if (getContext().getTargetAddressSpace(ETy) == 0) {
2294 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2295 AI->getArgNo() + 1,
2296 llvm::Attribute::NonNull));
2297 }
2298 }
2299 } else if (const auto *ArrTy =
2300 getContext().getAsVariableArrayType(OTy)) {
2301 // For C99 VLAs with the static keyword, we don't know the size so
2302 // we can't use the dereferenceable attribute, but in addrspace(0)
2303 // we know that it must be nonnull.
2304 if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
2305 !getContext().getTargetAddressSpace(ArrTy->getElementType()))
2306 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2307 AI->getArgNo() + 1,
2308 llvm::Attribute::NonNull));
2309 }
Hal Finkel1b0d24e2014-10-02 21:21:25 +00002310
2311 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2312 if (!AVAttr)
2313 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2314 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2315 if (AVAttr) {
2316 llvm::Value *AlignmentValue =
2317 EmitScalarExpr(AVAttr->getAlignment());
2318 llvm::ConstantInt *AlignmentCI =
2319 cast<llvm::ConstantInt>(AlignmentValue);
2320 unsigned Alignment =
2321 std::min((unsigned) AlignmentCI->getZExtValue(),
2322 +llvm::Value::MaximumAlignment);
2323
2324 llvm::AttrBuilder Attrs;
2325 Attrs.addAlignmentAttr(Alignment);
2326 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2327 AI->getArgNo() + 1, Attrs));
2328 }
Hal Finkel48d53e22014-07-19 01:41:07 +00002329 }
2330
Bill Wendling507c3512012-10-16 05:23:44 +00002331 if (Arg->getType().isRestrictQualified())
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002332 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
2333 AI->getArgNo() + 1,
2334 llvm::Attribute::NoAlias));
John McCall39ec71f2010-03-27 00:47:27 +00002335
John McCall12f23522016-04-04 18:33:08 +00002336 // LLVM expects swifterror parameters to be used in very restricted
2337 // ways. Copy the value into a less-restricted temporary.
2338 if (FI.getExtParameterInfo(ArgNo).getABI()
2339 == ParameterABI::SwiftErrorResult) {
2340 QualType pointeeTy = Ty->getPointeeType();
2341 assert(pointeeTy->isPointerType());
2342 Address temp =
2343 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2344 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2345 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2346 Builder.CreateStore(incomingErrorValue, temp);
2347 V = temp.getPointer();
2348
2349 // Push a cleanup to copy the value back at the end of the function.
2350 // The convention does not guarantee that the value will be written
2351 // back if the function exits with an unwind exception.
2352 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2353 }
2354
Chris Lattner7369c142011-07-20 06:29:00 +00002355 // Ensure the argument is the correct type.
2356 if (V->getType() != ArgI.getCoerceToType())
2357 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2358
John McCalla738c252011-03-09 04:27:21 +00002359 if (isPromoted)
2360 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8778c282012-11-29 16:09:03 +00002361
2362 // Because of merging of function types from multiple decls it is
2363 // possible for the type of an argument to not match the corresponding
2364 // type in the function type. Since we are codegening the callee
2365 // in here, add a cast to the argument type.
2366 llvm::Type *LTy = ConvertType(Arg->getType());
2367 if (V->getType() != LTy)
2368 V = Builder.CreateBitCast(V, LTy);
2369
John McCall7f416cc2015-09-08 08:05:57 +00002370 ArgVals.push_back(ParamValue::forDirect(V));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002371 break;
Daniel Dunbard5f1f552009-02-10 00:06:49 +00002372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
John McCall7f416cc2015-09-08 08:05:57 +00002374 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2375 Arg->getName());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002376
John McCall7f416cc2015-09-08 08:05:57 +00002377 // Pointer to store into.
2378 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002379
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002380 // Fast-isel and the optimizer generally like scalar values better than
2381 // FCAs, so we flatten them if this is safe to do for this argument.
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002382 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00002383 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2384 STy->getNumElements() > 1) {
John McCall7f416cc2015-09-08 08:05:57 +00002385 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002386 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
John McCall7f416cc2015-09-08 08:05:57 +00002387 llvm::Type *DstTy = Ptr.getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002388 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002389
John McCall7f416cc2015-09-08 08:05:57 +00002390 Address AddrToStoreInto = Address::invalid();
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002391 if (SrcSize <= DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00002392 AddrToStoreInto =
2393 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Evgeniy Stepanov3fae4ae2012-02-10 09:30:15 +00002394 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002395 AddrToStoreInto =
2396 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
Chris Lattner15ec3612010-06-29 00:06:42 +00002397 }
John McCall7f416cc2015-09-08 08:05:57 +00002398
2399 assert(STy->getNumElements() == NumIRArgs);
2400 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2401 auto AI = FnArgs[FirstIRArg + i];
2402 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2403 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
2404 Address EltPtr =
2405 Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
2406 Builder.CreateStore(AI, EltPtr);
2407 }
2408
2409 if (SrcSize > DstSize) {
2410 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2411 }
2412
Chris Lattner15ec3612010-06-29 00:06:42 +00002413 } else {
2414 // Simple case, just do a coerced store of the argument into the alloca.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002415 assert(NumIRArgs == 1);
2416 auto AI = FnArgs[FirstIRArg];
Chris Lattner9e748e92010-06-29 00:14:52 +00002417 AI->setName(Arg->getName() + ".coerce");
John McCall7f416cc2015-09-08 08:05:57 +00002418 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner15ec3612010-06-29 00:06:42 +00002419 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002420
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002421 // Match to what EmitParmDecl is expecting for this type.
John McCall47fb9502013-03-07 21:37:08 +00002422 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002423 llvm::Value *V =
2424 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
John McCalla738c252011-03-09 04:27:21 +00002425 if (isPromoted)
2426 V = emitArgumentDemotion(*this, Arg, V);
John McCall7f416cc2015-09-08 08:05:57 +00002427 ArgVals.push_back(ParamValue::forDirect(V));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002428 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002429 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Daniel Dunbar6e3b7df2009-02-04 07:22:24 +00002430 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002431 break;
Daniel Dunbar2f219b02009-02-03 19:12:28 +00002432 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002433
John McCallf26e73d2016-03-11 04:30:43 +00002434 case ABIArgInfo::CoerceAndExpand: {
2435 // Reconstruct into a temporary.
2436 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2437 ArgVals.push_back(ParamValue::forIndirect(alloca));
2438
2439 auto coercionType = ArgI.getCoerceAndExpandType();
2440 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2441 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2442
2443 unsigned argIndex = FirstIRArg;
2444 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2445 llvm::Type *eltType = coercionType->getElementType(i);
2446 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2447 continue;
2448
2449 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout);
2450 auto elt = FnArgs[argIndex++];
2451 Builder.CreateStore(elt, eltAddr);
2452 }
2453 assert(argIndex == FirstIRArg + NumIRArgs);
2454 break;
2455 }
2456
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002457 case ABIArgInfo::Expand: {
2458 // If this structure was expanded into multiple arguments then
2459 // we need to create a temporary and reconstruct it from the
2460 // arguments.
John McCall7f416cc2015-09-08 08:05:57 +00002461 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2462 LValue LV = MakeAddrLValue(Alloca, Ty);
2463 ArgVals.push_back(ParamValue::forIndirect(Alloca));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002464
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002465 auto FnArgIter = FnArgs.begin() + FirstIRArg;
2466 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2467 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
2468 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2469 auto AI = FnArgs[FirstIRArg + i];
2470 AI->setName(Arg->getName() + "." + Twine(i));
2471 }
2472 break;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002473 }
2474
2475 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002476 assert(NumIRArgs == 0);
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002477 // Initialize the local variable appropriately.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002478 if (!hasScalarEvaluationKind(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00002479 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002480 } else {
2481 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002482 ArgVals.push_back(ParamValue::forDirect(U));
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002483 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00002484 break;
Daniel Dunbard3674e62008-09-11 01:48:57 +00002485 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002486 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002487
Reid Kleckner739756c2013-12-04 19:23:12 +00002488 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2489 for (int I = Args.size() - 1; I >= 0; --I)
John McCall7f416cc2015-09-08 08:05:57 +00002490 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002491 } else {
2492 for (unsigned I = 0, E = Args.size(); I != E; ++I)
John McCall7f416cc2015-09-08 08:05:57 +00002493 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00002494 }
Daniel Dunbar613855c2008-09-09 23:27:19 +00002495}
2496
John McCallffa2c1a2012-01-29 07:46:59 +00002497static void eraseUnusedBitCasts(llvm::Instruction *insn) {
2498 while (insn->use_empty()) {
2499 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
2500 if (!bitcast) return;
2501
2502 // This is "safe" because we would have used a ConstantExpr otherwise.
2503 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
2504 bitcast->eraseFromParent();
2505 }
2506}
2507
John McCall31168b02011-06-15 23:02:42 +00002508/// Try to emit a fused autorelease of a return result.
2509static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
2510 llvm::Value *result) {
2511 // We must be immediately followed the cast.
2512 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002513 if (BB->empty()) return nullptr;
2514 if (&BB->back() != result) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002515
Chris Lattner2192fe52011-07-18 04:24:23 +00002516 llvm::Type *resultType = result->getType();
John McCall31168b02011-06-15 23:02:42 +00002517
2518 // result is in a BasicBlock and is therefore an Instruction.
2519 llvm::Instruction *generator = cast<llvm::Instruction>(result);
2520
Justin Bogner882f8612016-08-18 21:46:54 +00002521 SmallVector<llvm::Instruction *, 4> InstsToKill;
John McCall31168b02011-06-15 23:02:42 +00002522
2523 // Look for:
2524 // %generator = bitcast %type1* %generator2 to %type2*
2525 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
2526 // We would have emitted this as a constant if the operand weren't
2527 // an Instruction.
2528 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
2529
2530 // Require the generator to be immediately followed by the cast.
2531 if (generator->getNextNode() != bitcast)
Craig Topper8a13c412014-05-21 05:09:00 +00002532 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002533
Justin Bogner882f8612016-08-18 21:46:54 +00002534 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002535 }
2536
2537 // Look for:
2538 // %generator = call i8* @objc_retain(i8* %originalResult)
2539 // or
2540 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
2541 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
Craig Topper8a13c412014-05-21 05:09:00 +00002542 if (!call) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002543
2544 bool doRetainAutorelease;
2545
John McCallb04ecb72015-10-21 18:06:43 +00002546 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) {
John McCall31168b02011-06-15 23:02:42 +00002547 doRetainAutorelease = true;
John McCallb04ecb72015-10-21 18:06:43 +00002548 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints()
John McCall31168b02011-06-15 23:02:42 +00002549 .objc_retainAutoreleasedReturnValue) {
2550 doRetainAutorelease = false;
2551
John McCallcfa4e9b2012-09-07 23:30:50 +00002552 // If we emitted an assembly marker for this call (and the
2553 // ARCEntrypoints field should have been set if so), go looking
2554 // for that call. If we can't find it, we can't do this
2555 // optimization. But it should always be the immediately previous
2556 // instruction, unless we needed bitcasts around the call.
John McCallb04ecb72015-10-21 18:06:43 +00002557 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
John McCallcfa4e9b2012-09-07 23:30:50 +00002558 llvm::Instruction *prev = call->getPrevNode();
2559 assert(prev);
2560 if (isa<llvm::BitCastInst>(prev)) {
2561 prev = prev->getPrevNode();
2562 assert(prev);
2563 }
2564 assert(isa<llvm::CallInst>(prev));
2565 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
John McCallb04ecb72015-10-21 18:06:43 +00002566 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
Justin Bogner882f8612016-08-18 21:46:54 +00002567 InstsToKill.push_back(prev);
John McCallcfa4e9b2012-09-07 23:30:50 +00002568 }
John McCall31168b02011-06-15 23:02:42 +00002569 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002570 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002571 }
2572
2573 result = call->getArgOperand(0);
Justin Bogner882f8612016-08-18 21:46:54 +00002574 InstsToKill.push_back(call);
John McCall31168b02011-06-15 23:02:42 +00002575
2576 // Keep killing bitcasts, for sanity. Note that we no longer care
2577 // about precise ordering as long as there's exactly one use.
2578 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
2579 if (!bitcast->hasOneUse()) break;
Justin Bogner882f8612016-08-18 21:46:54 +00002580 InstsToKill.push_back(bitcast);
John McCall31168b02011-06-15 23:02:42 +00002581 result = bitcast->getOperand(0);
2582 }
2583
2584 // Delete all the unnecessary instructions, from latest to earliest.
Justin Bogner882f8612016-08-18 21:46:54 +00002585 for (auto *I : InstsToKill)
Saleem Abdulrasoolbe25c482016-08-18 21:40:06 +00002586 I->eraseFromParent();
John McCall31168b02011-06-15 23:02:42 +00002587
2588 // Do the fused retain/autorelease if we were asked to.
2589 if (doRetainAutorelease)
2590 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
2591
2592 // Cast back to the result type.
2593 return CGF.Builder.CreateBitCast(result, resultType);
2594}
2595
John McCallffa2c1a2012-01-29 07:46:59 +00002596/// If this is a +1 of the value of an immutable 'self', remove it.
2597static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
2598 llvm::Value *result) {
2599 // This is only applicable to a method with an immutable 'self'.
John McCallff755cd2012-07-31 00:33:55 +00002600 const ObjCMethodDecl *method =
2601 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002602 if (!method) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002603 const VarDecl *self = method->getSelfDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00002604 if (!self->getType().isConstQualified()) return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002605
2606 // Look for a retain call.
2607 llvm::CallInst *retainCall =
2608 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
2609 if (!retainCall ||
John McCallb04ecb72015-10-21 18:06:43 +00002610 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain)
Craig Topper8a13c412014-05-21 05:09:00 +00002611 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002612
2613 // Look for an ordinary load of 'self'.
2614 llvm::Value *retainedValue = retainCall->getArgOperand(0);
2615 llvm::LoadInst *load =
2616 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
2617 if (!load || load->isAtomic() || load->isVolatile() ||
John McCall7f416cc2015-09-08 08:05:57 +00002618 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
Craig Topper8a13c412014-05-21 05:09:00 +00002619 return nullptr;
John McCallffa2c1a2012-01-29 07:46:59 +00002620
2621 // Okay! Burn it all down. This relies for correctness on the
2622 // assumption that the retain is emitted as part of the return and
2623 // that thereafter everything is used "linearly".
2624 llvm::Type *resultType = result->getType();
2625 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
2626 assert(retainCall->use_empty());
2627 retainCall->eraseFromParent();
2628 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
2629
2630 return CGF.Builder.CreateBitCast(load, resultType);
2631}
2632
John McCall31168b02011-06-15 23:02:42 +00002633/// Emit an ARC autorelease of the result of a function.
John McCallffa2c1a2012-01-29 07:46:59 +00002634///
2635/// \return the value to actually return from the function
John McCall31168b02011-06-15 23:02:42 +00002636static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
2637 llvm::Value *result) {
John McCallffa2c1a2012-01-29 07:46:59 +00002638 // If we're returning 'self', kill the initial retain. This is a
2639 // heuristic attempt to "encourage correctness" in the really unfortunate
2640 // case where we have a return of self during a dealloc and we desperately
2641 // need to avoid the possible autorelease.
2642 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
2643 return self;
2644
John McCall31168b02011-06-15 23:02:42 +00002645 // At -O0, try to emit a fused retain/autorelease.
2646 if (CGF.shouldUseFusedARCCalls())
2647 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
2648 return fused;
2649
2650 return CGF.EmitARCAutoreleaseReturnValue(result);
2651}
2652
John McCall6e1c0122012-01-29 02:35:02 +00002653/// Heuristically search for a dominating store to the return-value slot.
2654static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002655 // Check if a User is a store which pointerOperand is the ReturnValue.
2656 // We are looking for stores to the ReturnValue, not for stores of the
2657 // ReturnValue to some other location.
2658 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
2659 auto *SI = dyn_cast<llvm::StoreInst>(U);
2660 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
2661 return nullptr;
2662 // These aren't actually possible for non-coerced returns, and we
2663 // only care about non-coerced returns on this code path.
2664 assert(!SI->isAtomic() && !SI->isVolatile());
2665 return SI;
2666 };
John McCall6e1c0122012-01-29 02:35:02 +00002667 // If there are multiple uses of the return-value slot, just check
2668 // for something immediately preceding the IP. Sometimes this can
2669 // happen with how we generate implicit-returns; it can also happen
2670 // with noreturn cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00002671 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
John McCall6e1c0122012-01-29 02:35:02 +00002672 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +00002673 if (IP->empty()) return nullptr;
David Majnemerdc012fa2015-04-22 21:38:15 +00002674 llvm::Instruction *I = &IP->back();
2675
2676 // Skip lifetime markers
2677 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
2678 IE = IP->rend();
2679 II != IE; ++II) {
2680 if (llvm::IntrinsicInst *Intrinsic =
2681 dyn_cast<llvm::IntrinsicInst>(&*II)) {
2682 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
2683 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
2684 ++II;
Alexey Samsonov10544202015-06-12 21:05:32 +00002685 if (II == IE)
2686 break;
2687 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
2688 continue;
David Majnemerdc012fa2015-04-22 21:38:15 +00002689 }
2690 }
2691 I = &*II;
2692 break;
2693 }
2694
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002695 return GetStoreIfValid(I);
John McCall6e1c0122012-01-29 02:35:02 +00002696 }
2697
2698 llvm::StoreInst *store =
Jakub Kuderskif50ab0f2015-09-08 10:36:42 +00002699 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
Craig Topper8a13c412014-05-21 05:09:00 +00002700 if (!store) return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002701
John McCall6e1c0122012-01-29 02:35:02 +00002702 // Now do a first-and-dirty dominance check: just walk up the
2703 // single-predecessors chain from the current insertion point.
2704 llvm::BasicBlock *StoreBB = store->getParent();
2705 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
2706 while (IP != StoreBB) {
2707 if (!(IP = IP->getSinglePredecessor()))
Craig Topper8a13c412014-05-21 05:09:00 +00002708 return nullptr;
John McCall6e1c0122012-01-29 02:35:02 +00002709 }
2710
2711 // Okay, the store's basic block dominates the insertion point; we
2712 // can do our thing.
2713 return store;
2714}
2715
Adrian Prantl3be10542013-05-02 17:30:20 +00002716void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002717 bool EmitRetDbgLoc,
2718 SourceLocation EndLoc) {
Hans Wennborgd71907d2014-09-04 22:16:33 +00002719 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
2720 // Naked functions don't have epilogues.
2721 Builder.CreateUnreachable();
2722 return;
2723 }
2724
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002725 // Functions with no result always return void.
John McCall7f416cc2015-09-08 08:05:57 +00002726 if (!ReturnValue.isValid()) {
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002727 Builder.CreateRetVoid();
Chris Lattner726b3d02010-06-26 23:13:19 +00002728 return;
Daniel Dunbara72d4ae2008-09-10 02:41:04 +00002729 }
Daniel Dunbar6696e222010-06-30 21:27:58 +00002730
Dan Gohman481e40c2010-07-20 20:13:52 +00002731 llvm::DebugLoc RetDbgLoc;
Craig Topper8a13c412014-05-21 05:09:00 +00002732 llvm::Value *RV = nullptr;
Chris Lattner726b3d02010-06-26 23:13:19 +00002733 QualType RetTy = FI.getReturnType();
2734 const ABIArgInfo &RetAI = FI.getReturnInfo();
2735
2736 switch (RetAI.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002737 case ABIArgInfo::InAlloca:
Reid Klecknerfab1e892014-02-25 00:59:14 +00002738 // Aggregrates get evaluated directly into the destination. Sometimes we
2739 // need to return the sret value in a register, though.
2740 assert(hasAggregateEvaluationKind(RetTy));
2741 if (RetAI.getInAllocaSRet()) {
2742 llvm::Function::arg_iterator EI = CurFn->arg_end();
2743 --EI;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002744 llvm::Value *ArgStruct = &*EI;
David Blaikie2e804282015-04-05 22:47:07 +00002745 llvm::Value *SRet = Builder.CreateStructGEP(
2746 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
John McCall7f416cc2015-09-08 08:05:57 +00002747 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
Reid Klecknerfab1e892014-02-25 00:59:14 +00002748 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002749 break;
2750
Daniel Dunbar03816342010-08-21 02:24:36 +00002751 case ABIArgInfo::Indirect: {
Reid Kleckner37abaca2014-05-09 22:46:15 +00002752 auto AI = CurFn->arg_begin();
2753 if (RetAI.isSRetAfterThis())
2754 ++AI;
John McCall47fb9502013-03-07 21:37:08 +00002755 switch (getEvaluationKind(RetTy)) {
2756 case TEK_Complex: {
2757 ComplexPairTy RT =
John McCall7f416cc2015-09-08 08:05:57 +00002758 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002759 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002760 /*isInit*/ true);
2761 break;
2762 }
2763 case TEK_Aggregate:
Chris Lattner726b3d02010-06-26 23:13:19 +00002764 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall47fb9502013-03-07 21:37:08 +00002765 break;
2766 case TEK_Scalar:
2767 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00002768 MakeNaturalAlignAddrLValue(&*AI, RetTy),
John McCall47fb9502013-03-07 21:37:08 +00002769 /*isInit*/ true);
2770 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002771 }
2772 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00002773 }
Chris Lattner726b3d02010-06-26 23:13:19 +00002774
2775 case ABIArgInfo::Extend:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002776 case ABIArgInfo::Direct:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002777 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
2778 RetAI.getDirectOffset() == 0) {
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002779 // The internal return value temp always will have pointer-to-return-type
2780 // type, just do a load.
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002781
John McCall6e1c0122012-01-29 02:35:02 +00002782 // If there is a dominating store to ReturnValue, we can elide
2783 // the load, zap the store, and usually zap the alloca.
David Majnemerdc012fa2015-04-22 21:38:15 +00002784 if (llvm::StoreInst *SI =
2785 findDominatingStoreToReturnValue(*this)) {
Adrian Prantl4c9a38a2013-05-30 18:12:23 +00002786 // Reuse the debug location from the store unless there is
2787 // cleanup code to be emitted between the store and return
2788 // instruction.
2789 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantl3be10542013-05-02 17:30:20 +00002790 RetDbgLoc = SI->getDebugLoc();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002791 // Get the stored value and nuke the now-dead store.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002792 RV = SI->getValueOperand();
2793 SI->eraseFromParent();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002794
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002795 // If that was the only use of the return value, nuke it as well now.
John McCall7f416cc2015-09-08 08:05:57 +00002796 auto returnValueInst = ReturnValue.getPointer();
2797 if (returnValueInst->use_empty()) {
2798 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
2799 alloca->eraseFromParent();
2800 ReturnValue = Address::invalid();
2801 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002802 }
John McCall6e1c0122012-01-29 02:35:02 +00002803
2804 // Otherwise, we have to do a simple load.
2805 } else {
2806 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002807 }
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002808 } else {
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002809 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00002810 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002811
John McCall7f416cc2015-09-08 08:05:57 +00002812 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner3fcc7902010-06-27 01:06:27 +00002813 }
John McCall31168b02011-06-15 23:02:42 +00002814
2815 // In ARC, end functions that return a retainable type with a call
2816 // to objc_autoreleaseReturnValue.
2817 if (AutoreleaseResult) {
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002818#ifndef NDEBUG
2819 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
2820 // been stripped of the typedefs, so we cannot use RetTy here. Get the
2821 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
2822 // CurCodeDecl or BlockInfo.
2823 QualType RT;
2824
2825 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
2826 RT = FD->getReturnType();
2827 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
2828 RT = MD->getReturnType();
2829 else if (isa<BlockDecl>(CurCodeDecl))
2830 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
2831 else
2832 llvm_unreachable("Unexpected function/method type");
2833
David Blaikiebbafb8a2012-03-11 07:00:24 +00002834 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002835 !FI.isReturnsRetained() &&
Akira Hatanaka9d8ac612016-02-17 21:09:50 +00002836 RT->isObjCRetainableType());
2837#endif
John McCall31168b02011-06-15 23:02:42 +00002838 RV = emitAutoreleaseOfResult(*this, RV);
2839 }
2840
Chris Lattner726b3d02010-06-26 23:13:19 +00002841 break;
Chris Lattner726b3d02010-06-26 23:13:19 +00002842
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002843 case ABIArgInfo::Ignore:
Chris Lattner726b3d02010-06-26 23:13:19 +00002844 break;
2845
John McCallf26e73d2016-03-11 04:30:43 +00002846 case ABIArgInfo::CoerceAndExpand: {
2847 auto coercionType = RetAI.getCoerceAndExpandType();
2848 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
2849
2850 // Load all of the coerced elements out into results.
2851 llvm::SmallVector<llvm::Value*, 4> results;
2852 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
2853 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2854 auto coercedEltType = coercionType->getElementType(i);
2855 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
2856 continue;
2857
2858 auto eltAddr = Builder.CreateStructGEP(addr, i, layout);
2859 auto elt = Builder.CreateLoad(eltAddr);
2860 results.push_back(elt);
2861 }
2862
2863 // If we have one result, it's the single direct result type.
2864 if (results.size() == 1) {
2865 RV = results[0];
2866
2867 // Otherwise, we need to make a first-class aggregate.
2868 } else {
2869 // Construct a return type that lacks padding elements.
2870 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
2871
2872 RV = llvm::UndefValue::get(returnType);
2873 for (unsigned i = 0, e = results.size(); i != e; ++i) {
2874 RV = Builder.CreateInsertValue(RV, results[i], i);
2875 }
2876 }
2877 break;
2878 }
2879
Chris Lattner726b3d02010-06-26 23:13:19 +00002880 case ABIArgInfo::Expand:
David Blaikie83d382b2011-09-23 05:06:16 +00002881 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattner726b3d02010-06-26 23:13:19 +00002882 }
2883
Alexey Samsonovde443c52014-08-13 00:26:40 +00002884 llvm::Instruction *Ret;
2885 if (RV) {
John McCall9a2c1c92015-09-10 00:57:46 +00002886 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
2887 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
Alexey Samsonov90452df2014-09-08 20:17:19 +00002888 SanitizerScope SanScope(this);
2889 llvm::Value *Cond = Builder.CreateICmpNE(
2890 RV, llvm::Constant::getNullValue(RV->getType()));
2891 llvm::Constant *StaticData[] = {
2892 EmitCheckSourceLocation(EndLoc),
2893 EmitCheckSourceLocation(RetNNAttr->getLocation()),
2894 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002895 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002896 SanitizerHandler::NonnullReturn, StaticData, None);
Alexey Samsonov90452df2014-09-08 20:17:19 +00002897 }
Alexey Samsonovde443c52014-08-13 00:26:40 +00002898 }
2899 Ret = Builder.CreateRet(RV);
2900 } else {
2901 Ret = Builder.CreateRetVoid();
2902 }
2903
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00002904 if (RetDbgLoc)
Benjamin Kramer03278662015-02-07 13:15:54 +00002905 Ret->setDebugLoc(std::move(RetDbgLoc));
Daniel Dunbar613855c2008-09-09 23:27:19 +00002906}
2907
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002908static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
2909 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2910 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
2911}
2912
John McCall7f416cc2015-09-08 08:05:57 +00002913static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
2914 QualType Ty) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002915 // FIXME: Generate IR in one pass, rather than going back and fixing up these
2916 // placeholders.
2917 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
Peter Collingbourneb367c562016-11-28 22:30:21 +00002918 llvm::Type *IRPtrTy = IRTy->getPointerTo();
2919 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00002920
2921 // FIXME: When we generate this IR in one pass, we shouldn't need
2922 // this win32-specific alignment hack.
2923 CharUnits Align = CharUnits::fromQuantity(4);
Peter Collingbourneb367c562016-11-28 22:30:21 +00002924 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002925
2926 return AggValueSlot::forAddr(Address(Placeholder, Align),
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002927 Ty.getQualifiers(),
2928 AggValueSlot::IsNotDestructed,
2929 AggValueSlot::DoesNotNeedGCBarriers,
2930 AggValueSlot::IsNotAliased);
2931}
2932
John McCall32ea9692011-03-11 20:59:21 +00002933void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
Nick Lewycky2d84e842013-10-02 02:29:49 +00002934 const VarDecl *param,
2935 SourceLocation loc) {
John McCall23f66262010-05-26 22:34:26 +00002936 // StartFunction converted the ABI-lowered parameter(s) into a
2937 // local alloca. We need to turn that into an r-value suitable
2938 // for EmitCall.
John McCall7f416cc2015-09-08 08:05:57 +00002939 Address local = GetAddrOfLocalVar(param);
John McCall23f66262010-05-26 22:34:26 +00002940
John McCall32ea9692011-03-11 20:59:21 +00002941 QualType type = param->getType();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002942
Reid Klecknerab2090d2014-07-26 01:34:32 +00002943 assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
2944 "cannot emit delegate call arguments for inalloca arguments!");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002945
John McCall811b2912016-11-18 01:08:24 +00002946 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
2947 // but the argument needs to be the original pointer.
2948 if (type->isReferenceType()) {
2949 args.add(RValue::get(Builder.CreateLoad(local)), type);
2950
2951 // In ARC, move out of consumed arguments so that the release cleanup
2952 // entered by StartFunction doesn't cause an over-release. This isn't
2953 // optimal -O0 code generation, but it should get cleaned up when
2954 // optimization is enabled. This also assumes that delegate calls are
2955 // performed exactly once for a set of arguments, but that should be safe.
2956 } else if (getLangOpts().ObjCAutoRefCount &&
2957 param->hasAttr<NSConsumedAttr>() &&
2958 type->isObjCRetainableType()) {
2959 llvm::Value *ptr = Builder.CreateLoad(local);
2960 auto null =
2961 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
2962 Builder.CreateStore(null, local);
2963 args.add(RValue::get(ptr), type);
2964
Richard Smithd62d4982016-06-14 01:13:21 +00002965 // For the most part, we just need to load the alloca, except that
2966 // aggregate r-values are actually pointers to temporaries.
John McCall811b2912016-11-18 01:08:24 +00002967 } else {
Richard Smithd62d4982016-06-14 01:13:21 +00002968 args.add(convertTempToRValue(local, type, loc), type);
John McCall811b2912016-11-18 01:08:24 +00002969 }
John McCall23f66262010-05-26 22:34:26 +00002970}
2971
John McCall31168b02011-06-15 23:02:42 +00002972static bool isProvablyNull(llvm::Value *addr) {
2973 return isa<llvm::ConstantPointerNull>(addr);
2974}
2975
John McCall31168b02011-06-15 23:02:42 +00002976/// Emit the actual writing-back of a writeback.
2977static void emitWriteback(CodeGenFunction &CGF,
2978 const CallArgList::Writeback &writeback) {
John McCalleff18842013-03-23 02:35:54 +00002979 const LValue &srcLV = writeback.Source;
John McCall7f416cc2015-09-08 08:05:57 +00002980 Address srcAddr = srcLV.getAddress();
2981 assert(!isProvablyNull(srcAddr.getPointer()) &&
John McCall31168b02011-06-15 23:02:42 +00002982 "shouldn't have writeback for provably null argument");
2983
Craig Topper8a13c412014-05-21 05:09:00 +00002984 llvm::BasicBlock *contBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002985
2986 // If the argument wasn't provably non-null, we need to null check
2987 // before doing the store.
Nick Lewyckyd9bce502016-09-20 15:49:58 +00002988 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002989 if (!provablyNonNull) {
2990 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
2991 contBB = CGF.createBasicBlock("icr.done");
2992
John McCall7f416cc2015-09-08 08:05:57 +00002993 llvm::Value *isNull =
2994 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00002995 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
2996 CGF.EmitBlock(writebackBB);
2997 }
2998
2999 // Load the value to writeback.
3000 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3001
3002 // Cast it back, in case we're writing an id to a Foo* or something.
John McCall7f416cc2015-09-08 08:05:57 +00003003 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3004 "icr.writeback-cast");
John McCall31168b02011-06-15 23:02:42 +00003005
3006 // Perform the writeback.
John McCalleff18842013-03-23 02:35:54 +00003007
3008 // If we have a "to use" value, it's something we need to emit a use
3009 // of. This has to be carefully threaded in: if it's done after the
3010 // release it's potentially undefined behavior (and the optimizer
3011 // will ignore it), and if it happens before the retain then the
3012 // optimizer could move the release there.
3013 if (writeback.ToUse) {
3014 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3015
3016 // Retain the new value. No need to block-copy here: the block's
3017 // being passed up the stack.
3018 value = CGF.EmitARCRetainNonBlock(value);
3019
3020 // Emit the intrinsic use here.
3021 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3022
3023 // Load the old value (primitively).
Nick Lewycky2d84e842013-10-02 02:29:49 +00003024 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
John McCalleff18842013-03-23 02:35:54 +00003025
3026 // Put the new value in place (primitively).
3027 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3028
3029 // Release the old value.
3030 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3031
3032 // Otherwise, we can just do a normal lvalue store.
3033 } else {
3034 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3035 }
John McCall31168b02011-06-15 23:02:42 +00003036
3037 // Jump to the continuation block.
3038 if (!provablyNonNull)
3039 CGF.EmitBlock(contBB);
3040}
3041
3042static void emitWritebacks(CodeGenFunction &CGF,
3043 const CallArgList &args) {
Aaron Ballman36a7fa82014-03-17 17:22:27 +00003044 for (const auto &I : args.writebacks())
3045 emitWriteback(CGF, I);
John McCall31168b02011-06-15 23:02:42 +00003046}
3047
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003048static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3049 const CallArgList &CallArgs) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003050 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003051 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3052 CallArgs.getCleanupsToDeactivate();
3053 // Iterate in reverse to increase the likelihood of popping the cleanup.
Pete Cooper57d3f142015-07-30 17:22:52 +00003054 for (const auto &I : llvm::reverse(Cleanups)) {
3055 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3056 I.IsActiveIP->eraseFromParent();
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003057 }
3058}
3059
John McCalleff18842013-03-23 02:35:54 +00003060static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3061 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3062 if (uop->getOpcode() == UO_AddrOf)
3063 return uop->getSubExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00003064 return nullptr;
John McCalleff18842013-03-23 02:35:54 +00003065}
3066
John McCall31168b02011-06-15 23:02:42 +00003067/// Emit an argument that's being passed call-by-writeback. That is,
John McCall7f416cc2015-09-08 08:05:57 +00003068/// we are passing the address of an __autoreleased temporary; it
3069/// might be copy-initialized with the current value of the given
3070/// address, but it will definitely be copied out of after the call.
John McCall31168b02011-06-15 23:02:42 +00003071static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3072 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCalleff18842013-03-23 02:35:54 +00003073 LValue srcLV;
3074
3075 // Make an optimistic effort to emit the address as an l-value.
Eric Christopher2c4555a2015-06-19 01:52:53 +00003076 // This can fail if the argument expression is more complicated.
John McCalleff18842013-03-23 02:35:54 +00003077 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3078 srcLV = CGF.EmitLValue(lvExpr);
3079
3080 // Otherwise, just emit it as a scalar.
3081 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003082 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
John McCalleff18842013-03-23 02:35:54 +00003083
3084 QualType srcAddrType =
3085 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003086 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCalleff18842013-03-23 02:35:54 +00003087 }
John McCall7f416cc2015-09-08 08:05:57 +00003088 Address srcAddr = srcLV.getAddress();
John McCall31168b02011-06-15 23:02:42 +00003089
3090 // The dest and src types don't necessarily match in LLVM terms
3091 // because of the crazy ObjC compatibility rules.
3092
Chris Lattner2192fe52011-07-18 04:24:23 +00003093 llvm::PointerType *destType =
John McCall31168b02011-06-15 23:02:42 +00003094 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3095
3096 // If the address is a constant null, just pass the appropriate null.
John McCall7f416cc2015-09-08 08:05:57 +00003097 if (isProvablyNull(srcAddr.getPointer())) {
John McCall31168b02011-06-15 23:02:42 +00003098 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3099 CRE->getType());
3100 return;
3101 }
3102
John McCall31168b02011-06-15 23:02:42 +00003103 // Create the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00003104 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3105 CGF.getPointerAlign(),
3106 "icr.temp");
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003107 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3108 // and that cleanup will be conditional if we can't prove that the l-value
3109 // isn't null, so we need to register a dominating point so that the cleanups
3110 // system will make valid IR.
3111 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3112
John McCall31168b02011-06-15 23:02:42 +00003113 // Zero-initialize it if we're not doing a copy-initialization.
3114 bool shouldCopy = CRE->shouldCopy();
3115 if (!shouldCopy) {
3116 llvm::Value *null =
3117 llvm::ConstantPointerNull::get(
3118 cast<llvm::PointerType>(destType->getElementType()));
3119 CGF.Builder.CreateStore(null, temp);
3120 }
Craig Topper8a13c412014-05-21 05:09:00 +00003121
3122 llvm::BasicBlock *contBB = nullptr;
3123 llvm::BasicBlock *originBB = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003124
3125 // If the address is *not* known to be non-null, we need to switch.
3126 llvm::Value *finalArgument;
3127
Nick Lewyckyd9bce502016-09-20 15:49:58 +00003128 bool provablyNonNull = llvm::isKnownNonNull(srcAddr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00003129 if (provablyNonNull) {
John McCall7f416cc2015-09-08 08:05:57 +00003130 finalArgument = temp.getPointer();
John McCall31168b02011-06-15 23:02:42 +00003131 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003132 llvm::Value *isNull =
3133 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
John McCall31168b02011-06-15 23:02:42 +00003134
3135 finalArgument = CGF.Builder.CreateSelect(isNull,
3136 llvm::ConstantPointerNull::get(destType),
John McCall7f416cc2015-09-08 08:05:57 +00003137 temp.getPointer(), "icr.argument");
John McCall31168b02011-06-15 23:02:42 +00003138
3139 // If we need to copy, then the load has to be conditional, which
3140 // means we need control flow.
3141 if (shouldCopy) {
John McCalleff18842013-03-23 02:35:54 +00003142 originBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003143 contBB = CGF.createBasicBlock("icr.cont");
3144 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3145 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3146 CGF.EmitBlock(copyBB);
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003147 condEval.begin(CGF);
John McCall31168b02011-06-15 23:02:42 +00003148 }
3149 }
3150
Craig Topper8a13c412014-05-21 05:09:00 +00003151 llvm::Value *valueToUse = nullptr;
John McCalleff18842013-03-23 02:35:54 +00003152
John McCall31168b02011-06-15 23:02:42 +00003153 // Perform a copy if necessary.
3154 if (shouldCopy) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00003155 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00003156 assert(srcRV.isScalar());
3157
3158 llvm::Value *src = srcRV.getScalarVal();
3159 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3160 "icr.cast");
3161
3162 // Use an ordinary store, not a store-to-lvalue.
3163 CGF.Builder.CreateStore(src, temp);
John McCalleff18842013-03-23 02:35:54 +00003164
3165 // If optimization is enabled, and the value was held in a
3166 // __strong variable, we need to tell the optimizer that this
3167 // value has to stay alive until we're doing the store back.
3168 // This is because the temporary is effectively unretained,
3169 // and so otherwise we can violate the high-level semantics.
3170 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3171 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3172 valueToUse = src;
3173 }
John McCall31168b02011-06-15 23:02:42 +00003174 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003175
John McCall31168b02011-06-15 23:02:42 +00003176 // Finish the control flow if we needed it.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003177 if (shouldCopy && !provablyNonNull) {
John McCalleff18842013-03-23 02:35:54 +00003178 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCall31168b02011-06-15 23:02:42 +00003179 CGF.EmitBlock(contBB);
John McCalleff18842013-03-23 02:35:54 +00003180
3181 // Make a phi for the value to intrinsically use.
3182 if (valueToUse) {
3183 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3184 "icr.to-use");
3185 phiToUse->addIncoming(valueToUse, copyBB);
3186 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3187 originBB);
3188 valueToUse = phiToUse;
3189 }
3190
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00003191 condEval.end(CGF);
3192 }
John McCall31168b02011-06-15 23:02:42 +00003193
John McCalleff18842013-03-23 02:35:54 +00003194 args.addWriteback(srcLV, temp, valueToUse);
John McCall31168b02011-06-15 23:02:42 +00003195 args.add(RValue::get(finalArgument), CRE->getType());
3196}
3197
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003198void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
Richard Smith762672a2016-09-28 19:09:10 +00003199 assert(!StackBase);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003200
3201 // Save the stack.
3202 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie43f9bb72015-05-18 22:14:03 +00003203 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003204}
3205
Nico Weber8cdb3f92015-08-25 18:43:32 +00003206void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3207 if (StackBase) {
Reid Kleckner7c2f9e82015-10-08 00:17:45 +00003208 // Restore the stack after the call.
Nico Weber8cdb3f92015-08-25 18:43:32 +00003209 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
Nico Weber8cdb3f92015-08-25 18:43:32 +00003210 CGF.Builder.CreateCall(F, StackBase);
3211 }
3212}
3213
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003214void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3215 SourceLocation ArgLoc,
3216 const FunctionDecl *FD,
3217 unsigned ParmNum) {
3218 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003219 return;
3220 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
3221 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3222 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
3223 if (!NNAttr)
3224 return;
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003225 SanitizerScope SanScope(this);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003226 assert(RV.isScalar());
3227 llvm::Value *V = RV.getScalarVal();
3228 llvm::Value *Cond =
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003229 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003230 llvm::Constant *StaticData[] = {
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003231 EmitCheckSourceLocation(ArgLoc),
3232 EmitCheckSourceLocation(NNAttr->getLocation()),
3233 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003234 };
Nuno Lopes1ba2d782015-05-30 16:11:40 +00003235 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003236 SanitizerHandler::NonnullArg, StaticData, None);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00003237}
3238
David Blaikief05779e2015-07-21 18:37:18 +00003239void CodeGenFunction::EmitCallArgs(
3240 CallArgList &Args, ArrayRef<QualType> ArgTypes,
3241 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
Richard Smith762672a2016-09-28 19:09:10 +00003242 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip,
Richard Smitha560ccf2016-09-29 21:30:12 +00003243 EvaluationOrder Order) {
David Blaikief05779e2015-07-21 18:37:18 +00003244 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003245
Reid Kleckner739756c2013-12-04 19:23:12 +00003246 // We *have* to evaluate arguments from right to left in the MS C++ ABI,
Richard Smitha560ccf2016-09-29 21:30:12 +00003247 // because arguments are destroyed left to right in the callee. As a special
3248 // case, there are certain language constructs that require left-to-right
3249 // evaluation, and in those cases we consider the evaluation order requirement
3250 // to trump the "destruction order is reverse construction order" guarantee.
3251 bool LeftToRight =
3252 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
3253 ? Order == EvaluationOrder::ForceLeftToRight
3254 : Order != EvaluationOrder::ForceRightToLeft;
3255
George Burgess IV0d6592a2017-02-23 05:59:56 +00003256 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
3257 RValue EmittedArg) {
3258 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams())
3259 return;
3260 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>();
3261 if (PS == nullptr)
3262 return;
3263
3264 const auto &Context = getContext();
3265 auto SizeTy = Context.getSizeType();
3266 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3267 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
3268 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
3269 EmittedArg.getScalarVal());
3270 Args.add(RValue::get(V), SizeTy);
3271 // If we're emitting args in reverse, be sure to do so with
3272 // pass_object_size, as well.
3273 if (!LeftToRight)
3274 std::swap(Args.back(), *(&Args.back() - 1));
3275 };
3276
Richard Smitha560ccf2016-09-29 21:30:12 +00003277 // Insert a stack save if we're going to need any inalloca args.
3278 bool HasInAllocaArgs = false;
3279 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003280 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
3281 I != E && !HasInAllocaArgs; ++I)
3282 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
3283 if (HasInAllocaArgs) {
3284 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3285 Args.allocateArgumentMemory(*this);
3286 }
Richard Smitha560ccf2016-09-29 21:30:12 +00003287 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003288
Richard Smitha560ccf2016-09-29 21:30:12 +00003289 // Evaluate each argument in the appropriate order.
3290 size_t CallArgsStart = Args.size();
3291 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
3292 unsigned Idx = LeftToRight ? I : E - I - 1;
3293 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
George Burgess IV0d6592a2017-02-23 05:59:56 +00003294 unsigned InitialArgSize = Args.size();
Richard Smitha560ccf2016-09-29 21:30:12 +00003295 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
George Burgess IV0d6592a2017-02-23 05:59:56 +00003296 // In particular, we depend on it being the last arg in Args, and the
3297 // objectsize bits depend on there only being one arg if !LeftToRight.
3298 assert(InitialArgSize + 1 == Args.size() &&
3299 "The code below depends on only adding one arg per EmitCallArg");
3300 (void)InitialArgSize;
3301 RValue RVArg = Args.back().RV;
3302 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), CalleeDecl,
3303 ParamsToSkip + Idx);
3304 // @llvm.objectsize should never have side-effects and shouldn't need
3305 // destruction/cleanups, so we can safely "emit" it after its arg,
3306 // regardless of right-to-leftness
3307 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
Richard Smitha560ccf2016-09-29 21:30:12 +00003308 }
Reid Kleckner739756c2013-12-04 19:23:12 +00003309
Richard Smitha560ccf2016-09-29 21:30:12 +00003310 if (!LeftToRight) {
Reid Kleckner739756c2013-12-04 19:23:12 +00003311 // Un-reverse the arguments we just evaluated so they match up with the LLVM
3312 // IR function.
3313 std::reverse(Args.begin() + CallArgsStart, Args.end());
Reid Kleckner739756c2013-12-04 19:23:12 +00003314 }
3315}
3316
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003317namespace {
3318
David Blaikie7e70d682015-08-18 22:40:54 +00003319struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +00003320 DestroyUnpassedArg(Address Addr, QualType Ty)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003321 : Addr(Addr), Ty(Ty) {}
3322
John McCall7f416cc2015-09-08 08:05:57 +00003323 Address Addr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003324 QualType Ty;
3325
Craig Topper4f12f102014-03-12 06:41:41 +00003326 void Emit(CodeGenFunction &CGF, Flags flags) override {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003327 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
3328 assert(!Dtor->isTrivial());
3329 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
3330 /*Delegating=*/false, Addr);
3331 }
3332};
3333
David Blaikie38b25912015-02-09 19:13:51 +00003334struct DisableDebugLocationUpdates {
3335 CodeGenFunction &CGF;
3336 bool disabledDebugInfo;
3337 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
3338 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
3339 CGF.disableDebugInfo();
3340 }
3341 ~DisableDebugLocationUpdates() {
3342 if (disabledDebugInfo)
3343 CGF.enableDebugInfo();
3344 }
3345};
3346
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003347} // end anonymous namespace
3348
John McCall32ea9692011-03-11 20:59:21 +00003349void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
3350 QualType type) {
David Blaikie38b25912015-02-09 19:13:51 +00003351 DisableDebugLocationUpdates Dis(*this, E);
John McCall31168b02011-06-15 23:02:42 +00003352 if (const ObjCIndirectCopyRestoreExpr *CRE
3353 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003354 assert(getLangOpts().ObjCAutoRefCount);
Vedant Kumar30914f32016-10-03 15:29:22 +00003355 assert(getContext().hasSameUnqualifiedType(E->getType(), type));
John McCall31168b02011-06-15 23:02:42 +00003356 return emitWritebackArg(*this, args, CRE);
3357 }
3358
John McCall0a76c0c2011-08-26 18:42:59 +00003359 assert(type->isReferenceType() == E->isGLValue() &&
3360 "reference binding to unmaterialized r-value!");
3361
John McCall17054bd62011-08-26 21:08:13 +00003362 if (E->isGLValue()) {
3363 assert(E->getObjectKind() == OK_Ordinary);
Richard Smitha1c9d4d2013-06-12 23:38:09 +00003364 return args.add(EmitReferenceBindingToExpr(E), type);
John McCall17054bd62011-08-26 21:08:13 +00003365 }
Mike Stump11289f42009-09-09 15:08:12 +00003366
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003367 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
3368
3369 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
3370 // However, we still have to push an EH-only cleanup in case we unwind before
3371 // we make it to the call.
Reid Klecknerac640602014-05-01 03:07:18 +00003372 if (HasAggregateEvalKind &&
3373 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3374 // If we're using inalloca, use the argument memory. Otherwise, use a
Reid Klecknere39ee212014-05-03 00:33:28 +00003375 // temporary.
Reid Klecknerac640602014-05-01 03:07:18 +00003376 AggValueSlot Slot;
3377 if (args.isUsingInAlloca())
3378 Slot = createPlaceholderSlot(*this, type);
3379 else
3380 Slot = CreateAggTemp(type, "agg.tmp");
Reid Klecknere39ee212014-05-03 00:33:28 +00003381
3382 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3383 bool DestroyedInCallee =
3384 RD && RD->hasNonTrivialDestructor() &&
3385 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
3386 if (DestroyedInCallee)
3387 Slot.setExternallyDestructed();
3388
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003389 EmitAggExpr(E, Slot);
3390 RValue RV = Slot.asRValue();
3391 args.add(RV, type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003392
Reid Klecknere39ee212014-05-03 00:33:28 +00003393 if (DestroyedInCallee) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003394 // Create a no-op GEP between the placeholder and the cleanup so we can
3395 // RAUW it successfully. It also serves as a marker of the first
3396 // instruction where the cleanup is active.
John McCall7f416cc2015-09-08 08:05:57 +00003397 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
3398 type);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003399 // This unreachable is a temporary marker which will be removed later.
3400 llvm::Instruction *IsActive = Builder.CreateUnreachable();
3401 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003402 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003403 return;
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003404 }
3405
3406 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedmandf968192011-05-26 00:10:27 +00003407 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
3408 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
3409 assert(L.isSimple());
Eli Friedman61f615a2013-06-11 01:08:22 +00003410 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
3411 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
3412 } else {
3413 // We can't represent a misaligned lvalue in the CallArgList, so copy
3414 // to an aligned temporary now.
John McCall7f416cc2015-09-08 08:05:57 +00003415 Address tmp = CreateMemTemp(type);
3416 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
Eli Friedman61f615a2013-06-11 01:08:22 +00003417 args.add(RValue::getAggregate(tmp), type);
3418 }
Eli Friedmandf968192011-05-26 00:10:27 +00003419 return;
3420 }
3421
John McCall32ea9692011-03-11 20:59:21 +00003422 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson60ce3fe2009-04-08 20:47:54 +00003423}
3424
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003425QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
3426 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
3427 // implicitly widens null pointer constants that are arguments to varargs
3428 // functions to pointer-sized ints.
3429 if (!getTarget().getTriple().isOSWindows())
3430 return Arg->getType();
3431
3432 if (Arg->getType()->isIntegerType() &&
3433 getContext().getTypeSize(Arg->getType()) <
3434 getContext().getTargetInfo().getPointerWidth(0) &&
3435 Arg->isNullPointerConstant(getContext(),
3436 Expr::NPC_ValueDependentIsNotNull)) {
3437 return getContext().getIntPtrType();
3438 }
3439
3440 return Arg->getType();
3441}
3442
Dan Gohman515a60d2012-02-16 00:57:37 +00003443// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3444// optimizer it can aggressively ignore unwind edges.
3445void
3446CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
3447 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3448 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
3449 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
3450 CGM.getNoObjCARCExceptionsMetadata());
3451}
3452
John McCall882987f2013-02-28 19:01:20 +00003453/// Emits a call to the given no-arguments nounwind runtime function.
3454llvm::CallInst *
3455CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3456 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003457 return EmitNounwindRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003458}
3459
3460/// Emits a call to the given nounwind runtime function.
3461llvm::CallInst *
3462CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
3463 ArrayRef<llvm::Value*> args,
3464 const llvm::Twine &name) {
3465 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
3466 call->setDoesNotThrow();
3467 return call;
3468}
3469
3470/// Emits a simple call (never an invoke) to the given no-arguments
3471/// runtime function.
3472llvm::CallInst *
3473CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3474 const llvm::Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003475 return EmitRuntimeCall(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003476}
3477
David Majnemer0b17d442015-12-15 21:27:59 +00003478// Calls which may throw must have operand bundles indicating which funclet
3479// they are nested within.
3480static void
Sanjay Patel846b63b2016-01-18 22:15:33 +00003481getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad,
David Majnemer0b17d442015-12-15 21:27:59 +00003482 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) {
Sanjay Patel846b63b2016-01-18 22:15:33 +00003483 // There is no need for a funclet operand bundle if we aren't inside a
3484 // funclet.
David Majnemer0b17d442015-12-15 21:27:59 +00003485 if (!CurrentFuncletPad)
3486 return;
3487
3488 // Skip intrinsics which cannot throw.
3489 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
3490 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
3491 return;
3492
3493 BundleList.emplace_back("funclet", CurrentFuncletPad);
3494}
3495
David Majnemer971d31b2016-02-24 17:02:45 +00003496/// Emits a simple call (never an invoke) to the given runtime function.
3497llvm::CallInst *
3498CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
3499 ArrayRef<llvm::Value*> args,
3500 const llvm::Twine &name) {
3501 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3502 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3503
3504 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name);
3505 call->setCallingConv(getRuntimeCC());
3506 return call;
3507}
3508
John McCall882987f2013-02-28 19:01:20 +00003509/// Emits a call or invoke to the given noreturn runtime function.
3510void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3511 ArrayRef<llvm::Value*> args) {
David Majnemer0b17d442015-12-15 21:27:59 +00003512 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3513 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList);
3514
John McCall882987f2013-02-28 19:01:20 +00003515 if (getInvokeDest()) {
3516 llvm::InvokeInst *invoke =
3517 Builder.CreateInvoke(callee,
3518 getUnreachableBlock(),
3519 getInvokeDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003520 args,
3521 BundleList);
John McCall882987f2013-02-28 19:01:20 +00003522 invoke->setDoesNotReturn();
3523 invoke->setCallingConv(getRuntimeCC());
3524 } else {
David Majnemer0b17d442015-12-15 21:27:59 +00003525 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
John McCall882987f2013-02-28 19:01:20 +00003526 call->setDoesNotReturn();
3527 call->setCallingConv(getRuntimeCC());
3528 Builder.CreateUnreachable();
3529 }
3530}
3531
Sanjay Patel846b63b2016-01-18 22:15:33 +00003532/// Emits a call or invoke instruction to the given nullary runtime function.
John McCall882987f2013-02-28 19:01:20 +00003533llvm::CallSite
3534CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3535 const Twine &name) {
Craig Topper5fc8fc22014-08-27 06:28:36 +00003536 return EmitRuntimeCallOrInvoke(callee, None, name);
John McCall882987f2013-02-28 19:01:20 +00003537}
3538
3539/// Emits a call or invoke instruction to the given runtime function.
3540llvm::CallSite
3541CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
3542 ArrayRef<llvm::Value*> args,
3543 const Twine &name) {
3544 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
3545 callSite.setCallingConv(getRuntimeCC());
3546 return callSite;
3547}
3548
John McCallbd309292010-07-06 01:34:17 +00003549/// Emits a call or invoke instruction to the given function, depending
3550/// on the current state of the EH stack.
3551llvm::CallSite
3552CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner54b16772011-07-23 17:14:25 +00003553 ArrayRef<llvm::Value *> Args,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003554 const Twine &Name) {
John McCallbd309292010-07-06 01:34:17 +00003555 llvm::BasicBlock *InvokeDest = getInvokeDest();
David Majnemer3df77bc2016-01-26 23:14:47 +00003556 SmallVector<llvm::OperandBundleDef, 1> BundleList;
3557 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList);
John McCallbd309292010-07-06 01:34:17 +00003558
Dan Gohman515a60d2012-02-16 00:57:37 +00003559 llvm::Instruction *Inst;
3560 if (!InvokeDest)
David Majnemer3df77bc2016-01-26 23:14:47 +00003561 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003562 else {
3563 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
David Majnemer3df77bc2016-01-26 23:14:47 +00003564 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
3565 Name);
Dan Gohman515a60d2012-02-16 00:57:37 +00003566 EmitBlock(ContBB);
3567 }
3568
3569 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
3570 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003571 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohman515a60d2012-02-16 00:57:37 +00003572 AddObjCARCExceptionMetadata(Inst);
3573
Benjamin Kramerc19cde12015-04-10 14:49:31 +00003574 return llvm::CallSite(Inst);
John McCallbd309292010-07-06 01:34:17 +00003575}
3576
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003577/// \brief Store a non-aggregate value to an address to initialize it. For
3578/// initialization, a non-atomic store will be used.
3579static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
3580 LValue Dst) {
3581 if (Src.isScalar())
3582 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
3583 else
3584 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
3585}
3586
3587void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
3588 llvm::Value *New) {
3589 DeferredReplacements.push_back(std::make_pair(Old, New));
3590}
Chris Lattnerd59d8672011-07-12 06:29:11 +00003591
Daniel Dunbard931a872009-02-02 22:03:45 +00003592RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
John McCallb92ab1a2016-10-26 23:46:34 +00003593 const CGCallee &Callee,
Anders Carlsson61a401c2009-12-24 19:25:24 +00003594 ReturnValueSlot ReturnValue,
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003595 const CallArgList &CallArgs,
David Chisnallff5f88c2010-05-02 13:41:58 +00003596 llvm::Instruction **callOrInvoke) {
Mike Stump18bb9282009-05-16 07:57:57 +00003597 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar613855c2008-09-09 23:27:19 +00003598
John McCallb92ab1a2016-10-26 23:46:34 +00003599 assert(Callee.isOrdinary());
3600
Daniel Dunbar613855c2008-09-09 23:27:19 +00003601 // Handle struct-return functions by passing a pointer to the
3602 // location that we would like to return into.
Daniel Dunbar7633cbf2009-02-02 21:43:58 +00003603 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003604 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003605
John McCallb92ab1a2016-10-26 23:46:34 +00003606 llvm::FunctionType *IRFuncTy = Callee.getFunctionType();
3607
3608 // 1. Set up the arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003609
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003610 // If we're using inalloca, insert the allocation after the stack save.
3611 // FIXME: Do this earlier rather than hacking it in here!
John McCall7f416cc2015-09-08 08:05:57 +00003612 Address ArgMemory = Address::invalid();
3613 const llvm::StructLayout *ArgMemoryLayout = nullptr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003614 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
John McCall7f416cc2015-09-08 08:05:57 +00003615 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
Reid Kleckner9df1d972014-04-10 01:40:15 +00003616 llvm::Instruction *IP = CallArgs.getStackBase();
3617 llvm::AllocaInst *AI;
3618 if (IP) {
3619 IP = IP->getNextNode();
3620 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
3621 } else {
Reid Kleckner966abe72014-05-15 23:01:46 +00003622 AI = CreateTempAlloca(ArgStruct, "argmem");
Reid Kleckner9df1d972014-04-10 01:40:15 +00003623 }
John McCall7f416cc2015-09-08 08:05:57 +00003624 auto Align = CallInfo.getArgStructAlignment();
3625 AI->setAlignment(Align.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003626 AI->setUsedWithInAlloca(true);
3627 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
John McCall7f416cc2015-09-08 08:05:57 +00003628 ArgMemory = Address(AI, Align);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003629 }
3630
John McCall7f416cc2015-09-08 08:05:57 +00003631 // Helper function to drill into the inalloca allocation.
3632 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
3633 auto FieldOffset =
3634 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
3635 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
3636 };
3637
Alexey Samsonov153004f2014-09-29 22:08:00 +00003638 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003639 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
3640
Chris Lattner4ca97c32009-06-13 00:26:38 +00003641 // If the call returns a temporary with struct return, create a temporary
Anders Carlsson17490832009-12-24 20:40:36 +00003642 // alloca to hold the result, unless one is given to us.
John McCall7f416cc2015-09-08 08:05:57 +00003643 Address SRetPtr = Address::invalid();
Leny Kholodov6aab1112015-06-08 10:23:49 +00003644 size_t UnusedReturnSize = 0;
John McCallf26e73d2016-03-11 04:30:43 +00003645 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
John McCall7f416cc2015-09-08 08:05:57 +00003646 if (!ReturnValue.isNull()) {
3647 SRetPtr = ReturnValue.getValue();
3648 } else {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003649 SRetPtr = CreateMemTemp(RetTy);
Leny Kholodov6aab1112015-06-08 10:23:49 +00003650 if (HaveInsertPoint() && ReturnValue.isUnused()) {
3651 uint64_t size =
3652 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
John McCall7f416cc2015-09-08 08:05:57 +00003653 if (EmitLifetimeStart(size, SRetPtr.getPointer()))
Leny Kholodov6aab1112015-06-08 10:23:49 +00003654 UnusedReturnSize = size;
3655 }
3656 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003657 if (IRFunctionArgs.hasSRetArg()) {
John McCall7f416cc2015-09-08 08:05:57 +00003658 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
John McCallf26e73d2016-03-11 04:30:43 +00003659 } else if (RetAI.isInAlloca()) {
John McCall7f416cc2015-09-08 08:05:57 +00003660 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
3661 Builder.CreateStore(SRetPtr.getPointer(), Addr);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003662 }
Anders Carlsson17490832009-12-24 20:40:36 +00003663 }
Mike Stump11289f42009-09-09 15:08:12 +00003664
John McCall12f23522016-04-04 18:33:08 +00003665 Address swiftErrorTemp = Address::invalid();
3666 Address swiftErrorArg = Address::invalid();
3667
John McCallb92ab1a2016-10-26 23:46:34 +00003668 // Translate all of the arguments as necessary to match the IR lowering.
Daniel Dunbara45bdbb2009-02-04 21:17:21 +00003669 assert(CallInfo.arg_size() == CallArgs.size() &&
3670 "Mismatch between function signature & arguments.");
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003671 unsigned ArgNo = 0;
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003672 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump11289f42009-09-09 15:08:12 +00003673 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003674 I != E; ++I, ++info_it, ++ArgNo) {
Daniel Dunbarb52d0772009-02-03 05:59:18 +00003675 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanf4258eb2011-05-02 18:05:27 +00003676 RValue RV = I->RV;
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003677
Rafael Espindolafad28de2012-10-24 01:59:00 +00003678 // Insert a padding argument to ensure proper alignment.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003679 if (IRFunctionArgs.hasPaddingArg(ArgNo))
3680 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
3681 llvm::UndefValue::get(ArgInfo.getPaddingType());
3682
3683 unsigned FirstIRArg, NumIRArgs;
3684 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
Rafael Espindolafad28de2012-10-24 01:59:00 +00003685
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003686 switch (ArgInfo.getKind()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003687 case ABIArgInfo::InAlloca: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003688 assert(NumIRArgs == 0);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003689 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
3690 if (RV.isAggregate()) {
3691 // Replace the placeholder with the appropriate argument slot GEP.
3692 llvm::Instruction *Placeholder =
John McCall7f416cc2015-09-08 08:05:57 +00003693 cast<llvm::Instruction>(RV.getAggregatePointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003694 CGBuilderTy::InsertPoint IP = Builder.saveIP();
3695 Builder.SetInsertPoint(Placeholder);
John McCall7f416cc2015-09-08 08:05:57 +00003696 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003697 Builder.restoreIP(IP);
John McCall7f416cc2015-09-08 08:05:57 +00003698 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003699 } else {
3700 // Store the RValue into the argument struct.
John McCall7f416cc2015-09-08 08:05:57 +00003701 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
3702 unsigned AS = Addr.getType()->getPointerAddressSpace();
David Majnemer32b57b02014-03-31 16:12:47 +00003703 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
3704 // There are some cases where a trivial bitcast is not avoidable. The
3705 // definition of a type later in a translation unit may change it's type
3706 // from {}* to (%struct.foo*)*.
John McCall7f416cc2015-09-08 08:05:57 +00003707 if (Addr.getType() != MemType)
David Majnemer32b57b02014-03-31 16:12:47 +00003708 Addr = Builder.CreateBitCast(Addr, MemType);
John McCall7f416cc2015-09-08 08:05:57 +00003709 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003710 EmitInitStoreOfNonAggregate(*this, RV, argLV);
3711 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003712 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003713 }
3714
Daniel Dunbar03816342010-08-21 02:24:36 +00003715 case ABIArgInfo::Indirect: {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003716 assert(NumIRArgs == 1);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003717 if (RV.isScalar() || RV.isComplex()) {
3718 // Make a temporary alloca to pass the argument.
John McCall7f416cc2015-09-08 08:05:57 +00003719 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3720 IRCallArgs[FirstIRArg] = Addr.getPointer();
John McCall47fb9502013-03-07 21:37:08 +00003721
John McCall7f416cc2015-09-08 08:05:57 +00003722 LValue argLV = MakeAddrLValue(Addr, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003723 EmitInitStoreOfNonAggregate(*this, RV, argLV);
Daniel Dunbar747865a2009-02-05 09:16:39 +00003724 } else {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003725 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyei3832bfd2013-03-10 12:59:00 +00003726 // however, we need one in three cases:
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003727 // 1. If the argument is not byval, and we are required to copy the
3728 // source. (This case doesn't occur on any common architecture.)
3729 // 2. If the argument is byval, RV is not sufficiently aligned, and
3730 // we cannot force it to be sufficiently aligned.
Guy Benyei3832bfd2013-03-10 12:59:00 +00003731 // 3. If the argument is byval, but RV is located in an address space
3732 // different than that of the argument (0).
John McCall7f416cc2015-09-08 08:05:57 +00003733 Address Addr = RV.getAggregateAddress();
3734 CharUnits Align = ArgInfo.getIndirectAlign();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003735 const llvm::DataLayout *TD = &CGM.getDataLayout();
John McCall7f416cc2015-09-08 08:05:57 +00003736 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003737 const unsigned ArgAddrSpace =
3738 (FirstIRArg < IRFuncTy->getNumParams()
3739 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
3740 : 0);
Eli Friedmanf7456192011-06-15 22:09:18 +00003741 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall7f416cc2015-09-08 08:05:57 +00003742 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
3743 llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
3744 Align.getQuantity(), *TD)
3745 < Align.getQuantity()) ||
Mehdi Aminib3d52092015-03-10 02:36:43 +00003746 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003747 // Create an aligned temporary, and copy to it.
John McCall7f416cc2015-09-08 08:05:57 +00003748 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
3749 IRCallArgs[FirstIRArg] = AI.getPointer();
Chad Rosier615ed1a2012-03-29 17:37:10 +00003750 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003751 } else {
3752 // Skip the extra memcpy call.
John McCall7f416cc2015-09-08 08:05:57 +00003753 IRCallArgs[FirstIRArg] = Addr.getPointer();
Eli Friedmaneb7fab62011-06-14 01:37:52 +00003754 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003755 }
3756 break;
Daniel Dunbar03816342010-08-21 02:24:36 +00003757 }
Daniel Dunbar747865a2009-02-05 09:16:39 +00003758
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003759 case ABIArgInfo::Ignore:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003760 assert(NumIRArgs == 0);
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003761 break;
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003762
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003763 case ABIArgInfo::Extend:
3764 case ABIArgInfo::Direct: {
3765 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003766 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
3767 ArgInfo.getDirectOffset() == 0) {
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003768 assert(NumIRArgs == 1);
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003769 llvm::Value *V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003770 if (RV.isScalar())
Chris Lattnerbb1952c2011-07-12 04:46:18 +00003771 V = RV.getScalarVal();
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003772 else
John McCall7f416cc2015-09-08 08:05:57 +00003773 V = Builder.CreateLoad(RV.getAggregateAddress());
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003774
John McCall12f23522016-04-04 18:33:08 +00003775 // Implement swifterror by copying into a new swifterror argument.
3776 // We'll write back in the normal path out of the call.
3777 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
3778 == ParameterABI::SwiftErrorResult) {
3779 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
3780
3781 QualType pointeeTy = I->Ty->getPointeeType();
3782 swiftErrorArg =
3783 Address(V, getContext().getTypeAlignInChars(pointeeTy));
3784
3785 swiftErrorTemp =
3786 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
3787 V = swiftErrorTemp.getPointer();
3788 cast<llvm::AllocaInst>(V)->setSwiftError(true);
3789
3790 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
3791 Builder.CreateStore(errorValue, swiftErrorTemp);
3792 }
3793
Reid Kleckner79b0fd72014-10-10 00:05:45 +00003794 // We might have to widen integers, but we should never truncate.
3795 if (ArgInfo.getCoerceToType() != V->getType() &&
3796 V->getType()->isIntegerTy())
3797 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
3798
Chris Lattner3ce86682011-07-12 04:53:39 +00003799 // If the argument doesn't match, perform a bitcast to coerce it. This
3800 // can happen due to trivial type mismatches.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003801 if (FirstIRArg < IRFuncTy->getNumParams() &&
3802 V->getType() != IRFuncTy->getParamType(FirstIRArg))
3803 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
John McCall12f23522016-04-04 18:33:08 +00003804
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003805 IRCallArgs[FirstIRArg] = V;
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003806 break;
3807 }
Daniel Dunbar94a6f252009-01-26 21:26:08 +00003808
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003809 // FIXME: Avoid the conversion through memory if possible.
John McCall7f416cc2015-09-08 08:05:57 +00003810 Address Src = Address::invalid();
John McCall47fb9502013-03-07 21:37:08 +00003811 if (RV.isScalar() || RV.isComplex()) {
John McCall7f416cc2015-09-08 08:05:57 +00003812 Src = CreateMemTemp(I->Ty, "coerce");
3813 LValue SrcLV = MakeAddrLValue(Src, I->Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003814 EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003815 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003816 Src = RV.getAggregateAddress();
Ulrich Weigand6e2cea62015-07-10 11:31:43 +00003817 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003818
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003819 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00003820 Src = emitAddressAtOffset(*this, Src, ArgInfo);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003821
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003822 // Fast-isel and the optimizer generally like scalar values better than
3823 // FCAs, so we flatten them if this is safe to do for this argument.
James Molloy6f244b62014-05-09 16:21:39 +00003824 llvm::StructType *STy =
3825 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00003826 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
John McCall7f416cc2015-09-08 08:05:57 +00003827 llvm::Type *SrcTy = Src.getType()->getElementType();
Chandler Carrutha6399a52012-10-10 11:29:08 +00003828 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
3829 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
3830
3831 // If the source type is smaller than the destination type of the
3832 // coerce-to logic, copy the source value into a temp alloca the size
3833 // of the destination type to allow loading all of it. The bits past
3834 // the source value are left undef.
3835 if (SrcSize < DstSize) {
John McCall7f416cc2015-09-08 08:05:57 +00003836 Address TempAlloca
3837 = CreateTempAlloca(STy, Src.getAlignment(),
3838 Src.getName() + ".coerce");
3839 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
3840 Src = TempAlloca;
Chandler Carrutha6399a52012-10-10 11:29:08 +00003841 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003842 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
Chandler Carrutha6399a52012-10-10 11:29:08 +00003843 }
3844
John McCall7f416cc2015-09-08 08:05:57 +00003845 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003846 assert(NumIRArgs == STy->getNumElements());
Chris Lattnerceddafb2010-07-05 20:41:41 +00003847 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00003848 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
3849 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
3850 llvm::Value *LI = Builder.CreateLoad(EltPtr);
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003851 IRCallArgs[FirstIRArg + i] = LI;
Chris Lattner15ec3612010-06-29 00:06:42 +00003852 }
Chris Lattner3dd716c2010-06-28 23:44:11 +00003853 } else {
Chris Lattner15ec3612010-06-29 00:06:42 +00003854 // In the simple case, just pass the coerced loaded value.
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003855 assert(NumIRArgs == 1);
3856 IRCallArgs[FirstIRArg] =
John McCall7f416cc2015-09-08 08:05:57 +00003857 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
Chris Lattner3dd716c2010-06-28 23:44:11 +00003858 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003859
Daniel Dunbar2f219b02009-02-03 19:12:28 +00003860 break;
3861 }
3862
John McCallf26e73d2016-03-11 04:30:43 +00003863 case ABIArgInfo::CoerceAndExpand: {
John McCallf26e73d2016-03-11 04:30:43 +00003864 auto coercionType = ArgInfo.getCoerceAndExpandType();
3865 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
3866
John McCall12f23522016-04-04 18:33:08 +00003867 llvm::Value *tempSize = nullptr;
3868 Address addr = Address::invalid();
3869 if (RV.isAggregate()) {
3870 addr = RV.getAggregateAddress();
3871 } else {
3872 assert(RV.isScalar()); // complex should always just be direct
3873
3874 llvm::Type *scalarType = RV.getScalarVal()->getType();
3875 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
3876 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
3877
3878 tempSize = llvm::ConstantInt::get(CGM.Int64Ty, scalarSize);
3879
3880 // Materialize to a temporary.
3881 addr = CreateTempAlloca(RV.getScalarVal()->getType(),
3882 CharUnits::fromQuantity(std::max(layout->getAlignment(),
3883 scalarAlign)));
3884 EmitLifetimeStart(scalarSize, addr.getPointer());
3885
3886 Builder.CreateStore(RV.getScalarVal(), addr);
3887 }
3888
John McCallf26e73d2016-03-11 04:30:43 +00003889 addr = Builder.CreateElementBitCast(addr, coercionType);
3890
3891 unsigned IRArgPos = FirstIRArg;
3892 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3893 llvm::Type *eltType = coercionType->getElementType(i);
3894 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
3895 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
3896 llvm::Value *elt = Builder.CreateLoad(eltAddr);
3897 IRCallArgs[IRArgPos++] = elt;
3898 }
3899 assert(IRArgPos == FirstIRArg + NumIRArgs);
3900
John McCall12f23522016-04-04 18:33:08 +00003901 if (tempSize) {
3902 EmitLifetimeEnd(tempSize, addr.getPointer());
3903 }
3904
John McCallf26e73d2016-03-11 04:30:43 +00003905 break;
3906 }
3907
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003908 case ABIArgInfo::Expand:
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003909 unsigned IRArgPos = FirstIRArg;
3910 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
3911 assert(IRArgPos == FirstIRArg + NumIRArgs);
Daniel Dunbar8fc81b02008-09-17 00:51:38 +00003912 break;
Daniel Dunbar613855c2008-09-09 23:27:19 +00003913 }
3914 }
Mike Stump11289f42009-09-09 15:08:12 +00003915
John McCallb92ab1a2016-10-26 23:46:34 +00003916 llvm::Value *CalleePtr = Callee.getFunctionPointer();
3917
3918 // If we're using inalloca, set up that argument.
John McCall7f416cc2015-09-08 08:05:57 +00003919 if (ArgMemory.isValid()) {
3920 llvm::Value *Arg = ArgMemory.getPointer();
Reid Klecknerafba553e2014-07-08 02:24:27 +00003921 if (CallInfo.isVariadic()) {
3922 // When passing non-POD arguments by value to variadic functions, we will
3923 // end up with a variadic prototype and an inalloca call site. In such
3924 // cases, we can't do any parameter mismatch checks. Give up and bitcast
3925 // the callee.
John McCallb92ab1a2016-10-26 23:46:34 +00003926 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
3927 auto FnTy = getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS);
3928 CalleePtr = Builder.CreateBitCast(CalleePtr, FnTy);
Reid Klecknerafba553e2014-07-08 02:24:27 +00003929 } else {
3930 llvm::Type *LastParamTy =
3931 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
3932 if (Arg->getType() != LastParamTy) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003933#ifndef NDEBUG
Reid Klecknerafba553e2014-07-08 02:24:27 +00003934 // Assert that these structs have equivalent element types.
3935 llvm::StructType *FullTy = CallInfo.getArgStruct();
3936 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
3937 cast<llvm::PointerType>(LastParamTy)->getElementType());
3938 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
3939 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
3940 DE = DeclaredTy->element_end(),
3941 FI = FullTy->element_begin();
3942 DI != DE; ++DI, ++FI)
3943 assert(*DI == *FI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003944#endif
Reid Klecknerafba553e2014-07-08 02:24:27 +00003945 Arg = Builder.CreateBitCast(Arg, LastParamTy);
3946 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003947 }
Alexey Samsonov91cf4552014-08-22 01:06:06 +00003948 assert(IRFunctionArgs.hasInallocaArg());
3949 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00003950 }
3951
John McCallb92ab1a2016-10-26 23:46:34 +00003952 // 2. Prepare the function pointer.
3953
3954 // If the callee is a bitcast of a non-variadic function to have a
3955 // variadic function pointer type, check to see if we can remove the
3956 // bitcast. This comes up with unprototyped functions.
3957 //
3958 // This makes the IR nicer, but more importantly it ensures that we
3959 // can inline the function at -O0 if it is marked always_inline.
3960 auto simplifyVariadicCallee = [](llvm::Value *Ptr) -> llvm::Value* {
3961 llvm::FunctionType *CalleeFT =
3962 cast<llvm::FunctionType>(Ptr->getType()->getPointerElementType());
3963 if (!CalleeFT->isVarArg())
3964 return Ptr;
3965
3966 llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr);
3967 if (!CE || CE->getOpcode() != llvm::Instruction::BitCast)
3968 return Ptr;
3969
3970 llvm::Function *OrigFn = dyn_cast<llvm::Function>(CE->getOperand(0));
3971 if (!OrigFn)
3972 return Ptr;
3973
3974 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
3975
3976 // If the original type is variadic, or if any of the component types
3977 // disagree, we cannot remove the cast.
3978 if (OrigFT->isVarArg() ||
3979 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
3980 OrigFT->getReturnType() != CalleeFT->getReturnType())
3981 return Ptr;
3982
3983 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
3984 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
3985 return Ptr;
3986
3987 return OrigFn;
3988 };
3989 CalleePtr = simplifyVariadicCallee(CalleePtr);
3990
3991 // 3. Perform the actual call.
3992
3993 // Deactivate any cleanups that we're supposed to do immediately before
3994 // the call.
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00003995 if (!CallArgs.getCleanupsToDeactivate().empty())
3996 deactivateArgCleanupsBeforeCall(*this, CallArgs);
3997
John McCallb92ab1a2016-10-26 23:46:34 +00003998 // Assert that the arguments we computed match up. The IR verifier
3999 // will catch this, but this is a common enough source of problems
4000 // during IRGen changes that it's way better for debugging to catch
4001 // it ourselves here.
4002#ifndef NDEBUG
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004003 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
4004 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
4005 // Inalloca argument can have different type.
4006 if (IRFunctionArgs.hasInallocaArg() &&
4007 i == IRFunctionArgs.getInallocaArgNo())
4008 continue;
4009 if (i < IRFuncTy->getNumParams())
4010 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
4011 }
John McCallb92ab1a2016-10-26 23:46:34 +00004012#endif
Alexey Samsonov91cf4552014-08-22 01:06:06 +00004013
John McCallb92ab1a2016-10-26 23:46:34 +00004014 // Compute the calling convention and attributes.
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004015 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +00004016 CodeGen::AttributeListType AttributeList;
John McCallb92ab1a2016-10-26 23:46:34 +00004017 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
4018 Callee.getAbstractInfo(),
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00004019 AttributeList, CallingConv,
4020 /*AttrOnCallSite=*/true);
Bill Wendling3087d022012-12-07 23:17:26 +00004021 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendlingf4d64cb2013-02-22 00:13:35 +00004022 AttributeList);
Mike Stump11289f42009-09-09 15:08:12 +00004023
John McCallb92ab1a2016-10-26 23:46:34 +00004024 // Apply some call-site-specific attributes.
4025 // TODO: work this into building the attribute set.
4026
4027 // Apply always_inline to all calls within flatten functions.
4028 // FIXME: should this really take priority over __try, below?
4029 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
4030 !(Callee.getAbstractInfo().getCalleeDecl() &&
4031 Callee.getAbstractInfo().getCalleeDecl()->hasAttr<NoInlineAttr>())) {
4032 Attrs =
4033 Attrs.addAttribute(getLLVMContext(),
4034 llvm::AttributeSet::FunctionIndex,
4035 llvm::Attribute::AlwaysInline);
4036 }
4037
4038 // Disable inlining inside SEH __try blocks.
4039 if (isSEHTryScope()) {
4040 Attrs =
4041 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
4042 llvm::Attribute::NoInline);
4043 }
4044
4045 // Decide whether to use a call or an invoke.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004046 bool CannotThrow;
4047 if (currentFunctionUsesSEHTry()) {
John McCallb92ab1a2016-10-26 23:46:34 +00004048 // SEH cares about asynchronous exceptions, so everything can "throw."
David Majnemer4e52d6f2015-12-12 05:39:21 +00004049 CannotThrow = false;
4050 } else if (isCleanupPadScope() &&
4051 EHPersonality::get(*this).isMSVCXXPersonality()) {
4052 // The MSVC++ personality will implicitly terminate the program if an
John McCallb92ab1a2016-10-26 23:46:34 +00004053 // exception is thrown during a cleanup outside of a try/catch.
4054 // We don't need to model anything in IR to get this behavior.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004055 CannotThrow = true;
4056 } else {
John McCallb92ab1a2016-10-26 23:46:34 +00004057 // Otherwise, nounwind call sites will never throw.
David Majnemer4e52d6f2015-12-12 05:39:21 +00004058 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
4059 llvm::Attribute::NoUnwind);
4060 }
4061 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
John McCallbd309292010-07-06 01:34:17 +00004062
David Majnemer0b17d442015-12-15 21:27:59 +00004063 SmallVector<llvm::OperandBundleDef, 1> BundleList;
John McCallb92ab1a2016-10-26 23:46:34 +00004064 getBundlesForFunclet(CalleePtr, CurrentFuncletPad, BundleList);
David Majnemer0b17d442015-12-15 21:27:59 +00004065
John McCallb92ab1a2016-10-26 23:46:34 +00004066 // Emit the actual call/invoke instruction.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004067 llvm::CallSite CS;
John McCallbd309292010-07-06 01:34:17 +00004068 if (!InvokeDest) {
John McCallb92ab1a2016-10-26 23:46:34 +00004069 CS = Builder.CreateCall(CalleePtr, IRCallArgs, BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004070 } else {
4071 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
John McCallb92ab1a2016-10-26 23:46:34 +00004072 CS = Builder.CreateInvoke(CalleePtr, Cont, InvokeDest, IRCallArgs,
David Majnemer0b17d442015-12-15 21:27:59 +00004073 BundleList);
Daniel Dunbar12347492009-02-23 17:26:39 +00004074 EmitBlock(Cont);
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004075 }
John McCallb92ab1a2016-10-26 23:46:34 +00004076 llvm::Instruction *CI = CS.getInstruction();
Chris Lattnere70a0072010-06-29 16:40:28 +00004077 if (callOrInvoke)
John McCallb92ab1a2016-10-26 23:46:34 +00004078 *callOrInvoke = CI;
Daniel Dunbar5006f4a2009-02-20 18:54:31 +00004079
John McCallb92ab1a2016-10-26 23:46:34 +00004080 // Apply the attributes and calling convention.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004081 CS.setAttributes(Attrs);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00004082 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004083
John McCallb92ab1a2016-10-26 23:46:34 +00004084 // Apply various metadata.
4085
4086 if (!CI->getType()->isVoidTy())
4087 CI->setName("call");
4088
Adam Nemet1e217bc2016-03-28 22:18:53 +00004089 // Insert instrumentation or attach profile metadata at indirect call sites.
4090 // For more details, see the comment before the definition of
4091 // IPVK_IndirectCallTarget in InstrProfData.inc.
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004092 if (!CS.getCalledFunction())
4093 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
John McCallb92ab1a2016-10-26 23:46:34 +00004094 CI, CalleePtr);
Betul Buyukkurt518276a2016-01-23 22:50:44 +00004095
Dan Gohman515a60d2012-02-16 00:57:37 +00004096 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4097 // optimizer it can aggressively ignore unwind edges.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004098 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallb92ab1a2016-10-26 23:46:34 +00004099 AddObjCARCExceptionMetadata(CI);
4100
4101 // Suppress tail calls if requested.
4102 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
4103 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
4104 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
4105 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
4106 }
4107
4108 // 4. Finish the call.
Dan Gohman515a60d2012-02-16 00:57:37 +00004109
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004110 // If the call doesn't return, finish the basic block and clear the
John McCallb92ab1a2016-10-26 23:46:34 +00004111 // insertion point; this allows the rest of IRGen to discard
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004112 // unreachable code.
4113 if (CS.doesNotReturn()) {
Leny Kholodov6aab1112015-06-08 10:23:49 +00004114 if (UnusedReturnSize)
4115 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
John McCall7f416cc2015-09-08 08:05:57 +00004116 SRetPtr.getPointer());
Leny Kholodov6aab1112015-06-08 10:23:49 +00004117
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004118 Builder.CreateUnreachable();
4119 Builder.ClearInsertionPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004120
Mike Stump18bb9282009-05-16 07:57:57 +00004121 // FIXME: For now, emit a dummy basic block because expr emitters in
4122 // generally are not ready to handle emitting expressions at unreachable
4123 // points.
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004124 EnsureInsertPoint();
Mike Stump11289f42009-09-09 15:08:12 +00004125
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004126 // Return a reasonable RValue.
4127 return GetUndefRValue(RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00004128 }
Daniel Dunbarb960b7b2009-03-02 04:32:35 +00004129
John McCall12f23522016-04-04 18:33:08 +00004130 // Perform the swifterror writeback.
4131 if (swiftErrorTemp.isValid()) {
4132 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
4133 Builder.CreateStore(errorResult, swiftErrorArg);
4134 }
4135
John McCallb92ab1a2016-10-26 23:46:34 +00004136 // Emit any call-associated writebacks immediately. Arguably this
4137 // should happen after any return-value munging.
John McCall31168b02011-06-15 23:02:42 +00004138 if (CallArgs.hasWritebacks())
4139 emitWritebacks(*this, CallArgs);
4140
Nico Weber8cdb3f92015-08-25 18:43:32 +00004141 // The stack cleanup for inalloca arguments has to run out of the normal
4142 // lexical order, so deactivate it and run it manually here.
4143 CallArgs.freeArgumentMemory(*this);
4144
John McCallb92ab1a2016-10-26 23:46:34 +00004145 // Extract the return value.
Hal Finkelee90a222014-09-26 05:04:30 +00004146 RValue Ret = [&] {
4147 switch (RetAI.getKind()) {
John McCallf26e73d2016-03-11 04:30:43 +00004148 case ABIArgInfo::CoerceAndExpand: {
4149 auto coercionType = RetAI.getCoerceAndExpandType();
4150 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
4151
4152 Address addr = SRetPtr;
4153 addr = Builder.CreateElementBitCast(addr, coercionType);
4154
John McCall12f23522016-04-04 18:33:08 +00004155 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
4156 bool requiresExtract = isa<llvm::StructType>(CI->getType());
4157
John McCallf26e73d2016-03-11 04:30:43 +00004158 unsigned unpaddedIndex = 0;
4159 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4160 llvm::Type *eltType = coercionType->getElementType(i);
4161 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
4162 Address eltAddr = Builder.CreateStructGEP(addr, i, layout);
John McCall12f23522016-04-04 18:33:08 +00004163 llvm::Value *elt = CI;
4164 if (requiresExtract)
4165 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
4166 else
4167 assert(unpaddedIndex == 0);
John McCallf26e73d2016-03-11 04:30:43 +00004168 Builder.CreateStore(elt, eltAddr);
4169 }
John McCall12f23522016-04-04 18:33:08 +00004170 // FALLTHROUGH
4171 }
4172
4173 case ABIArgInfo::InAlloca:
4174 case ABIArgInfo::Indirect: {
4175 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
4176 if (UnusedReturnSize)
4177 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
4178 SRetPtr.getPointer());
4179 return ret;
John McCallf26e73d2016-03-11 04:30:43 +00004180 }
4181
Hal Finkelee90a222014-09-26 05:04:30 +00004182 case ABIArgInfo::Ignore:
4183 // If we are ignoring an argument that had a result, make sure to
4184 // construct the appropriate return value for our caller.
4185 return GetUndefRValue(RetTy);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004186
Hal Finkelee90a222014-09-26 05:04:30 +00004187 case ABIArgInfo::Extend:
4188 case ABIArgInfo::Direct: {
4189 llvm::Type *RetIRTy = ConvertType(RetTy);
4190 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
4191 switch (getEvaluationKind(RetTy)) {
4192 case TEK_Complex: {
4193 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
4194 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
4195 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004196 }
Hal Finkelee90a222014-09-26 05:04:30 +00004197 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00004198 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004199 bool DestIsVolatile = ReturnValue.isVolatile();
4200
John McCall7f416cc2015-09-08 08:05:57 +00004201 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004202 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
4203 DestIsVolatile = false;
4204 }
John McCall7f416cc2015-09-08 08:05:57 +00004205 BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
Hal Finkelee90a222014-09-26 05:04:30 +00004206 return RValue::getAggregate(DestPtr);
4207 }
4208 case TEK_Scalar: {
4209 // If the argument doesn't match, perform a bitcast to coerce it. This
4210 // can happen due to trivial type mismatches.
4211 llvm::Value *V = CI;
4212 if (V->getType() != RetIRTy)
4213 V = Builder.CreateBitCast(V, RetIRTy);
4214 return RValue::get(V);
4215 }
4216 }
4217 llvm_unreachable("bad evaluation kind");
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004218 }
Hal Finkelee90a222014-09-26 05:04:30 +00004219
John McCall7f416cc2015-09-08 08:05:57 +00004220 Address DestPtr = ReturnValue.getValue();
Hal Finkelee90a222014-09-26 05:04:30 +00004221 bool DestIsVolatile = ReturnValue.isVolatile();
4222
John McCall7f416cc2015-09-08 08:05:57 +00004223 if (!DestPtr.isValid()) {
Hal Finkelee90a222014-09-26 05:04:30 +00004224 DestPtr = CreateMemTemp(RetTy, "coerce");
4225 DestIsVolatile = false;
John McCall47fb9502013-03-07 21:37:08 +00004226 }
Hal Finkelee90a222014-09-26 05:04:30 +00004227
4228 // If the value is offset in memory, apply the offset now.
John McCall7f416cc2015-09-08 08:05:57 +00004229 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
4230 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Hal Finkelee90a222014-09-26 05:04:30 +00004231
4232 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004233 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004234
Hal Finkelee90a222014-09-26 05:04:30 +00004235 case ABIArgInfo::Expand:
4236 llvm_unreachable("Invalid ABI kind for return argument");
Anders Carlsson17490832009-12-24 20:40:36 +00004237 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004238
Hal Finkelee90a222014-09-26 05:04:30 +00004239 llvm_unreachable("Unhandled ABIArgInfo::Kind");
4240 } ();
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00004241
John McCallb92ab1a2016-10-26 23:46:34 +00004242 // Emit the assume_aligned check on the return value.
4243 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl();
Hal Finkelee90a222014-09-26 05:04:30 +00004244 if (Ret.isScalar() && TargetDecl) {
4245 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
4246 llvm::Value *OffsetValue = nullptr;
4247 if (const auto *Offset = AA->getOffset())
4248 OffsetValue = EmitScalarExpr(Offset);
4249
4250 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
4251 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
4252 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
4253 OffsetValue);
4254 }
Daniel Dunbar573884e2008-09-10 07:04:09 +00004255 }
Daniel Dunbard3674e62008-09-11 01:48:57 +00004256
Hal Finkelee90a222014-09-26 05:04:30 +00004257 return Ret;
Daniel Dunbar613855c2008-09-09 23:27:19 +00004258}
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004259
4260/* VarArg handling */
4261
Charles Davisc7d5c942015-09-17 20:55:33 +00004262Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
4263 VAListAddr = VE->isMicrosoftABI()
4264 ? EmitMSVAListRef(VE->getSubExpr())
4265 : EmitVAListRef(VE->getSubExpr());
4266 QualType Ty = VE->getType();
4267 if (VE->isMicrosoftABI())
4268 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004269 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
Daniel Dunbar2d0746f2009-02-10 20:44:09 +00004270}