blob: ed02c74cdfca25fb0b0d75c44bcb613203349e72 [file] [log] [blame]
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001//===--- CGCall.cpp - Encapsulate calling convention details ----*- C++ -*-===//
Daniel Dunbar0dbe2272008-09-08 21:33:45 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
Chris Lattnerce933992010-06-29 16:40:28 +000016#include "ABIInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCXXABI.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
John McCallde5d3c72012-02-17 03:33:10 +000020#include "TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000021#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +000026#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000027#include "llvm/IR/Attributes.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/InlineAsm.h"
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +000030#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/Support/CallSite.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000032#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000033using namespace clang;
34using namespace CodeGen;
35
36/***/
37
John McCall04a67a62010-02-05 21:31:56 +000038static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
39 switch (CC) {
40 default: return llvm::CallingConv::C;
41 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
42 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregorf813a2c2010-05-18 16:57:00 +000043 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Anton Korobeynikov414d8962011-04-14 20:06:49 +000044 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
45 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Guy Benyei38980082012-12-25 08:53:55 +000046 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
Dawn Perchik52fc3142010-09-03 01:29:35 +000047 // TODO: add support for CC_X86Pascal to llvm
John McCall04a67a62010-02-05 21:31:56 +000048 }
49}
50
John McCall0b0ef0a2010-02-24 07:14:12 +000051/// Derives the 'this' type for codegen purposes, i.e. ignoring method
52/// qualification.
53/// FIXME: address space qualification?
John McCallead608a2010-02-26 00:48:12 +000054static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
55 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
56 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000057}
58
John McCall0b0ef0a2010-02-24 07:14:12 +000059/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000060static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
61 return MD->getType()->getCanonicalTypeUnqualified()
62 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-02-24 07:14:12 +000063}
64
65/// Returns the "extra-canonicalized" return type, which discards
66/// qualifiers on the return type. Codegen doesn't care about them,
67/// and it makes ABI code a little easier to be able to assume that
68/// all parameter and return types are top-level unqualified.
John McCallead608a2010-02-26 00:48:12 +000069static CanQualType GetReturnType(QualType RetTy) {
70 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000071}
72
John McCall0f3d0972012-07-07 06:41:13 +000073/// Arrange the argument and result information for a value of the given
74/// unprototyped freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +000075const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +000076CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
John McCallde5d3c72012-02-17 03:33:10 +000077 // When translating an unprototyped function type, always use a
78 // variadic type.
John McCall0f3d0972012-07-07 06:41:13 +000079 return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
Dmitri Gribenko55431692013-05-05 00:41:58 +000080 None, FTNP->getExtInfo(), RequiredArgs(0));
John McCall0b0ef0a2010-02-24 07:14:12 +000081}
82
John McCall0f3d0972012-07-07 06:41:13 +000083/// Arrange the LLVM function layout for a value of the given function
84/// type, on top of any implicit parameters already stored. Use the
85/// given ExtInfo instead of the ExtInfo from the function type.
86static const CGFunctionInfo &arrangeLLVMFunctionInfo(CodeGenTypes &CGT,
87 SmallVectorImpl<CanQualType> &prefix,
88 CanQual<FunctionProtoType> FTP,
89 FunctionType::ExtInfo extInfo) {
90 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
Daniel Dunbar541b63b2009-02-02 23:23:47 +000091 // FIXME: Kill copy.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000092 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCall0f3d0972012-07-07 06:41:13 +000093 prefix.push_back(FTP->getArgType(i));
John McCallde5d3c72012-02-17 03:33:10 +000094 CanQualType resultType = FTP->getResultType().getUnqualifiedType();
John McCall0f3d0972012-07-07 06:41:13 +000095 return CGT.arrangeLLVMFunctionInfo(resultType, prefix, extInfo, required);
96}
97
98/// Arrange the argument and result information for a free function (i.e.
99/// not a C++ or ObjC instance method) of the given type.
100static const CGFunctionInfo &arrangeFreeFunctionType(CodeGenTypes &CGT,
101 SmallVectorImpl<CanQualType> &prefix,
102 CanQual<FunctionProtoType> FTP) {
103 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, FTP->getExtInfo());
104}
105
John McCall0f3d0972012-07-07 06:41:13 +0000106/// Arrange the argument and result information for a free function (i.e.
107/// not a C++ or ObjC instance method) of the given type.
108static const CGFunctionInfo &arrangeCXXMethodType(CodeGenTypes &CGT,
109 SmallVectorImpl<CanQualType> &prefix,
110 CanQual<FunctionProtoType> FTP) {
111 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall0f3d0972012-07-07 06:41:13 +0000112 return arrangeLLVMFunctionInfo(CGT, prefix, FTP, extInfo);
John McCall0b0ef0a2010-02-24 07:14:12 +0000113}
114
John McCallde5d3c72012-02-17 03:33:10 +0000115/// Arrange the argument and result information for a value of the
John McCall0f3d0972012-07-07 06:41:13 +0000116/// given freestanding function type.
John McCall0b0ef0a2010-02-24 07:14:12 +0000117const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000118CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
John McCallde5d3c72012-02-17 03:33:10 +0000119 SmallVector<CanQualType, 16> argTypes;
John McCall0f3d0972012-07-07 06:41:13 +0000120 return ::arrangeFreeFunctionType(*this, argTypes, FTP);
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000121}
122
John McCall04a67a62010-02-05 21:31:56 +0000123static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000124 // Set the appropriate calling convention for the Function.
125 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000126 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000127
128 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000129 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000130
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000131 if (D->hasAttr<ThisCallAttr>())
132 return CC_X86ThisCall;
133
Dawn Perchik52fc3142010-09-03 01:29:35 +0000134 if (D->hasAttr<PascalAttr>())
135 return CC_X86Pascal;
136
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000137 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
138 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
139
Derek Schuff263366f2012-10-16 22:30:41 +0000140 if (D->hasAttr<PnaclCallAttr>())
141 return CC_PnaclCall;
142
Guy Benyei38980082012-12-25 08:53:55 +0000143 if (D->hasAttr<IntelOclBiccAttr>())
144 return CC_IntelOclBicc;
145
John McCall04a67a62010-02-05 21:31:56 +0000146 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000147}
148
John McCallde5d3c72012-02-17 03:33:10 +0000149/// Arrange the argument and result information for a call to an
150/// unknown C++ non-static member function of the given abstract type.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000151/// (Zero value of RD means we don't have any meaningful "this" argument type,
152/// so fall back to a generic pointer type).
John McCallde5d3c72012-02-17 03:33:10 +0000153/// The member function must be an ordinary function, i.e. not a
154/// constructor or destructor.
155const CGFunctionInfo &
156CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
157 const FunctionProtoType *FTP) {
158 SmallVector<CanQualType, 16> argTypes;
John McCall0b0ef0a2010-02-24 07:14:12 +0000159
Anders Carlsson375c31c2009-10-03 19:43:08 +0000160 // Add the 'this' pointer.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000161 if (RD)
162 argTypes.push_back(GetThisType(Context, RD));
163 else
164 argTypes.push_back(Context.VoidPtrTy);
John McCall0b0ef0a2010-02-24 07:14:12 +0000165
John McCall0f3d0972012-07-07 06:41:13 +0000166 return ::arrangeCXXMethodType(*this, argTypes,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000167 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000168}
169
John McCallde5d3c72012-02-17 03:33:10 +0000170/// Arrange the argument and result information for a declaration or
171/// definition of the given C++ non-static member function. The
172/// member function must be an ordinary function, i.e. not a
173/// constructor or destructor.
174const CGFunctionInfo &
175CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
John McCallfc400282010-09-03 01:26:39 +0000176 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
177 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
178
John McCallde5d3c72012-02-17 03:33:10 +0000179 CanQual<FunctionProtoType> prototype = GetFormalType(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
John McCallde5d3c72012-02-17 03:33:10 +0000181 if (MD->isInstance()) {
182 // The abstract case is perfectly fine.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000183 const CXXRecordDecl *ThisType =
184 CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
185 return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
John McCallde5d3c72012-02-17 03:33:10 +0000186 }
187
John McCall0f3d0972012-07-07 06:41:13 +0000188 return arrangeFreeFunctionType(prototype);
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000189}
190
John McCallde5d3c72012-02-17 03:33:10 +0000191/// Arrange the argument and result information for a declaration
192/// or definition to the given constructor variant.
193const CGFunctionInfo &
194CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
195 CXXCtorType ctorKind) {
196 SmallVector<CanQualType, 16> argTypes;
197 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000198
199 GlobalDecl GD(D, ctorKind);
200 CanQualType resultType =
201 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000202
John McCallde5d3c72012-02-17 03:33:10 +0000203 TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
John McCall0b0ef0a2010-02-24 07:14:12 +0000204
John McCall4c40d982010-08-31 07:33:07 +0000205 CanQual<FunctionProtoType> FTP = GetFormalType(D);
206
John McCallde5d3c72012-02-17 03:33:10 +0000207 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, argTypes.size());
208
John McCall4c40d982010-08-31 07:33:07 +0000209 // Add the formal parameters.
210 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000211 argTypes.push_back(FTP->getArgType(i));
John McCall4c40d982010-08-31 07:33:07 +0000212
John McCall0f3d0972012-07-07 06:41:13 +0000213 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall0f3d0972012-07-07 06:41:13 +0000214 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo, required);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000215}
216
John McCallde5d3c72012-02-17 03:33:10 +0000217/// Arrange the argument and result information for a declaration,
218/// definition, or call to the given destructor variant. It so
219/// happens that all three cases produce the same information.
220const CGFunctionInfo &
221CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
222 CXXDtorType dtorKind) {
223 SmallVector<CanQualType, 2> argTypes;
224 argTypes.push_back(GetThisType(Context, D->getParent()));
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000225
226 GlobalDecl GD(D, dtorKind);
227 CanQualType resultType =
228 TheCXXABI.HasThisReturn(GD) ? argTypes.front() : Context.VoidTy;
John McCall0b0ef0a2010-02-24 07:14:12 +0000229
John McCallde5d3c72012-02-17 03:33:10 +0000230 TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
John McCall4c40d982010-08-31 07:33:07 +0000231
232 CanQual<FunctionProtoType> FTP = GetFormalType(D);
233 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +0000234 assert(FTP->isVariadic() == 0 && "dtor with formal parameters");
John McCall4c40d982010-08-31 07:33:07 +0000235
John McCall0f3d0972012-07-07 06:41:13 +0000236 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
John McCall0f3d0972012-07-07 06:41:13 +0000237 return arrangeLLVMFunctionInfo(resultType, argTypes, extInfo,
238 RequiredArgs::All);
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000239}
240
John McCallde5d3c72012-02-17 03:33:10 +0000241/// Arrange the argument and result information for the declaration or
242/// definition of the given function.
243const CGFunctionInfo &
244CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
Chris Lattner3eb67ca2009-05-12 20:27:19 +0000245 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000246 if (MD->isInstance())
John McCallde5d3c72012-02-17 03:33:10 +0000247 return arrangeCXXMethodDeclaration(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000248
John McCallead608a2010-02-26 00:48:12 +0000249 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
John McCallde5d3c72012-02-17 03:33:10 +0000250
John McCallead608a2010-02-26 00:48:12 +0000251 assert(isa<FunctionType>(FTy));
John McCallde5d3c72012-02-17 03:33:10 +0000252
253 // When declaring a function without a prototype, always use a
254 // non-variadic type.
255 if (isa<FunctionNoProtoType>(FTy)) {
256 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
Dmitri Gribenko55431692013-05-05 00:41:58 +0000257 return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
258 noProto->getExtInfo(), RequiredArgs::All);
John McCallde5d3c72012-02-17 03:33:10 +0000259 }
260
John McCallead608a2010-02-26 00:48:12 +0000261 assert(isa<FunctionProtoType>(FTy));
John McCall0f3d0972012-07-07 06:41:13 +0000262 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000263}
264
John McCallde5d3c72012-02-17 03:33:10 +0000265/// Arrange the argument and result information for the declaration or
266/// definition of an Objective-C method.
267const CGFunctionInfo &
268CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
269 // It happens that this is the same as a call with no optional
270 // arguments, except also using the formal 'self' type.
271 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
272}
273
274/// Arrange the argument and result information for the function type
275/// through which to perform a send to the given Objective-C method,
276/// using the given receiver type. The receiver type is not always
277/// the 'self' type of the method or even an Objective-C pointer type.
278/// This is *not* the right method for actually performing such a
279/// message send, due to the possibility of optional arguments.
280const CGFunctionInfo &
281CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
282 QualType receiverType) {
283 SmallVector<CanQualType, 16> argTys;
284 argTys.push_back(Context.getCanonicalParamType(receiverType));
285 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000286 // FIXME: Kill copy?
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000287 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
John McCall0b0ef0a2010-02-24 07:14:12 +0000288 e = MD->param_end(); i != e; ++i) {
John McCallde5d3c72012-02-17 03:33:10 +0000289 argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
John McCall0b0ef0a2010-02-24 07:14:12 +0000290 }
John McCallf85e1932011-06-15 23:02:42 +0000291
292 FunctionType::ExtInfo einfo;
293 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
294
David Blaikie4e4d0842012-03-11 07:00:24 +0000295 if (getContext().getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000296 MD->hasAttr<NSReturnsRetainedAttr>())
297 einfo = einfo.withProducesResult(true);
298
John McCallde5d3c72012-02-17 03:33:10 +0000299 RequiredArgs required =
300 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
301
John McCall0f3d0972012-07-07 06:41:13 +0000302 return arrangeLLVMFunctionInfo(GetReturnType(MD->getResultType()), argTys,
303 einfo, required);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000304}
305
John McCallde5d3c72012-02-17 03:33:10 +0000306const CGFunctionInfo &
307CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000308 // FIXME: Do we need to handle ObjCMethodDecl?
309 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000310
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000311 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000312 return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000313
314 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
John McCallde5d3c72012-02-17 03:33:10 +0000315 return arrangeCXXDestructor(DD, GD.getDtorType());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000316
John McCallde5d3c72012-02-17 03:33:10 +0000317 return arrangeFunctionDeclaration(FD);
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000318}
319
John McCalle56bb362012-12-07 07:03:17 +0000320/// Arrange a call as unto a free function, except possibly with an
321/// additional number of formal parameters considered required.
322static const CGFunctionInfo &
323arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
324 const CallArgList &args,
325 const FunctionType *fnType,
326 unsigned numExtraRequiredArgs) {
327 assert(args.size() >= numExtraRequiredArgs);
328
329 // In most cases, there are no optional arguments.
330 RequiredArgs required = RequiredArgs::All;
331
332 // If we have a variadic prototype, the required arguments are the
333 // extra prefix plus the arguments in the prototype.
334 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
335 if (proto->isVariadic())
336 required = RequiredArgs(proto->getNumArgs() + numExtraRequiredArgs);
337
338 // If we don't have a prototype at all, but we're supposed to
339 // explicitly use the variadic convention for unprototyped calls,
340 // treat all of the arguments as required but preserve the nominal
341 // possibility of variadics.
342 } else if (CGT.CGM.getTargetCodeGenInfo()
343 .isNoProtoCallVariadic(args, cast<FunctionNoProtoType>(fnType))) {
344 required = RequiredArgs(args.size());
345 }
346
347 return CGT.arrangeFreeFunctionCall(fnType->getResultType(), args,
348 fnType->getExtInfo(), required);
349}
350
John McCallde5d3c72012-02-17 03:33:10 +0000351/// Figure out the rules for calling a function with the given formal
352/// type using the given arguments. The arguments are necessary
353/// because the function might be unprototyped, in which case it's
354/// target-dependent in crazy ways.
355const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000356CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
357 const FunctionType *fnType) {
John McCalle56bb362012-12-07 07:03:17 +0000358 return arrangeFreeFunctionLikeCall(*this, args, fnType, 0);
359}
John McCallde5d3c72012-02-17 03:33:10 +0000360
John McCalle56bb362012-12-07 07:03:17 +0000361/// A block function call is essentially a free-function call with an
362/// extra implicit argument.
363const CGFunctionInfo &
364CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
365 const FunctionType *fnType) {
366 return arrangeFreeFunctionLikeCall(*this, args, fnType, 1);
John McCallde5d3c72012-02-17 03:33:10 +0000367}
368
369const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000370CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
371 const CallArgList &args,
372 FunctionType::ExtInfo info,
373 RequiredArgs required) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000374 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000375 SmallVector<CanQualType, 16> argTypes;
376 for (CallArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbar725ad312009-01-31 02:19:00 +0000377 i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000378 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
John McCall0f3d0972012-07-07 06:41:13 +0000379 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
380 required);
381}
382
383/// Arrange a call to a C++ method, passing the given arguments.
384const CGFunctionInfo &
385CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
386 const FunctionProtoType *FPT,
387 RequiredArgs required) {
388 // FIXME: Kill copy.
389 SmallVector<CanQualType, 16> argTypes;
390 for (CallArgList::const_iterator i = args.begin(), e = args.end();
391 i != e; ++i)
392 argTypes.push_back(Context.getCanonicalParamType(i->Ty));
393
394 FunctionType::ExtInfo info = FPT->getExtInfo();
John McCall0f3d0972012-07-07 06:41:13 +0000395 return arrangeLLVMFunctionInfo(GetReturnType(FPT->getResultType()),
396 argTypes, info, required);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000397}
398
John McCallde5d3c72012-02-17 03:33:10 +0000399const CGFunctionInfo &
400CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
401 const FunctionArgList &args,
402 const FunctionType::ExtInfo &info,
403 bool isVariadic) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000404 // FIXME: Kill copy.
John McCallde5d3c72012-02-17 03:33:10 +0000405 SmallVector<CanQualType, 16> argTypes;
406 for (FunctionArgList::const_iterator i = args.begin(), e = args.end();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000407 i != e; ++i)
John McCallde5d3c72012-02-17 03:33:10 +0000408 argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
409
410 RequiredArgs required =
411 (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
John McCall0f3d0972012-07-07 06:41:13 +0000412 return arrangeLLVMFunctionInfo(GetReturnType(resultType), argTypes, info,
413 required);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000414}
415
John McCallde5d3c72012-02-17 03:33:10 +0000416const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
Dmitri Gribenko55431692013-05-05 00:41:58 +0000417 return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
John McCall0f3d0972012-07-07 06:41:13 +0000418 FunctionType::ExtInfo(), RequiredArgs::All);
John McCalld26bc762011-03-09 04:27:21 +0000419}
420
John McCallde5d3c72012-02-17 03:33:10 +0000421/// Arrange the argument and result information for an abstract value
422/// of a given function type. This is the method which all of the
423/// above functions ultimately defer to.
424const CGFunctionInfo &
John McCall0f3d0972012-07-07 06:41:13 +0000425CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
426 ArrayRef<CanQualType> argTypes,
427 FunctionType::ExtInfo info,
428 RequiredArgs required) {
John McCallead608a2010-02-26 00:48:12 +0000429#ifndef NDEBUG
John McCallde5d3c72012-02-17 03:33:10 +0000430 for (ArrayRef<CanQualType>::const_iterator
431 I = argTypes.begin(), E = argTypes.end(); I != E; ++I)
John McCallead608a2010-02-26 00:48:12 +0000432 assert(I->isCanonicalAsParam());
433#endif
434
John McCallde5d3c72012-02-17 03:33:10 +0000435 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000436
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000437 // Lookup or create unique function info.
438 llvm::FoldingSetNodeID ID;
John McCallde5d3c72012-02-17 03:33:10 +0000439 CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000440
John McCallde5d3c72012-02-17 03:33:10 +0000441 void *insertPos = 0;
442 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000443 if (FI)
444 return *FI;
445
John McCallde5d3c72012-02-17 03:33:10 +0000446 // Construct the function info. We co-allocate the ArgInfos.
447 FI = CGFunctionInfo::create(CC, info, resultType, argTypes, required);
448 FunctionInfos.InsertNode(FI, insertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000449
John McCallde5d3c72012-02-17 03:33:10 +0000450 bool inserted = FunctionsBeingProcessed.insert(FI); (void)inserted;
451 assert(inserted && "Recursively being processed?");
Chris Lattner71305cc2011-07-15 05:16:14 +0000452
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000453 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000454 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000455
Chris Lattner800588f2010-07-29 06:26:06 +0000456 // Loop over all of the computed argument and return value info. If any of
457 // them are direct or extend without a specified coerce type, specify the
458 // default now.
John McCallde5d3c72012-02-17 03:33:10 +0000459 ABIArgInfo &retInfo = FI->getReturnInfo();
460 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == 0)
461 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000462
Chris Lattner800588f2010-07-29 06:26:06 +0000463 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
464 I != E; ++I)
465 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000466 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000467
John McCallde5d3c72012-02-17 03:33:10 +0000468 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
469 assert(erased && "Not in set?");
Chris Lattnerd26c0712011-07-15 06:41:05 +0000470
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000471 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000472}
473
John McCallde5d3c72012-02-17 03:33:10 +0000474CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
475 const FunctionType::ExtInfo &info,
476 CanQualType resultType,
477 ArrayRef<CanQualType> argTypes,
478 RequiredArgs required) {
479 void *buffer = operator new(sizeof(CGFunctionInfo) +
480 sizeof(ArgInfo) * (argTypes.size() + 1));
481 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
482 FI->CallingConvention = llvmCC;
483 FI->EffectiveCallingConvention = llvmCC;
484 FI->ASTCallingConvention = info.getCC();
485 FI->NoReturn = info.getNoReturn();
486 FI->ReturnsRetained = info.getProducesResult();
487 FI->Required = required;
488 FI->HasRegParm = info.getHasRegParm();
489 FI->RegParm = info.getRegParm();
490 FI->NumArgs = argTypes.size();
491 FI->getArgsBuffer()[0].type = resultType;
492 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
493 FI->getArgsBuffer()[i + 1].type = argTypes[i];
494 return FI;
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000495}
496
497/***/
498
John McCall42e06112011-05-15 02:19:42 +0000499void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000500 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000501 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
502 uint64_t NumElts = AT->getSize().getZExtValue();
503 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
504 GetExpandedTypes(AT->getElementType(), expandedTypes);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000505 } else if (const RecordType *RT = type->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000506 const RecordDecl *RD = RT->getDecl();
507 assert(!RD->hasFlexibleArrayMember() &&
508 "Cannot expand structure with flexible array.");
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000509 if (RD->isUnion()) {
510 // Unions can be here only in degenerative cases - all the fields are same
511 // after flattening. Thus we have to use the "largest" field.
512 const FieldDecl *LargestFD = 0;
513 CharUnits UnionSize = CharUnits::Zero();
514
515 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
516 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000517 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000518 assert(!FD->isBitField() &&
519 "Cannot expand structure with bit-field members.");
520 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
521 if (UnionSize < FieldSize) {
522 UnionSize = FieldSize;
523 LargestFD = FD;
524 }
525 }
526 if (LargestFD)
527 GetExpandedTypes(LargestFD->getType(), expandedTypes);
528 } else {
529 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
530 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000531 assert(!i->isBitField() &&
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000532 "Cannot expand structure with bit-field members.");
David Blaikie581deb32012-06-06 20:45:41 +0000533 GetExpandedTypes(i->getType(), expandedTypes);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000534 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000535 }
536 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
537 llvm::Type *EltTy = ConvertType(CT->getElementType());
538 expandedTypes.push_back(EltTy);
539 expandedTypes.push_back(EltTy);
540 } else
541 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar56273772008-09-17 00:51:38 +0000542}
543
Mike Stump1eb44332009-09-09 15:08:12 +0000544llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000545CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
546 llvm::Function::arg_iterator AI) {
Mike Stump1eb44332009-09-09 15:08:12 +0000547 assert(LV.isSimple() &&
548 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000549
Bob Wilson194f06a2011-08-03 05:58:22 +0000550 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
551 unsigned NumElts = AT->getSize().getZExtValue();
552 QualType EltTy = AT->getElementType();
553 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
Eli Friedman377ecc72012-04-16 03:54:45 +0000554 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(LV.getAddress(), 0, Elt);
Bob Wilson194f06a2011-08-03 05:58:22 +0000555 LValue LV = MakeAddrLValue(EltAddr, EltTy);
556 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar56273772008-09-17 00:51:38 +0000557 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000558 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000559 RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000560 if (RD->isUnion()) {
561 // Unions can be here only in degenerative cases - all the fields are same
562 // after flattening. Thus we have to use the "largest" field.
563 const FieldDecl *LargestFD = 0;
564 CharUnits UnionSize = CharUnits::Zero();
Bob Wilson194f06a2011-08-03 05:58:22 +0000565
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000566 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
567 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000568 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000569 assert(!FD->isBitField() &&
570 "Cannot expand structure with bit-field members.");
571 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
572 if (UnionSize < FieldSize) {
573 UnionSize = FieldSize;
574 LargestFD = FD;
575 }
576 }
577 if (LargestFD) {
578 // FIXME: What are the right qualifiers here?
Eli Friedman377ecc72012-04-16 03:54:45 +0000579 LValue SubLV = EmitLValueForField(LV, LargestFD);
580 AI = ExpandTypeFromArgs(LargestFD->getType(), SubLV, AI);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000581 }
582 } else {
583 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
584 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000585 FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000586 QualType FT = FD->getType();
587
588 // FIXME: What are the right qualifiers here?
Eli Friedman377ecc72012-04-16 03:54:45 +0000589 LValue SubLV = EmitLValueForField(LV, FD);
590 AI = ExpandTypeFromArgs(FT, SubLV, AI);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +0000591 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000592 }
593 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
594 QualType EltTy = CT->getElementType();
Eli Friedman377ecc72012-04-16 03:54:45 +0000595 llvm::Value *RealAddr = Builder.CreateStructGEP(LV.getAddress(), 0, "real");
Bob Wilson194f06a2011-08-03 05:58:22 +0000596 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Eli Friedman377ecc72012-04-16 03:54:45 +0000597 llvm::Value *ImagAddr = Builder.CreateStructGEP(LV.getAddress(), 1, "imag");
Bob Wilson194f06a2011-08-03 05:58:22 +0000598 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
599 } else {
600 EmitStoreThroughLValue(RValue::get(AI), LV);
601 ++AI;
Daniel Dunbar56273772008-09-17 00:51:38 +0000602 }
603
604 return AI;
605}
606
Chris Lattnere7bb7772010-06-27 06:04:18 +0000607/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-06-27 05:56:15 +0000608/// accessing some number of bytes out of it, try to gep into the struct to get
609/// at its inner goodness. Dive as deep as possible without entering an element
610/// with an in-memory size smaller than DstSize.
611static llvm::Value *
Chris Lattnere7bb7772010-06-27 06:04:18 +0000612EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000613 llvm::StructType *SrcSTy,
Chris Lattnere7bb7772010-06-27 06:04:18 +0000614 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000615 // We can't dive into a zero-element struct.
616 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000617
Chris Lattner2acc6e32011-07-18 04:24:23 +0000618 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000619
Chris Lattner08dd2a02010-06-27 05:56:15 +0000620 // If the first elt is at least as large as what we're looking for, or if the
621 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000622 uint64_t FirstEltSize =
Micah Villmow25a6a842012-10-08 16:25:52 +0000623 CGF.CGM.getDataLayout().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000624 if (FirstEltSize < DstSize &&
Micah Villmow25a6a842012-10-08 16:25:52 +0000625 FirstEltSize < CGF.CGM.getDataLayout().getTypeAllocSize(SrcSTy))
Chris Lattner08dd2a02010-06-27 05:56:15 +0000626 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000627
Chris Lattner08dd2a02010-06-27 05:56:15 +0000628 // GEP into the first element.
629 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000630
Chris Lattner08dd2a02010-06-27 05:56:15 +0000631 // If the first element is a struct, recurse.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000632 llvm::Type *SrcTy =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000633 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000634 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000635 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000636
637 return SrcPtr;
638}
639
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000640/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
641/// are either integers or pointers. This does a truncation of the value if it
642/// is too large or a zero extension if it is too small.
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000643///
644/// This behaves as if the value were coerced through memory, so on big-endian
645/// targets the high bits are preserved in a truncation, while little-endian
646/// targets preserve the low bits.
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000647static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000648 llvm::Type *Ty,
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000649 CodeGenFunction &CGF) {
650 if (Val->getType() == Ty)
651 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000652
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000653 if (isa<llvm::PointerType>(Val->getType())) {
654 // If this is Pointer->Pointer avoid conversion to and from int.
655 if (isa<llvm::PointerType>(Ty))
656 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000657
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000658 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000659 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000660 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000661
Chris Lattner2acc6e32011-07-18 04:24:23 +0000662 llvm::Type *DestIntTy = Ty;
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000663 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000664 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000665
Jakob Stoklund Olesen7e9f52f2013-06-05 03:00:13 +0000666 if (Val->getType() != DestIntTy) {
667 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
668 if (DL.isBigEndian()) {
669 // Preserve the high bits on big-endian targets.
670 // That is what memory coercion does.
671 uint64_t SrcSize = DL.getTypeAllocSizeInBits(Val->getType());
672 uint64_t DstSize = DL.getTypeAllocSizeInBits(DestIntTy);
673 if (SrcSize > DstSize) {
674 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
675 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
676 } else {
677 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
678 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
679 }
680 } else {
681 // Little-endian targets preserve the low bits. No shifts required.
682 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
683 }
684 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000685
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000686 if (isa<llvm::PointerType>(Ty))
687 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
688 return Val;
689}
690
Chris Lattner08dd2a02010-06-27 05:56:15 +0000691
692
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000693/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
694/// a pointer to an object of type \arg Ty.
695///
696/// This safely handles the case when the src type is smaller than the
697/// destination type; in this situation the values of bits which not
698/// present in the src are undefined.
699static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000700 llvm::Type *Ty,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000701 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000702 llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000703 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000704
Chris Lattner6ae00692010-06-28 22:51:39 +0000705 // If SrcTy and Ty are the same, just do a load.
706 if (SrcTy == Ty)
707 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000708
Micah Villmow25a6a842012-10-08 16:25:52 +0000709 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000710
Chris Lattner2acc6e32011-07-18 04:24:23 +0000711 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000712 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000713 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
714 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000715
Micah Villmow25a6a842012-10-08 16:25:52 +0000716 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000717
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000718 // If the source and destination are integer or pointer types, just do an
719 // extension or truncation to the desired type.
720 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
721 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
722 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
723 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
724 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000725
Daniel Dunbarb225be42009-02-03 05:59:18 +0000726 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000727 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000728 // Generally SrcSize is never greater than DstSize, since this means we are
729 // losing bits. However, this can happen in cases where the structure has
730 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000731 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000732 // FIXME: Assert that we aren't truncating non-padding bits when have access
733 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000734 llvm::Value *Casted =
735 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000736 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
737 // FIXME: Use better alignment / avoid requiring aligned load.
738 Load->setAlignment(1);
739 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000740 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000741
Chris Lattner35b21b82010-06-27 01:06:27 +0000742 // Otherwise do coercion through memory. This is stupid, but
743 // simple.
744 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
Manman Renf51c61c2012-11-28 22:08:52 +0000745 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
746 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
747 llvm::Value *SrcCasted = CGF.Builder.CreateBitCast(SrcPtr, I8PtrTy);
Manman Ren060f34d2012-11-28 22:29:41 +0000748 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000749 CGF.Builder.CreateMemCpy(Casted, SrcCasted,
750 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
751 1, false);
Chris Lattner35b21b82010-06-27 01:06:27 +0000752 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000753}
754
Eli Friedmanbadea572011-05-17 21:08:01 +0000755// Function to store a first-class aggregate into memory. We prefer to
756// store the elements rather than the aggregate to be more friendly to
757// fast-isel.
758// FIXME: Do we need to recurse here?
759static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
760 llvm::Value *DestPtr, bool DestIsVolatile,
761 bool LowAlignment) {
762 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000763 if (llvm::StructType *STy =
Eli Friedmanbadea572011-05-17 21:08:01 +0000764 dyn_cast<llvm::StructType>(Val->getType())) {
765 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
766 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
767 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
768 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
769 DestIsVolatile);
770 if (LowAlignment)
771 SI->setAlignment(1);
772 }
773 } else {
Bill Wendling08212632012-03-16 21:45:12 +0000774 llvm::StoreInst *SI = CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
775 if (LowAlignment)
776 SI->setAlignment(1);
Eli Friedmanbadea572011-05-17 21:08:01 +0000777 }
778}
779
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000780/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
781/// where the source and destination may have different types.
782///
783/// This safely handles the case when the src type is larger than the
784/// destination type; the upper bits of the src will be lost.
785static void CreateCoercedStore(llvm::Value *Src,
786 llvm::Value *DstPtr,
Anders Carlssond2490a92009-12-24 20:40:36 +0000787 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000788 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000789 llvm::Type *SrcTy = Src->getType();
790 llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000791 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000792 if (SrcTy == DstTy) {
793 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
794 return;
795 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000796
Micah Villmow25a6a842012-10-08 16:25:52 +0000797 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000798
Chris Lattner2acc6e32011-07-18 04:24:23 +0000799 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000800 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
801 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
802 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000803
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000804 // If the source and destination are integer or pointer types, just do an
805 // extension or truncation to the desired type.
806 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
807 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
808 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
809 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
810 return;
811 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000812
Micah Villmow25a6a842012-10-08 16:25:52 +0000813 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000814
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000815 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000816 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000817 llvm::Value *Casted =
818 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000819 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000820 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000821 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000822 // Otherwise do coercion through memory. This is stupid, but
823 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000824
825 // Generally SrcSize is never greater than DstSize, since this means we are
826 // losing bits. However, this can happen in cases where the structure has
827 // additional padding, for example due to a user specified alignment.
828 //
829 // FIXME: Assert that we aren't truncating non-padding bits when have access
830 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000831 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
832 CGF.Builder.CreateStore(Src, Tmp);
Manman Renf51c61c2012-11-28 22:08:52 +0000833 llvm::Type *I8PtrTy = CGF.Builder.getInt8PtrTy();
834 llvm::Value *Casted = CGF.Builder.CreateBitCast(Tmp, I8PtrTy);
835 llvm::Value *DstCasted = CGF.Builder.CreateBitCast(DstPtr, I8PtrTy);
Manman Ren060f34d2012-11-28 22:29:41 +0000836 // FIXME: Use better alignment.
Manman Renf51c61c2012-11-28 22:08:52 +0000837 CGF.Builder.CreateMemCpy(DstCasted, Casted,
838 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
839 1, false);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000840 }
841}
842
Daniel Dunbar56273772008-09-17 00:51:38 +0000843/***/
844
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000845bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000846 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000847}
848
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000849bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
850 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
851 switch (BT->getKind()) {
852 default:
853 return false;
854 case BuiltinType::Float:
John McCall64aa4b32013-04-16 22:48:15 +0000855 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000856 case BuiltinType::Double:
John McCall64aa4b32013-04-16 22:48:15 +0000857 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000858 case BuiltinType::LongDouble:
John McCall64aa4b32013-04-16 22:48:15 +0000859 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000860 }
861 }
862
863 return false;
864}
865
Anders Carlssoneea64802011-10-31 16:27:11 +0000866bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
867 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
868 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
869 if (BT->getKind() == BuiltinType::LongDouble)
John McCall64aa4b32013-04-16 22:48:15 +0000870 return getTarget().useObjCFP2RetForComplexLongDouble();
Anders Carlssoneea64802011-10-31 16:27:11 +0000871 }
872 }
873
874 return false;
875}
876
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000877llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallde5d3c72012-02-17 03:33:10 +0000878 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
879 return GetFunctionType(FI);
John McCallc0bf4622010-02-23 00:48:20 +0000880}
881
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000882llvm::FunctionType *
John McCallde5d3c72012-02-17 03:33:10 +0000883CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
Chris Lattner71305cc2011-07-15 05:16:14 +0000884
885 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
886 assert(Inserted && "Recursively being processed?");
887
Chris Lattner5f9e2722011-07-23 10:55:15 +0000888 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2acc6e32011-07-18 04:24:23 +0000889 llvm::Type *resultType = 0;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000890
John McCall42e06112011-05-15 02:19:42 +0000891 const ABIArgInfo &retAI = FI.getReturnInfo();
892 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000893 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000894 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000895
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000896 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000897 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000898 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000899 break;
900
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000901 case ABIArgInfo::Indirect: {
John McCall42e06112011-05-15 02:19:42 +0000902 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
903 resultType = llvm::Type::getVoidTy(getLLVMContext());
904
905 QualType ret = FI.getReturnType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000906 llvm::Type *ty = ConvertType(ret);
John McCall42e06112011-05-15 02:19:42 +0000907 unsigned addressSpace = Context.getTargetAddressSpace(ret);
908 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000909 break;
910 }
911
Daniel Dunbar11434922009-01-26 21:26:08 +0000912 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000913 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000914 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
John McCalle56bb362012-12-07 07:03:17 +0000917 // Add in all of the required arguments.
918 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), ie;
919 if (FI.isVariadic()) {
920 ie = it + FI.getRequiredArgs().getNumRequiredArgs();
921 } else {
922 ie = FI.arg_end();
923 }
924 for (; it != ie; ++it) {
John McCall42e06112011-05-15 02:19:42 +0000925 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000927 // Insert a padding type to ensure proper alignment.
928 if (llvm::Type *PaddingType = argAI.getPaddingType())
929 argTypes.push_back(PaddingType);
930
John McCall42e06112011-05-15 02:19:42 +0000931 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +0000932 case ABIArgInfo::Ignore:
933 break;
934
Chris Lattner800588f2010-07-29 06:26:06 +0000935 case ABIArgInfo::Indirect: {
936 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000937 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall42e06112011-05-15 02:19:42 +0000938 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +0000939 break;
940 }
941
942 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +0000943 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-06-28 23:44:11 +0000944 // If the coerce-to type is a first class aggregate, flatten it. Either
945 // way is semantically identical, but fast-isel and the optimizer
946 // generally likes scalar values better than FCAs.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000947 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000948 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall42e06112011-05-15 02:19:42 +0000949 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
950 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +0000951 } else {
John McCall42e06112011-05-15 02:19:42 +0000952 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +0000953 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000954 break;
Chris Lattner1ed72672010-07-29 06:44:09 +0000955 }
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000957 case ABIArgInfo::Expand:
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000958 GetExpandedTypes(it->type, argTypes);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000959 break;
960 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000961 }
962
Chris Lattner71305cc2011-07-15 05:16:14 +0000963 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
964 assert(Erased && "Not in set?");
965
John McCallde5d3c72012-02-17 03:33:10 +0000966 return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
Daniel Dunbar3913f182008-09-09 23:48:28 +0000967}
968
Chris Lattner2acc6e32011-07-18 04:24:23 +0000969llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall4c40d982010-08-31 07:33:07 +0000970 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000971 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000972
Chris Lattnerf742eb02011-07-10 00:18:59 +0000973 if (!isFuncTypeConvertible(FPT))
974 return llvm::StructType::get(getLLVMContext());
975
976 const CGFunctionInfo *Info;
977 if (isa<CXXDestructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000978 Info = &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtorType());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000979 else
John McCallde5d3c72012-02-17 03:33:10 +0000980 Info = &arrangeCXXMethodDeclaration(MD);
981 return GetFunctionType(*Info);
Anders Carlssonecf282b2009-11-24 05:08:52 +0000982}
983
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000984void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +0000985 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000986 AttributeListType &PAL,
Bill Wendling94236e72013-02-22 00:13:35 +0000987 unsigned &CallingConv,
988 bool AttrOnCallSite) {
Bill Wendling0d583392012-10-15 20:36:26 +0000989 llvm::AttrBuilder FuncAttrs;
990 llvm::AttrBuilder RetAttrs;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000991
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000992 CallingConv = FI.getEffectiveCallingConvention();
993
John McCall04a67a62010-02-05 21:31:56 +0000994 if (FI.isNoReturn())
Bill Wendling72390b32012-12-20 19:27:06 +0000995 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall04a67a62010-02-05 21:31:56 +0000996
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000997 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000998 if (TargetDecl) {
Rafael Espindola67004152011-10-12 19:51:18 +0000999 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001000 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001001 if (TargetDecl->hasAttr<NoThrowAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001002 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith7586a6e2013-01-30 05:45:05 +00001003 if (TargetDecl->hasAttr<NoReturnAttr>())
1004 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
1005
1006 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
John McCall9c0c1f32010-07-08 06:48:12 +00001007 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001008 if (FPT && FPT->isNothrow(getContext()))
Bill Wendling72390b32012-12-20 19:27:06 +00001009 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Richard Smith3c5cd152013-03-05 08:30:04 +00001010 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
1011 // These attributes are not inherited by overloads.
1012 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
1013 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
Richard Smith7586a6e2013-01-30 05:45:05 +00001014 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
John McCall9c0c1f32010-07-08 06:48:12 +00001015 }
1016
Eric Christopher041087c2011-08-15 22:38:22 +00001017 // 'const' and 'pure' attribute functions are also nounwind.
1018 if (TargetDecl->hasAttr<ConstAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001019 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
1020 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001021 } else if (TargetDecl->hasAttr<PureAttr>()) {
Bill Wendling72390b32012-12-20 19:27:06 +00001022 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
1023 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
Eric Christopher041087c2011-08-15 22:38:22 +00001024 }
Ryan Flynn76168e22009-08-09 20:07:29 +00001025 if (TargetDecl->hasAttr<MallocAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +00001026 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001027 }
1028
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001029 if (CodeGenOpts.OptimizeSize)
Bill Wendling72390b32012-12-20 19:27:06 +00001030 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
Quentin Colombet90467682012-10-26 00:29:48 +00001031 if (CodeGenOpts.OptimizeSize == 2)
Bill Wendling72390b32012-12-20 19:27:06 +00001032 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001033 if (CodeGenOpts.DisableRedZone)
Bill Wendling72390b32012-12-20 19:27:06 +00001034 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
Chandler Carruth2811ccf2009-11-12 17:24:48 +00001035 if (CodeGenOpts.NoImplicitFloat)
Bill Wendling72390b32012-12-20 19:27:06 +00001036 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
Devang Patel24095da2009-06-04 23:32:02 +00001037
Bill Wendling93e4bff2013-02-22 20:53:29 +00001038 if (AttrOnCallSite) {
1039 // Attributes that should go on the call site only.
1040 if (!CodeGenOpts.SimplifyLibCalls)
1041 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001042 } else {
1043 // Attributes that should go on the function, but not the call site.
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001044 if (!CodeGenOpts.DisableFPElim) {
Bill Wendling4159f052013-03-13 22:24:33 +00001045 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001046 } else if (CodeGenOpts.OmitLeafFramePointer) {
Bill Wendling4159f052013-03-13 22:24:33 +00001047 FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001048 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001049 } else {
Bill Wendling4159f052013-03-13 22:24:33 +00001050 FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
Bill Wendlingfae228b2013-08-22 21:16:51 +00001051 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
Bill Wendlingbe9e8bf2013-02-28 22:49:57 +00001052 }
1053
Bill Wendling4159f052013-03-13 22:24:33 +00001054 FuncAttrs.addAttribute("less-precise-fpmad",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001055 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
Bill Wendling4159f052013-03-13 22:24:33 +00001056 FuncAttrs.addAttribute("no-infs-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001057 llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001058 FuncAttrs.addAttribute("no-nans-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001059 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001060 FuncAttrs.addAttribute("unsafe-fp-math",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001061 llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
Bill Wendling4159f052013-03-13 22:24:33 +00001062 FuncAttrs.addAttribute("use-soft-float",
Bill Wendling52d08fe2013-07-26 21:51:11 +00001063 llvm::toStringRef(CodeGenOpts.SoftFloat));
Bill Wendling45ccf282013-07-22 20:15:41 +00001064 FuncAttrs.addAttribute("stack-protector-buffer-size",
Bill Wendling8d230b42013-07-12 22:26:07 +00001065 llvm::utostr(CodeGenOpts.SSPBufferSize));
Bill Wendlingcab4a092013-07-25 00:32:41 +00001066
Bill Wendling1cf9ab82013-08-01 21:41:02 +00001067 if (!CodeGenOpts.StackRealignment)
1068 FuncAttrs.addAttribute("no-realign-stack");
Bill Wendlingc0dcc2d2013-02-15 21:30:01 +00001069 }
1070
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001071 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001072 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001073 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001074 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001075 case ABIArgInfo::Extend:
Jakob Stoklund Olesen5baefa82013-05-29 03:57:23 +00001076 if (RetTy->hasSignedIntegerRepresentation())
1077 RetAttrs.addAttribute(llvm::Attribute::SExt);
1078 else if (RetTy->hasUnsignedIntegerRepresentation())
1079 RetAttrs.addAttribute(llvm::Attribute::ZExt);
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001080 // FALL THROUGH
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001081 case ABIArgInfo::Direct:
Jakob Stoklund Olesen90f9ec02013-06-05 03:00:09 +00001082 if (RetAI.getInReg())
1083 RetAttrs.addAttribute(llvm::Attribute::InReg);
1084 break;
Chris Lattner800588f2010-07-29 06:26:06 +00001085 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001086 break;
1087
Rafael Espindolab48280b2012-07-31 02:44:24 +00001088 case ABIArgInfo::Indirect: {
Bill Wendling0d583392012-10-15 20:36:26 +00001089 llvm::AttrBuilder SRETAttrs;
Bill Wendling72390b32012-12-20 19:27:06 +00001090 SRETAttrs.addAttribute(llvm::Attribute::StructRet);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001091 if (RetAI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001092 SRETAttrs.addAttribute(llvm::Attribute::InReg);
Bill Wendling603571a2012-10-10 07:36:56 +00001093 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001094 AttributeSet::get(getLLVMContext(), Index, SRETAttrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001095
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001096 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001097 // sret disables readnone and readonly
Bill Wendling72390b32012-12-20 19:27:06 +00001098 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1099 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001100 break;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001101 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001102
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001103 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001104 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001105 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001106
Bill Wendling603571a2012-10-10 07:36:56 +00001107 if (RetAttrs.hasAttributes())
1108 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001109 AttributeSet::get(getLLVMContext(),
1110 llvm::AttributeSet::ReturnIndex,
1111 RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001114 ie = FI.arg_end(); it != ie; ++it) {
1115 QualType ParamType = it->type;
1116 const ABIArgInfo &AI = it->info;
Bill Wendling0d583392012-10-15 20:36:26 +00001117 llvm::AttrBuilder Attrs;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001118
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001119 if (AI.getPaddingType()) {
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001120 if (AI.getPaddingInReg())
1121 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index,
1122 llvm::Attribute::InReg));
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001123 // Increment Index if there is padding.
1124 ++Index;
1125 }
1126
John McCalld8e10d22010-03-27 00:47:27 +00001127 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
1128 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +00001129 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001130 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +00001131 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +00001132 if (ParamType->isSignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001133 Attrs.addAttribute(llvm::Attribute::SExt);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001134 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Bill Wendling72390b32012-12-20 19:27:06 +00001135 Attrs.addAttribute(llvm::Attribute::ZExt);
Chris Lattner800588f2010-07-29 06:26:06 +00001136 // FALL THROUGH
1137 case ABIArgInfo::Direct:
Rafael Espindolab48280b2012-07-31 02:44:24 +00001138 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001139 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001140
Chris Lattner800588f2010-07-29 06:26:06 +00001141 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001142
Chris Lattner2acc6e32011-07-18 04:24:23 +00001143 if (llvm::StructType *STy =
Rafael Espindolab48280b2012-07-31 02:44:24 +00001144 dyn_cast<llvm::StructType>(AI.getCoerceToType())) {
1145 unsigned Extra = STy->getNumElements()-1; // 1 will be added below.
Bill Wendling603571a2012-10-10 07:36:56 +00001146 if (Attrs.hasAttributes())
Rafael Espindolab48280b2012-07-31 02:44:24 +00001147 for (unsigned I = 0; I < Extra; ++I)
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001148 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index + I,
1149 Attrs));
Rafael Espindolab48280b2012-07-31 02:44:24 +00001150 Index += Extra;
1151 }
Chris Lattner800588f2010-07-29 06:26:06 +00001152 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001153
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001154 case ABIArgInfo::Indirect:
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001155 if (AI.getInReg())
Bill Wendling72390b32012-12-20 19:27:06 +00001156 Attrs.addAttribute(llvm::Attribute::InReg);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001157
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001158 if (AI.getIndirectByVal())
Bill Wendling72390b32012-12-20 19:27:06 +00001159 Attrs.addAttribute(llvm::Attribute::ByVal);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001160
Bill Wendling603571a2012-10-10 07:36:56 +00001161 Attrs.addAlignmentAttr(AI.getIndirectAlign());
1162
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001163 // byval disables readnone and readonly.
Bill Wendling72390b32012-12-20 19:27:06 +00001164 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
1165 .removeAttribute(llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001166 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001167
Daniel Dunbar11434922009-01-26 21:26:08 +00001168 case ABIArgInfo::Ignore:
1169 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001170 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +00001171
Daniel Dunbar56273772008-09-17 00:51:38 +00001172 case ABIArgInfo::Expand: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001173 SmallVector<llvm::Type*, 8> types;
Mike Stumpf5408fe2009-05-16 07:57:57 +00001174 // FIXME: This is rather inefficient. Do we ever actually need to do
1175 // anything here? The result should be just reconstructed on the other
1176 // side, so extension should be a non-issue.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001177 getTypes().GetExpandedTypes(ParamType, types);
John McCall42e06112011-05-15 02:19:42 +00001178 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00001179 continue;
1180 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Bill Wendling603571a2012-10-10 07:36:56 +00001183 if (Attrs.hasAttributes())
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001184 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), Index, Attrs));
Daniel Dunbar56273772008-09-17 00:51:38 +00001185 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001186 }
Bill Wendling603571a2012-10-10 07:36:56 +00001187 if (FuncAttrs.hasAttributes())
Bill Wendling75d37b42012-10-15 07:31:59 +00001188 PAL.push_back(llvm::
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001189 AttributeSet::get(getLLVMContext(),
1190 llvm::AttributeSet::FunctionIndex,
1191 FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001192}
1193
John McCalld26bc762011-03-09 04:27:21 +00001194/// An argument came in as a promoted argument; demote it back to its
1195/// declared type.
1196static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
1197 const VarDecl *var,
1198 llvm::Value *value) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001199 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalld26bc762011-03-09 04:27:21 +00001200
1201 // This can happen with promotions that actually don't change the
1202 // underlying type, like the enum promotions.
1203 if (value->getType() == varType) return value;
1204
1205 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
1206 && "unexpected promotion type");
1207
1208 if (isa<llvm::IntegerType>(varType))
1209 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
1210
1211 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
1212}
1213
Daniel Dunbar88b53962009-02-02 22:03:45 +00001214void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1215 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001216 const FunctionArgList &Args) {
John McCall0cfeb632009-07-28 01:00:58 +00001217 // If this is an implicit-return-zero function, go ahead and
1218 // initialize the return value. TODO: it might be nice to have
1219 // a more general mechanism for this that didn't require synthesized
1220 // return statements.
John McCallf5ebf9b2013-05-03 07:33:41 +00001221 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +00001222 if (FD->hasImplicitReturnZero()) {
1223 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001224 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001225 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +00001226 Builder.CreateStore(Zero, ReturnValue);
1227 }
1228 }
1229
Mike Stumpf5408fe2009-05-16 07:57:57 +00001230 // FIXME: We no longer need the types from FunctionArgList; lift up and
1231 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +00001232
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001233 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1234 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001236 // Name the struct return argument.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001237 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001238 AI->setName("agg.result");
Bill Wendling89530e42013-01-23 06:15:10 +00001239 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1240 AI->getArgNo() + 1,
1241 llvm::Attribute::NoAlias));
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001242 ++AI;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001245 assert(FI.arg_size() == Args.size() &&
1246 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +00001247 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001248 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +00001249 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1250 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +00001251 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001252 QualType Ty = info_it->type;
1253 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001254
John McCalld26bc762011-03-09 04:27:21 +00001255 bool isPromoted =
1256 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
1257
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001258 // Skip the dummy padding argument.
1259 if (ArgI.getPaddingType())
1260 ++AI;
1261
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001262 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001263 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +00001264 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001265
John McCall9d232c82013-03-07 21:37:08 +00001266 if (!hasScalarEvaluationKind(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001267 // Aggregates and complex variables are accessed by reference. All we
1268 // need to do is realign the value, if requested
1269 if (ArgI.getIndirectRealign()) {
1270 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
1271
1272 // Copy from the incoming argument pointer to the temporary with the
1273 // appropriate alignment.
1274 //
1275 // FIXME: We should have a common utility for generating an aggregate
1276 // copy.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001277 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +00001278 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +00001279 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
1280 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
1281 Builder.CreateMemCpy(Dst,
1282 Src,
Ken Dyckfe710082011-01-19 01:58:38 +00001283 llvm::ConstantInt::get(IntPtrTy,
1284 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +00001285 ArgI.getIndirectAlign(),
1286 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +00001287 V = AlignedTemp;
1288 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001289 } else {
1290 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +00001291 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1292 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalld26bc762011-03-09 04:27:21 +00001293
1294 if (isPromoted)
1295 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001296 }
Devang Patel093ac462011-03-03 20:13:15 +00001297 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001298 break;
1299 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001300
1301 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001302 case ABIArgInfo::Direct: {
Akira Hatanaka4ba3fd42012-01-09 19:08:06 +00001303
Chris Lattner800588f2010-07-29 06:26:06 +00001304 // If we have the trivial case, handle it with no muss and fuss.
1305 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001306 ArgI.getCoerceToType() == ConvertType(Ty) &&
1307 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001308 assert(AI != Fn->arg_end() && "Argument mismatch!");
1309 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001310
Bill Wendlinga6375562012-10-16 05:23:44 +00001311 if (Arg->getType().isRestrictQualified())
Bill Wendling89530e42013-01-23 06:15:10 +00001312 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
1313 AI->getArgNo() + 1,
1314 llvm::Attribute::NoAlias));
John McCalld8e10d22010-03-27 00:47:27 +00001315
Chris Lattnerb13eab92011-07-20 06:29:00 +00001316 // Ensure the argument is the correct type.
1317 if (V->getType() != ArgI.getCoerceToType())
1318 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
1319
John McCalld26bc762011-03-09 04:27:21 +00001320 if (isPromoted)
1321 V = emitArgumentDemotion(*this, Arg, V);
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001322
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00001323 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1324 if (MD->isVirtual() && Arg == CXXABIThisDecl)
1325 V = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
1326 }
1327
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00001328 // Because of merging of function types from multiple decls it is
1329 // possible for the type of an argument to not match the corresponding
1330 // type in the function type. Since we are codegening the callee
1331 // in here, add a cast to the argument type.
1332 llvm::Type *LTy = ConvertType(Arg->getType());
1333 if (V->getType() != LTy)
1334 V = Builder.CreateBitCast(V, LTy);
1335
Devang Patel093ac462011-03-03 20:13:15 +00001336 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001337 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001340 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, Arg->getName());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001341
Chris Lattnerdeabde22010-07-28 18:24:28 +00001342 // The alignment we need to use is the max of the requested alignment for
1343 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001344 unsigned AlignmentToUse =
Micah Villmow25a6a842012-10-08 16:25:52 +00001345 CGM.getDataLayout().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +00001346 AlignmentToUse = std::max(AlignmentToUse,
1347 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001348
Chris Lattnerdeabde22010-07-28 18:24:28 +00001349 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001350 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001351 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001352
Chris Lattner117e3f42010-07-30 04:02:24 +00001353 // If the value is offset in memory, apply the offset now.
1354 if (unsigned Offs = ArgI.getDirectOffset()) {
1355 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1356 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001357 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001358 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1359 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001360
Chris Lattner309c59f2010-06-29 00:06:42 +00001361 // If the coerce-to type is a first class aggregate, we flatten it and
1362 // pass the elements. Either way is semantically identical, but fast-isel
1363 // and the optimizer generally likes scalar values better than FCAs.
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001364 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
1365 if (STy && STy->getNumElements() > 1) {
Micah Villmow25a6a842012-10-08 16:25:52 +00001366 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001367 llvm::Type *DstTy =
1368 cast<llvm::PointerType>(Ptr->getType())->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00001369 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001370
Evgeniy Stepanova6ce20e2012-02-10 09:30:15 +00001371 if (SrcSize <= DstSize) {
1372 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
1373
1374 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1375 assert(AI != Fn->arg_end() && "Argument mismatch!");
1376 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1377 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1378 Builder.CreateStore(AI++, EltPtr);
1379 }
1380 } else {
1381 llvm::AllocaInst *TempAlloca =
1382 CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
1383 TempAlloca->setAlignment(AlignmentToUse);
1384 llvm::Value *TempV = TempAlloca;
1385
1386 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1387 assert(AI != Fn->arg_end() && "Argument mismatch!");
1388 AI->setName(Arg->getName() + ".coerce" + Twine(i));
1389 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(TempV, 0, i);
1390 Builder.CreateStore(AI++, EltPtr);
1391 }
1392
1393 Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
Chris Lattner309c59f2010-06-29 00:06:42 +00001394 }
1395 } else {
1396 // Simple case, just do a coerced store of the argument into the alloca.
1397 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001398 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001399 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001400 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001401
1402
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001403 // Match to what EmitParmDecl is expecting for this type.
John McCall9d232c82013-03-07 21:37:08 +00001404 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001405 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalld26bc762011-03-09 04:27:21 +00001406 if (isPromoted)
1407 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001408 }
Devang Patel093ac462011-03-03 20:13:15 +00001409 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerce700162010-06-28 23:44:11 +00001410 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001411 }
Chris Lattner800588f2010-07-29 06:26:06 +00001412
1413 case ABIArgInfo::Expand: {
1414 // If this structure was expanded into multiple arguments then
1415 // we need to create a temporary and reconstruct it from the
1416 // arguments.
Eli Friedman1bb94a42011-11-03 21:39:02 +00001417 llvm::AllocaInst *Alloca = CreateMemTemp(Ty);
Eli Friedman6da2c712011-12-03 04:14:32 +00001418 CharUnits Align = getContext().getDeclAlign(Arg);
1419 Alloca->setAlignment(Align.getQuantity());
1420 LValue LV = MakeAddrLValue(Alloca, Ty, Align);
Eli Friedman1bb94a42011-11-03 21:39:02 +00001421 llvm::Function::arg_iterator End = ExpandTypeFromArgs(Ty, LV, AI);
1422 EmitParmDecl(*Arg, Alloca, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001423
1424 // Name the arguments used in expansion and increment AI.
1425 unsigned Index = 0;
1426 for (; AI != End; ++AI, ++Index)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001427 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattner800588f2010-07-29 06:26:06 +00001428 continue;
1429 }
1430
1431 case ABIArgInfo::Ignore:
1432 // Initialize the local variable appropriately.
John McCall9d232c82013-03-07 21:37:08 +00001433 if (!hasScalarEvaluationKind(Ty))
Devang Patel093ac462011-03-03 20:13:15 +00001434 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001435 else
Devang Patel093ac462011-03-03 20:13:15 +00001436 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1437 ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001438
1439 // Skip increment, no matching LLVM parameter.
1440 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001441 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001442
1443 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001444 }
1445 assert(AI == Fn->arg_end() && "Argument mismatch!");
1446}
1447
John McCall77fe6cd2012-01-29 07:46:59 +00001448static void eraseUnusedBitCasts(llvm::Instruction *insn) {
1449 while (insn->use_empty()) {
1450 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
1451 if (!bitcast) return;
1452
1453 // This is "safe" because we would have used a ConstantExpr otherwise.
1454 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
1455 bitcast->eraseFromParent();
1456 }
1457}
1458
John McCallf85e1932011-06-15 23:02:42 +00001459/// Try to emit a fused autorelease of a return result.
1460static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1461 llvm::Value *result) {
1462 // We must be immediately followed the cast.
1463 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1464 if (BB->empty()) return 0;
1465 if (&BB->back() != result) return 0;
1466
Chris Lattner2acc6e32011-07-18 04:24:23 +00001467 llvm::Type *resultType = result->getType();
John McCallf85e1932011-06-15 23:02:42 +00001468
1469 // result is in a BasicBlock and is therefore an Instruction.
1470 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1471
Chris Lattner5f9e2722011-07-23 10:55:15 +00001472 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCallf85e1932011-06-15 23:02:42 +00001473
1474 // Look for:
1475 // %generator = bitcast %type1* %generator2 to %type2*
1476 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1477 // We would have emitted this as a constant if the operand weren't
1478 // an Instruction.
1479 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1480
1481 // Require the generator to be immediately followed by the cast.
1482 if (generator->getNextNode() != bitcast)
1483 return 0;
1484
1485 insnsToKill.push_back(bitcast);
1486 }
1487
1488 // Look for:
1489 // %generator = call i8* @objc_retain(i8* %originalResult)
1490 // or
1491 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1492 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1493 if (!call) return 0;
1494
1495 bool doRetainAutorelease;
1496
1497 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1498 doRetainAutorelease = true;
1499 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1500 .objc_retainAutoreleasedReturnValue) {
1501 doRetainAutorelease = false;
1502
John McCallf9fdcc02012-09-07 23:30:50 +00001503 // If we emitted an assembly marker for this call (and the
1504 // ARCEntrypoints field should have been set if so), go looking
1505 // for that call. If we can't find it, we can't do this
1506 // optimization. But it should always be the immediately previous
1507 // instruction, unless we needed bitcasts around the call.
1508 if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
1509 llvm::Instruction *prev = call->getPrevNode();
1510 assert(prev);
1511 if (isa<llvm::BitCastInst>(prev)) {
1512 prev = prev->getPrevNode();
1513 assert(prev);
1514 }
1515 assert(isa<llvm::CallInst>(prev));
1516 assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
1517 CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
1518 insnsToKill.push_back(prev);
1519 }
John McCallf85e1932011-06-15 23:02:42 +00001520 } else {
1521 return 0;
1522 }
1523
1524 result = call->getArgOperand(0);
1525 insnsToKill.push_back(call);
1526
1527 // Keep killing bitcasts, for sanity. Note that we no longer care
1528 // about precise ordering as long as there's exactly one use.
1529 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1530 if (!bitcast->hasOneUse()) break;
1531 insnsToKill.push_back(bitcast);
1532 result = bitcast->getOperand(0);
1533 }
1534
1535 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001536 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCallf85e1932011-06-15 23:02:42 +00001537 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1538 (*i)->eraseFromParent();
1539
1540 // Do the fused retain/autorelease if we were asked to.
1541 if (doRetainAutorelease)
1542 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1543
1544 // Cast back to the result type.
1545 return CGF.Builder.CreateBitCast(result, resultType);
1546}
1547
John McCall77fe6cd2012-01-29 07:46:59 +00001548/// If this is a +1 of the value of an immutable 'self', remove it.
1549static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
1550 llvm::Value *result) {
1551 // This is only applicable to a method with an immutable 'self'.
John McCallbd9b65a2012-07-31 00:33:55 +00001552 const ObjCMethodDecl *method =
1553 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall77fe6cd2012-01-29 07:46:59 +00001554 if (!method) return 0;
1555 const VarDecl *self = method->getSelfDecl();
1556 if (!self->getType().isConstQualified()) return 0;
1557
1558 // Look for a retain call.
1559 llvm::CallInst *retainCall =
1560 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
1561 if (!retainCall ||
1562 retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
1563 return 0;
1564
1565 // Look for an ordinary load of 'self'.
1566 llvm::Value *retainedValue = retainCall->getArgOperand(0);
1567 llvm::LoadInst *load =
1568 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
1569 if (!load || load->isAtomic() || load->isVolatile() ||
1570 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self))
1571 return 0;
1572
1573 // Okay! Burn it all down. This relies for correctness on the
1574 // assumption that the retain is emitted as part of the return and
1575 // that thereafter everything is used "linearly".
1576 llvm::Type *resultType = result->getType();
1577 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
1578 assert(retainCall->use_empty());
1579 retainCall->eraseFromParent();
1580 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
1581
1582 return CGF.Builder.CreateBitCast(load, resultType);
1583}
1584
John McCallf85e1932011-06-15 23:02:42 +00001585/// Emit an ARC autorelease of the result of a function.
John McCall77fe6cd2012-01-29 07:46:59 +00001586///
1587/// \return the value to actually return from the function
John McCallf85e1932011-06-15 23:02:42 +00001588static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1589 llvm::Value *result) {
John McCall77fe6cd2012-01-29 07:46:59 +00001590 // If we're returning 'self', kill the initial retain. This is a
1591 // heuristic attempt to "encourage correctness" in the really unfortunate
1592 // case where we have a return of self during a dealloc and we desperately
1593 // need to avoid the possible autorelease.
1594 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
1595 return self;
1596
John McCallf85e1932011-06-15 23:02:42 +00001597 // At -O0, try to emit a fused retain/autorelease.
1598 if (CGF.shouldUseFusedARCCalls())
1599 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1600 return fused;
1601
1602 return CGF.EmitARCAutoreleaseReturnValue(result);
1603}
1604
John McCallf48f7962012-01-29 02:35:02 +00001605/// Heuristically search for a dominating store to the return-value slot.
1606static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
1607 // If there are multiple uses of the return-value slot, just check
1608 // for something immediately preceding the IP. Sometimes this can
1609 // happen with how we generate implicit-returns; it can also happen
1610 // with noreturn cleanups.
1611 if (!CGF.ReturnValue->hasOneUse()) {
1612 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1613 if (IP->empty()) return 0;
1614 llvm::StoreInst *store = dyn_cast<llvm::StoreInst>(&IP->back());
1615 if (!store) return 0;
1616 if (store->getPointerOperand() != CGF.ReturnValue) return 0;
1617 assert(!store->isAtomic() && !store->isVolatile()); // see below
1618 return store;
1619 }
1620
1621 llvm::StoreInst *store =
1622 dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
1623 if (!store) return 0;
1624
1625 // These aren't actually possible for non-coerced returns, and we
1626 // only care about non-coerced returns on this code path.
1627 assert(!store->isAtomic() && !store->isVolatile());
1628
1629 // Now do a first-and-dirty dominance check: just walk up the
1630 // single-predecessors chain from the current insertion point.
1631 llvm::BasicBlock *StoreBB = store->getParent();
1632 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
1633 while (IP != StoreBB) {
1634 if (!(IP = IP->getSinglePredecessor()))
1635 return 0;
1636 }
1637
1638 // Okay, the store's basic block dominates the insertion point; we
1639 // can do our thing.
1640 return store;
1641}
1642
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001643void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
1644 bool EmitRetDbgLoc) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001645 // Functions with no result always return void.
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001646 if (ReturnValue == 0) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001647 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001648 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001649 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001650
Dan Gohman4751a532010-07-20 20:13:52 +00001651 llvm::DebugLoc RetDbgLoc;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001652 llvm::Value *RV = 0;
1653 QualType RetTy = FI.getReturnType();
1654 const ABIArgInfo &RetAI = FI.getReturnInfo();
1655
1656 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001657 case ABIArgInfo::Indirect: {
John McCall9d232c82013-03-07 21:37:08 +00001658 switch (getEvaluationKind(RetTy)) {
1659 case TEK_Complex: {
1660 ComplexPairTy RT =
1661 EmitLoadOfComplex(MakeNaturalAlignAddrLValue(ReturnValue, RetTy));
1662 EmitStoreOfComplex(RT,
1663 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1664 /*isInit*/ true);
1665 break;
1666 }
1667 case TEK_Aggregate:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001668 // Do nothing; aggregrates get evaluated directly into the destination.
John McCall9d232c82013-03-07 21:37:08 +00001669 break;
1670 case TEK_Scalar:
1671 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
1672 MakeNaturalAlignAddrLValue(CurFn->arg_begin(), RetTy),
1673 /*isInit*/ true);
1674 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001675 }
1676 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001677 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001678
1679 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001680 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001681 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1682 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001683 // The internal return value temp always will have pointer-to-return-type
1684 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001685
John McCallf48f7962012-01-29 02:35:02 +00001686 // If there is a dominating store to ReturnValue, we can elide
1687 // the load, zap the store, and usually zap the alloca.
1688 if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
Adrian Prantl7c731f52013-05-30 18:12:23 +00001689 // Reuse the debug location from the store unless there is
1690 // cleanup code to be emitted between the store and return
1691 // instruction.
1692 if (EmitRetDbgLoc && !AutoreleaseResult)
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001693 RetDbgLoc = SI->getDebugLoc();
Chris Lattner800588f2010-07-29 06:26:06 +00001694 // Get the stored value and nuke the now-dead store.
Chris Lattner800588f2010-07-29 06:26:06 +00001695 RV = SI->getValueOperand();
1696 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001697
Chris Lattner800588f2010-07-29 06:26:06 +00001698 // If that was the only use of the return value, nuke it as well now.
1699 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1700 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1701 ReturnValue = 0;
1702 }
John McCallf48f7962012-01-29 02:35:02 +00001703
1704 // Otherwise, we have to do a simple load.
1705 } else {
1706 RV = Builder.CreateLoad(ReturnValue);
Chris Lattner35b21b82010-06-27 01:06:27 +00001707 }
Chris Lattner800588f2010-07-29 06:26:06 +00001708 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001709 llvm::Value *V = ReturnValue;
1710 // If the value is offset in memory, apply the offset now.
1711 if (unsigned Offs = RetAI.getDirectOffset()) {
1712 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1713 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001714 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001715 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1716 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001717
Chris Lattner117e3f42010-07-30 04:02:24 +00001718 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001719 }
John McCallf85e1932011-06-15 23:02:42 +00001720
1721 // In ARC, end functions that return a retainable type with a call
1722 // to objc_autoreleaseReturnValue.
1723 if (AutoreleaseResult) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001724 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001725 !FI.isReturnsRetained() &&
1726 RetTy->isObjCRetainableType());
1727 RV = emitAutoreleaseOfResult(*this, RV);
1728 }
1729
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001730 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001731
Chris Lattner800588f2010-07-29 06:26:06 +00001732 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001733 break;
1734
1735 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001736 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001737 }
1738
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001739 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001740 if (!RetDbgLoc.isUnknown())
1741 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001742}
1743
John McCall413ebdb2011-03-11 20:59:21 +00001744void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1745 const VarDecl *param) {
John McCall27360712010-05-26 22:34:26 +00001746 // StartFunction converted the ABI-lowered parameter(s) into a
1747 // local alloca. We need to turn that into an r-value suitable
1748 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001749 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001750
John McCall413ebdb2011-03-11 20:59:21 +00001751 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001752
John McCall27360712010-05-26 22:34:26 +00001753 // For the most part, we just need to load the alloca, except:
1754 // 1) aggregate r-values are actually pointers to temporaries, and
John McCall9d232c82013-03-07 21:37:08 +00001755 // 2) references to non-scalars are pointers directly to the aggregate.
1756 // I don't know why references to scalars are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001757 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall9d232c82013-03-07 21:37:08 +00001758 if (!hasScalarEvaluationKind(ref->getPointeeType()))
John McCall413ebdb2011-03-11 20:59:21 +00001759 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001760
1761 // Locals which are references to scalars are represented
1762 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001763 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001764 }
1765
John McCall9d232c82013-03-07 21:37:08 +00001766 args.add(convertTempToRValue(local, type), type);
John McCall27360712010-05-26 22:34:26 +00001767}
1768
John McCallf85e1932011-06-15 23:02:42 +00001769static bool isProvablyNull(llvm::Value *addr) {
1770 return isa<llvm::ConstantPointerNull>(addr);
1771}
1772
1773static bool isProvablyNonNull(llvm::Value *addr) {
1774 return isa<llvm::AllocaInst>(addr);
1775}
1776
1777/// Emit the actual writing-back of a writeback.
1778static void emitWriteback(CodeGenFunction &CGF,
1779 const CallArgList::Writeback &writeback) {
John McCallb6a60792013-03-23 02:35:54 +00001780 const LValue &srcLV = writeback.Source;
1781 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00001782 assert(!isProvablyNull(srcAddr) &&
1783 "shouldn't have writeback for provably null argument");
1784
1785 llvm::BasicBlock *contBB = 0;
1786
1787 // If the argument wasn't provably non-null, we need to null check
1788 // before doing the store.
1789 bool provablyNonNull = isProvablyNonNull(srcAddr);
1790 if (!provablyNonNull) {
1791 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1792 contBB = CGF.createBasicBlock("icr.done");
1793
1794 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1795 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1796 CGF.EmitBlock(writebackBB);
1797 }
1798
1799 // Load the value to writeback.
1800 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1801
1802 // Cast it back, in case we're writing an id to a Foo* or something.
1803 value = CGF.Builder.CreateBitCast(value,
1804 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1805 "icr.writeback-cast");
1806
1807 // Perform the writeback.
John McCallb6a60792013-03-23 02:35:54 +00001808
1809 // If we have a "to use" value, it's something we need to emit a use
1810 // of. This has to be carefully threaded in: if it's done after the
1811 // release it's potentially undefined behavior (and the optimizer
1812 // will ignore it), and if it happens before the retain then the
1813 // optimizer could move the release there.
1814 if (writeback.ToUse) {
1815 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
1816
1817 // Retain the new value. No need to block-copy here: the block's
1818 // being passed up the stack.
1819 value = CGF.EmitARCRetainNonBlock(value);
1820
1821 // Emit the intrinsic use here.
1822 CGF.EmitARCIntrinsicUse(writeback.ToUse);
1823
1824 // Load the old value (primitively).
1825 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV);
1826
1827 // Put the new value in place (primitively).
1828 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
1829
1830 // Release the old value.
1831 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
1832
1833 // Otherwise, we can just do a normal lvalue store.
1834 } else {
1835 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
1836 }
John McCallf85e1932011-06-15 23:02:42 +00001837
1838 // Jump to the continuation block.
1839 if (!provablyNonNull)
1840 CGF.EmitBlock(contBB);
1841}
1842
1843static void emitWritebacks(CodeGenFunction &CGF,
1844 const CallArgList &args) {
1845 for (CallArgList::writeback_iterator
1846 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1847 emitWriteback(CGF, *i);
1848}
1849
Reid Kleckner9b601952013-06-21 12:45:15 +00001850static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
1851 const CallArgList &CallArgs) {
1852 assert(CGF.getTarget().getCXXABI().isArgumentDestroyedByCallee());
1853 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
1854 CallArgs.getCleanupsToDeactivate();
1855 // Iterate in reverse to increase the likelihood of popping the cleanup.
1856 for (ArrayRef<CallArgList::CallArgCleanup>::reverse_iterator
1857 I = Cleanups.rbegin(), E = Cleanups.rend(); I != E; ++I) {
1858 CGF.DeactivateCleanupBlock(I->Cleanup, I->IsActiveIP);
1859 I->IsActiveIP->eraseFromParent();
1860 }
1861}
1862
John McCallb6a60792013-03-23 02:35:54 +00001863static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
1864 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1865 if (uop->getOpcode() == UO_AddrOf)
1866 return uop->getSubExpr();
1867 return 0;
1868}
1869
John McCallf85e1932011-06-15 23:02:42 +00001870/// Emit an argument that's being passed call-by-writeback. That is,
1871/// we are passing the address of
1872static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1873 const ObjCIndirectCopyRestoreExpr *CRE) {
John McCallb6a60792013-03-23 02:35:54 +00001874 LValue srcLV;
1875
1876 // Make an optimistic effort to emit the address as an l-value.
1877 // This can fail if the the argument expression is more complicated.
1878 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
1879 srcLV = CGF.EmitLValue(lvExpr);
1880
1881 // Otherwise, just emit it as a scalar.
1882 } else {
1883 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1884
1885 QualType srcAddrType =
1886 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1887 srcLV = CGF.MakeNaturalAlignAddrLValue(srcAddr, srcAddrType);
1888 }
1889 llvm::Value *srcAddr = srcLV.getAddress();
John McCallf85e1932011-06-15 23:02:42 +00001890
1891 // The dest and src types don't necessarily match in LLVM terms
1892 // because of the crazy ObjC compatibility rules.
1893
Chris Lattner2acc6e32011-07-18 04:24:23 +00001894 llvm::PointerType *destType =
John McCallf85e1932011-06-15 23:02:42 +00001895 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1896
1897 // If the address is a constant null, just pass the appropriate null.
1898 if (isProvablyNull(srcAddr)) {
1899 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1900 CRE->getType());
1901 return;
1902 }
1903
John McCallf85e1932011-06-15 23:02:42 +00001904 // Create the temporary.
1905 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1906 "icr.temp");
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001907 // Loading an l-value can introduce a cleanup if the l-value is __weak,
1908 // and that cleanup will be conditional if we can't prove that the l-value
1909 // isn't null, so we need to register a dominating point so that the cleanups
1910 // system will make valid IR.
1911 CodeGenFunction::ConditionalEvaluation condEval(CGF);
1912
John McCallf85e1932011-06-15 23:02:42 +00001913 // Zero-initialize it if we're not doing a copy-initialization.
1914 bool shouldCopy = CRE->shouldCopy();
1915 if (!shouldCopy) {
1916 llvm::Value *null =
1917 llvm::ConstantPointerNull::get(
1918 cast<llvm::PointerType>(destType->getElementType()));
1919 CGF.Builder.CreateStore(null, temp);
1920 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001921
John McCallf85e1932011-06-15 23:02:42 +00001922 llvm::BasicBlock *contBB = 0;
John McCallb6a60792013-03-23 02:35:54 +00001923 llvm::BasicBlock *originBB = 0;
John McCallf85e1932011-06-15 23:02:42 +00001924
1925 // If the address is *not* known to be non-null, we need to switch.
1926 llvm::Value *finalArgument;
1927
1928 bool provablyNonNull = isProvablyNonNull(srcAddr);
1929 if (provablyNonNull) {
1930 finalArgument = temp;
1931 } else {
1932 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1933
1934 finalArgument = CGF.Builder.CreateSelect(isNull,
1935 llvm::ConstantPointerNull::get(destType),
1936 temp, "icr.argument");
1937
1938 // If we need to copy, then the load has to be conditional, which
1939 // means we need control flow.
1940 if (shouldCopy) {
John McCallb6a60792013-03-23 02:35:54 +00001941 originBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00001942 contBB = CGF.createBasicBlock("icr.cont");
1943 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1944 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1945 CGF.EmitBlock(copyBB);
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001946 condEval.begin(CGF);
John McCallf85e1932011-06-15 23:02:42 +00001947 }
1948 }
1949
John McCallb6a60792013-03-23 02:35:54 +00001950 llvm::Value *valueToUse = 0;
1951
John McCallf85e1932011-06-15 23:02:42 +00001952 // Perform a copy if necessary.
1953 if (shouldCopy) {
John McCall545d9962011-06-25 02:11:03 +00001954 RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
John McCallf85e1932011-06-15 23:02:42 +00001955 assert(srcRV.isScalar());
1956
1957 llvm::Value *src = srcRV.getScalarVal();
1958 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1959 "icr.cast");
1960
1961 // Use an ordinary store, not a store-to-lvalue.
1962 CGF.Builder.CreateStore(src, temp);
John McCallb6a60792013-03-23 02:35:54 +00001963
1964 // If optimization is enabled, and the value was held in a
1965 // __strong variable, we need to tell the optimizer that this
1966 // value has to stay alive until we're doing the store back.
1967 // This is because the temporary is effectively unretained,
1968 // and so otherwise we can violate the high-level semantics.
1969 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
1970 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
1971 valueToUse = src;
1972 }
John McCallf85e1932011-06-15 23:02:42 +00001973 }
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001974
John McCallf85e1932011-06-15 23:02:42 +00001975 // Finish the control flow if we needed it.
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001976 if (shouldCopy && !provablyNonNull) {
John McCallb6a60792013-03-23 02:35:54 +00001977 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
John McCallf85e1932011-06-15 23:02:42 +00001978 CGF.EmitBlock(contBB);
John McCallb6a60792013-03-23 02:35:54 +00001979
1980 // Make a phi for the value to intrinsically use.
1981 if (valueToUse) {
1982 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
1983 "icr.to-use");
1984 phiToUse->addIncoming(valueToUse, copyBB);
1985 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
1986 originBB);
1987 valueToUse = phiToUse;
1988 }
1989
Fariborz Jahanian82c458e2012-11-27 23:02:53 +00001990 condEval.end(CGF);
1991 }
John McCallf85e1932011-06-15 23:02:42 +00001992
John McCallb6a60792013-03-23 02:35:54 +00001993 args.addWriteback(srcLV, temp, valueToUse);
John McCallf85e1932011-06-15 23:02:42 +00001994 args.add(RValue::get(finalArgument), CRE->getType());
1995}
1996
John McCall413ebdb2011-03-11 20:59:21 +00001997void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
1998 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00001999 if (const ObjCIndirectCopyRestoreExpr *CRE
2000 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002001 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00002002 assert(getContext().hasSameType(E->getType(), type));
2003 return emitWritebackArg(*this, args, CRE);
2004 }
2005
John McCall8affed52011-08-26 18:42:59 +00002006 assert(type->isReferenceType() == E->isGLValue() &&
2007 "reference binding to unmaterialized r-value!");
2008
John McCallcec52f02011-08-26 21:08:13 +00002009 if (E->isGLValue()) {
2010 assert(E->getObjectKind() == OK_Ordinary);
Richard Smithd4ec5622013-06-12 23:38:09 +00002011 return args.add(EmitReferenceBindingToExpr(E), type);
John McCallcec52f02011-08-26 21:08:13 +00002012 }
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Reid Kleckner9b601952013-06-21 12:45:15 +00002014 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
2015
2016 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
2017 // However, we still have to push an EH-only cleanup in case we unwind before
2018 // we make it to the call.
2019 if (HasAggregateEvalKind &&
2020 CGM.getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
2021 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
2022 if (RD && RD->hasNonTrivialDestructor()) {
2023 AggValueSlot Slot = CreateAggTemp(type, "agg.arg.tmp");
2024 Slot.setExternallyDestructed();
2025 EmitAggExpr(E, Slot);
2026 RValue RV = Slot.asRValue();
2027 args.add(RV, type);
2028
2029 pushDestroy(EHCleanup, RV.getAggregateAddr(), type, destroyCXXObject,
2030 /*useEHCleanupForArray*/ true);
2031 // This unreachable is a temporary marker which will be removed later.
2032 llvm::Instruction *IsActive = Builder.CreateUnreachable();
2033 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
2034 return;
2035 }
2036 }
2037
2038 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00002039 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
2040 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
2041 assert(L.isSimple());
Eli Friedmand39083d2013-06-11 01:08:22 +00002042 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
2043 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
2044 } else {
2045 // We can't represent a misaligned lvalue in the CallArgList, so copy
2046 // to an aligned temporary now.
2047 llvm::Value *tmp = CreateMemTemp(type);
2048 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile(),
2049 L.getAlignment());
2050 args.add(RValue::getAggregate(tmp), type);
2051 }
Eli Friedman55d48482011-05-26 00:10:27 +00002052 return;
2053 }
2054
John McCall413ebdb2011-03-11 20:59:21 +00002055 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00002056}
2057
Dan Gohmanb49bd272012-02-16 00:57:37 +00002058// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2059// optimizer it can aggressively ignore unwind edges.
2060void
2061CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
2062 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
2063 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
2064 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
2065 CGM.getNoObjCARCExceptionsMetadata());
2066}
2067
John McCallbd7370a2013-02-28 19:01:20 +00002068/// Emits a call to the given no-arguments nounwind runtime function.
2069llvm::CallInst *
2070CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2071 const llvm::Twine &name) {
2072 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2073}
2074
2075/// Emits a call to the given nounwind runtime function.
2076llvm::CallInst *
2077CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
2078 ArrayRef<llvm::Value*> args,
2079 const llvm::Twine &name) {
2080 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
2081 call->setDoesNotThrow();
2082 return call;
2083}
2084
2085/// Emits a simple call (never an invoke) to the given no-arguments
2086/// runtime function.
2087llvm::CallInst *
2088CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2089 const llvm::Twine &name) {
2090 return EmitRuntimeCall(callee, ArrayRef<llvm::Value*>(), name);
2091}
2092
2093/// Emits a simple call (never an invoke) to the given runtime
2094/// function.
2095llvm::CallInst *
2096CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
2097 ArrayRef<llvm::Value*> args,
2098 const llvm::Twine &name) {
2099 llvm::CallInst *call = Builder.CreateCall(callee, args, name);
2100 call->setCallingConv(getRuntimeCC());
2101 return call;
2102}
2103
2104/// Emits a call or invoke to the given noreturn runtime function.
2105void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2106 ArrayRef<llvm::Value*> args) {
2107 if (getInvokeDest()) {
2108 llvm::InvokeInst *invoke =
2109 Builder.CreateInvoke(callee,
2110 getUnreachableBlock(),
2111 getInvokeDest(),
2112 args);
2113 invoke->setDoesNotReturn();
2114 invoke->setCallingConv(getRuntimeCC());
2115 } else {
2116 llvm::CallInst *call = Builder.CreateCall(callee, args);
2117 call->setDoesNotReturn();
2118 call->setCallingConv(getRuntimeCC());
2119 Builder.CreateUnreachable();
2120 }
2121}
2122
2123/// Emits a call or invoke instruction to the given nullary runtime
2124/// function.
2125llvm::CallSite
2126CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2127 const Twine &name) {
2128 return EmitRuntimeCallOrInvoke(callee, ArrayRef<llvm::Value*>(), name);
2129}
2130
2131/// Emits a call or invoke instruction to the given runtime function.
2132llvm::CallSite
2133CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
2134 ArrayRef<llvm::Value*> args,
2135 const Twine &name) {
2136 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
2137 callSite.setCallingConv(getRuntimeCC());
2138 return callSite;
2139}
2140
2141llvm::CallSite
2142CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
2143 const Twine &Name) {
2144 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
2145}
2146
John McCallf1549f62010-07-06 01:34:17 +00002147/// Emits a call or invoke instruction to the given function, depending
2148/// on the current state of the EH stack.
2149llvm::CallSite
2150CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002151 ArrayRef<llvm::Value *> Args,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002152 const Twine &Name) {
John McCallf1549f62010-07-06 01:34:17 +00002153 llvm::BasicBlock *InvokeDest = getInvokeDest();
John McCallf1549f62010-07-06 01:34:17 +00002154
Dan Gohmanb49bd272012-02-16 00:57:37 +00002155 llvm::Instruction *Inst;
2156 if (!InvokeDest)
2157 Inst = Builder.CreateCall(Callee, Args, Name);
2158 else {
2159 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
2160 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
2161 EmitBlock(ContBB);
2162 }
2163
2164 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2165 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002166 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002167 AddObjCARCExceptionMetadata(Inst);
2168
2169 return Inst;
John McCallf1549f62010-07-06 01:34:17 +00002170}
2171
Chris Lattner70855442011-07-12 04:46:18 +00002172static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
2173 llvm::FunctionType *FTy) {
2174 if (ArgNo < FTy->getNumParams())
2175 assert(Elt->getType() == FTy->getParamType(ArgNo));
2176 else
2177 assert(FTy->isVarArg());
2178 ++ArgNo;
2179}
2180
Chris Lattner811bf362011-07-12 06:29:11 +00002181void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Craig Topper6b9240e2013-07-05 19:34:19 +00002182 SmallVectorImpl<llvm::Value *> &Args,
Chris Lattner811bf362011-07-12 06:29:11 +00002183 llvm::FunctionType *IRFuncTy) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002184 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2185 unsigned NumElts = AT->getSize().getZExtValue();
2186 QualType EltTy = AT->getElementType();
2187 llvm::Value *Addr = RV.getAggregateAddr();
2188 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2189 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
John McCall9d232c82013-03-07 21:37:08 +00002190 RValue EltRV = convertTempToRValue(EltAddr, EltTy);
Bob Wilson194f06a2011-08-03 05:58:22 +00002191 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattner811bf362011-07-12 06:29:11 +00002192 }
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002193 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002194 RecordDecl *RD = RT->getDecl();
2195 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
Eli Friedman377ecc72012-04-16 03:54:45 +00002196 LValue LV = MakeAddrLValue(RV.getAggregateAddr(), Ty);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002197
2198 if (RD->isUnion()) {
2199 const FieldDecl *LargestFD = 0;
2200 CharUnits UnionSize = CharUnits::Zero();
2201
2202 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2203 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002204 const FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002205 assert(!FD->isBitField() &&
2206 "Cannot expand structure with bit-field members.");
2207 CharUnits FieldSize = getContext().getTypeSizeInChars(FD->getType());
2208 if (UnionSize < FieldSize) {
2209 UnionSize = FieldSize;
2210 LargestFD = FD;
2211 }
2212 }
2213 if (LargestFD) {
Eli Friedman377ecc72012-04-16 03:54:45 +00002214 RValue FldRV = EmitRValueForField(LV, LargestFD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002215 ExpandTypeToArgs(LargestFD->getType(), FldRV, Args, IRFuncTy);
2216 }
2217 } else {
2218 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2219 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002220 FieldDecl *FD = *i;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002221
Eli Friedman377ecc72012-04-16 03:54:45 +00002222 RValue FldRV = EmitRValueForField(LV, FD);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00002223 ExpandTypeToArgs(FD->getType(), FldRV, Args, IRFuncTy);
2224 }
Bob Wilson194f06a2011-08-03 05:58:22 +00002225 }
Eli Friedmanca3d3fc2011-11-15 02:46:03 +00002226 } else if (Ty->isAnyComplexType()) {
Bob Wilson194f06a2011-08-03 05:58:22 +00002227 ComplexPairTy CV = RV.getComplexVal();
2228 Args.push_back(CV.first);
2229 Args.push_back(CV.second);
2230 } else {
Chris Lattner811bf362011-07-12 06:29:11 +00002231 assert(RV.isScalar() &&
2232 "Unexpected non-scalar rvalue during struct expansion.");
2233
2234 // Insert a bitcast as needed.
2235 llvm::Value *V = RV.getScalarVal();
2236 if (Args.size() < IRFuncTy->getNumParams() &&
2237 V->getType() != IRFuncTy->getParamType(Args.size()))
2238 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
2239
2240 Args.push_back(V);
2241 }
2242}
2243
2244
Daniel Dunbar88b53962009-02-02 22:03:45 +00002245RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002246 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00002247 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002248 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00002249 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00002250 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002251 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002252 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002253
2254 // Handle struct-return functions by passing a pointer to the
2255 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002256 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002257 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Chris Lattner70855442011-07-12 04:46:18 +00002259 // IRArgNo - Keep track of the argument number in the callee we're looking at.
2260 unsigned IRArgNo = 0;
2261 llvm::FunctionType *IRFuncTy =
2262 cast<llvm::FunctionType>(
2263 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Chris Lattner5db7ae52009-06-13 00:26:38 +00002265 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00002266 // alloca to hold the result, unless one is given to us.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00002267 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlssond2490a92009-12-24 20:40:36 +00002268 llvm::Value *Value = ReturnValue.getValue();
2269 if (!Value)
Daniel Dunbar195337d2010-02-09 02:48:28 +00002270 Value = CreateMemTemp(RetTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00002271 Args.push_back(Value);
Chris Lattner70855442011-07-12 04:46:18 +00002272 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00002273 }
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00002275 assert(CallInfo.arg_size() == CallArgs.size() &&
2276 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00002277 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00002278 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002279 I != E; ++I, ++info_it) {
2280 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00002281 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00002282
John McCall9d232c82013-03-07 21:37:08 +00002283 CharUnits TypeAlign = getContext().getTypeAlignInChars(I->Ty);
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00002284
2285 // Insert a padding argument to ensure proper alignment.
2286 if (llvm::Type *PaddingType = ArgInfo.getPaddingType()) {
2287 Args.push_back(llvm::UndefValue::get(PaddingType));
2288 ++IRArgNo;
2289 }
2290
Daniel Dunbar56273772008-09-17 00:51:38 +00002291 switch (ArgInfo.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002292 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00002293 if (RV.isScalar() || RV.isComplex()) {
2294 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00002295 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2296 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
2297 AI->setAlignment(ArgInfo.getIndirectAlign());
2298 Args.push_back(AI);
John McCall9d232c82013-03-07 21:37:08 +00002299
2300 LValue argLV =
2301 MakeAddrLValue(Args.back(), I->Ty, TypeAlign);
Chris Lattner70855442011-07-12 04:46:18 +00002302
Daniel Dunbar1f745982009-02-05 09:16:39 +00002303 if (RV.isScalar())
John McCall9d232c82013-03-07 21:37:08 +00002304 EmitStoreOfScalar(RV.getScalarVal(), argLV, /*init*/ true);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002305 else
John McCall9d232c82013-03-07 21:37:08 +00002306 EmitStoreOfComplex(RV.getComplexVal(), argLV, /*init*/ true);
Chris Lattner70855442011-07-12 04:46:18 +00002307
2308 // Validate argument match.
2309 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002310 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002311 // We want to avoid creating an unnecessary temporary+copy here;
Guy Benyeid436c992013-03-10 12:59:00 +00002312 // however, we need one in three cases:
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002313 // 1. If the argument is not byval, and we are required to copy the
2314 // source. (This case doesn't occur on any common architecture.)
2315 // 2. If the argument is byval, RV is not sufficiently aligned, and
2316 // we cannot force it to be sufficiently aligned.
Guy Benyeid436c992013-03-10 12:59:00 +00002317 // 3. If the argument is byval, but RV is located in an address space
2318 // different than that of the argument (0).
Eli Friedman97cb5a42011-06-15 22:09:18 +00002319 llvm::Value *Addr = RV.getAggregateAddr();
2320 unsigned Align = ArgInfo.getIndirectAlign();
Micah Villmow25a6a842012-10-08 16:25:52 +00002321 const llvm::DataLayout *TD = &CGM.getDataLayout();
Guy Benyeid436c992013-03-10 12:59:00 +00002322 const unsigned RVAddrSpace = Addr->getType()->getPointerAddressSpace();
2323 const unsigned ArgAddrSpace = (IRArgNo < IRFuncTy->getNumParams() ?
2324 IRFuncTy->getParamType(IRArgNo)->getPointerAddressSpace() : 0);
Eli Friedman97cb5a42011-06-15 22:09:18 +00002325 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
John McCall9d232c82013-03-07 21:37:08 +00002326 (ArgInfo.getIndirectByVal() && TypeAlign.getQuantity() < Align &&
Guy Benyeid436c992013-03-10 12:59:00 +00002327 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align) ||
2328 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002329 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002330 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
2331 if (Align > AI->getAlignment())
2332 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002333 Args.push_back(AI);
Chad Rosier649b4a12012-03-29 17:37:10 +00002334 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattner70855442011-07-12 04:46:18 +00002335
2336 // Validate argument match.
2337 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002338 } else {
2339 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00002340 Args.push_back(Addr);
Chris Lattner70855442011-07-12 04:46:18 +00002341
2342 // Validate argument match.
2343 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00002344 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002345 }
2346 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00002347 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00002348
Daniel Dunbar11434922009-01-26 21:26:08 +00002349 case ABIArgInfo::Ignore:
2350 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002351
Chris Lattner800588f2010-07-29 06:26:06 +00002352 case ABIArgInfo::Extend:
2353 case ABIArgInfo::Direct: {
2354 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00002355 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
2356 ArgInfo.getDirectOffset() == 0) {
Chris Lattner70855442011-07-12 04:46:18 +00002357 llvm::Value *V;
Chris Lattner800588f2010-07-29 06:26:06 +00002358 if (RV.isScalar())
Chris Lattner70855442011-07-12 04:46:18 +00002359 V = RV.getScalarVal();
Chris Lattner800588f2010-07-29 06:26:06 +00002360 else
Chris Lattner70855442011-07-12 04:46:18 +00002361 V = Builder.CreateLoad(RV.getAggregateAddr());
2362
Chris Lattner21ca1fd2011-07-12 04:53:39 +00002363 // If the argument doesn't match, perform a bitcast to coerce it. This
2364 // can happen due to trivial type mismatches.
2365 if (IRArgNo < IRFuncTy->getNumParams() &&
2366 V->getType() != IRFuncTy->getParamType(IRArgNo))
2367 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattner70855442011-07-12 04:46:18 +00002368 Args.push_back(V);
2369
Chris Lattner70855442011-07-12 04:46:18 +00002370 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattner800588f2010-07-29 06:26:06 +00002371 break;
2372 }
Daniel Dunbar11434922009-01-26 21:26:08 +00002373
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002374 // FIXME: Avoid the conversion through memory if possible.
2375 llvm::Value *SrcPtr;
John McCall9d232c82013-03-07 21:37:08 +00002376 if (RV.isScalar() || RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00002377 SrcPtr = CreateMemTemp(I->Ty, "coerce");
John McCall9d232c82013-03-07 21:37:08 +00002378 LValue SrcLV = MakeAddrLValue(SrcPtr, I->Ty, TypeAlign);
2379 if (RV.isScalar()) {
2380 EmitStoreOfScalar(RV.getScalarVal(), SrcLV, /*init*/ true);
2381 } else {
2382 EmitStoreOfComplex(RV.getComplexVal(), SrcLV, /*init*/ true);
2383 }
Mike Stump1eb44332009-09-09 15:08:12 +00002384 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002385 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002386
Chris Lattner117e3f42010-07-30 04:02:24 +00002387 // If the value is offset in memory, apply the offset now.
2388 if (unsigned Offs = ArgInfo.getDirectOffset()) {
2389 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
2390 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002391 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002392 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
2393
2394 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002395
Chris Lattnerce700162010-06-28 23:44:11 +00002396 // If the coerce-to type is a first class aggregate, we flatten it and
2397 // pass the elements. Either way is semantically identical, but fast-isel
2398 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002399 if (llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00002400 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chandler Carruthf82232c2012-10-10 11:29:08 +00002401 llvm::Type *SrcTy =
2402 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
2403 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
2404 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
2405
2406 // If the source type is smaller than the destination type of the
2407 // coerce-to logic, copy the source value into a temp alloca the size
2408 // of the destination type to allow loading all of it. The bits past
2409 // the source value are left undef.
2410 if (SrcSize < DstSize) {
2411 llvm::AllocaInst *TempAlloca
2412 = CreateTempAlloca(STy, SrcPtr->getName() + ".coerce");
2413 Builder.CreateMemCpy(TempAlloca, SrcPtr, SrcSize, 0);
2414 SrcPtr = TempAlloca;
2415 } else {
2416 SrcPtr = Builder.CreateBitCast(SrcPtr,
2417 llvm::PointerType::getUnqual(STy));
2418 }
2419
Chris Lattner92826882010-07-05 20:41:41 +00002420 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2421 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00002422 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
2423 // We don't know what we're loading from.
2424 LI->setAlignment(1);
2425 Args.push_back(LI);
Chris Lattner70855442011-07-12 04:46:18 +00002426
2427 // Validate argument match.
2428 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner309c59f2010-06-29 00:06:42 +00002429 }
Chris Lattnerce700162010-06-28 23:44:11 +00002430 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00002431 // In the simple case, just pass the coerced loaded value.
2432 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2433 *this));
Chris Lattner70855442011-07-12 04:46:18 +00002434
2435 // Validate argument match.
2436 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattnerce700162010-06-28 23:44:11 +00002437 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002438
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002439 break;
2440 }
2441
Daniel Dunbar56273772008-09-17 00:51:38 +00002442 case ABIArgInfo::Expand:
Chris Lattner811bf362011-07-12 06:29:11 +00002443 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattner70855442011-07-12 04:46:18 +00002444 IRArgNo = Args.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00002445 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002446 }
2447 }
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Reid Kleckner9b601952013-06-21 12:45:15 +00002449 if (!CallArgs.getCleanupsToDeactivate().empty())
2450 deactivateArgCleanupsBeforeCall(*this, CallArgs);
2451
Chris Lattner5db7ae52009-06-13 00:26:38 +00002452 // If the callee is a bitcast of a function to a varargs pointer to function
2453 // type, check to see if we can remove the bitcast. This handles some cases
2454 // with unprototyped functions.
2455 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
2456 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002457 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
2458 llvm::FunctionType *CurFT =
Chris Lattner5db7ae52009-06-13 00:26:38 +00002459 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002460 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Chris Lattner5db7ae52009-06-13 00:26:38 +00002462 if (CE->getOpcode() == llvm::Instruction::BitCast &&
2463 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00002464 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00002465 ActualFT->getNumParams() == Args.size() &&
2466 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00002467 bool ArgsMatch = true;
2468 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
2469 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
2470 ArgsMatch = false;
2471 break;
2472 }
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Chris Lattner5db7ae52009-06-13 00:26:38 +00002474 // Strip the cast if we can get away with it. This is a nice cleanup,
2475 // but also allows us to inline the function at -O0 if it is marked
2476 // always_inline.
2477 if (ArgsMatch)
2478 Callee = CalleeF;
2479 }
2480 }
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002482 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00002483 CodeGen::AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +00002484 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
2485 CallingConv, true);
Bill Wendling785b7782012-12-07 23:17:26 +00002486 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
Bill Wendling94236e72013-02-22 00:13:35 +00002487 AttributeList);
Mike Stump1eb44332009-09-09 15:08:12 +00002488
John McCallf1549f62010-07-06 01:34:17 +00002489 llvm::BasicBlock *InvokeDest = 0;
Bill Wendling01ad9542012-12-30 10:32:17 +00002490 if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
2491 llvm::Attribute::NoUnwind))
John McCallf1549f62010-07-06 01:34:17 +00002492 InvokeDest = getInvokeDest();
2493
Daniel Dunbard14151d2009-03-02 04:32:35 +00002494 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00002495 if (!InvokeDest) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00002496 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002497 } else {
2498 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad4c7d9f12011-07-15 08:37:34 +00002499 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002500 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002501 }
Chris Lattnerce933992010-06-29 16:40:28 +00002502 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00002503 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002504
Daniel Dunbard14151d2009-03-02 04:32:35 +00002505 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00002506 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00002507
Dan Gohmanb49bd272012-02-16 00:57:37 +00002508 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
2509 // optimizer it can aggressively ignore unwind edges.
David Blaikie4e4d0842012-03-11 07:00:24 +00002510 if (CGM.getLangOpts().ObjCAutoRefCount)
Dan Gohmanb49bd272012-02-16 00:57:37 +00002511 AddObjCARCExceptionMetadata(CS.getInstruction());
2512
Daniel Dunbard14151d2009-03-02 04:32:35 +00002513 // If the call doesn't return, finish the basic block and clear the
2514 // insertion point; this allows the rest of IRgen to discard
2515 // unreachable code.
2516 if (CS.doesNotReturn()) {
2517 Builder.CreateUnreachable();
2518 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Mike Stumpf5408fe2009-05-16 07:57:57 +00002520 // FIXME: For now, emit a dummy basic block because expr emitters in
2521 // generally are not ready to handle emitting expressions at unreachable
2522 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00002523 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Daniel Dunbard14151d2009-03-02 04:32:35 +00002525 // Return a reasonable RValue.
2526 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002527 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00002528
2529 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00002530 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002531 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002532
John McCallf85e1932011-06-15 23:02:42 +00002533 // Emit any writebacks immediately. Arguably this should happen
2534 // after any return-value munging.
2535 if (CallArgs.hasWritebacks())
2536 emitWritebacks(*this, CallArgs);
2537
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002538 switch (RetAI.getKind()) {
John McCall9d232c82013-03-07 21:37:08 +00002539 case ABIArgInfo::Indirect:
2540 return convertTempToRValue(Args[0], RetTy);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002541
Daniel Dunbar11434922009-01-26 21:26:08 +00002542 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00002543 // If we are ignoring an argument that had a result, make sure to
2544 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00002545 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002546
Chris Lattner800588f2010-07-29 06:26:06 +00002547 case ABIArgInfo::Extend:
2548 case ABIArgInfo::Direct: {
Chris Lattner6af13f32011-07-13 03:59:32 +00002549 llvm::Type *RetIRTy = ConvertType(RetTy);
2550 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
John McCall9d232c82013-03-07 21:37:08 +00002551 switch (getEvaluationKind(RetTy)) {
2552 case TEK_Complex: {
Chris Lattner800588f2010-07-29 06:26:06 +00002553 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2554 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2555 return RValue::getComplex(std::make_pair(Real, Imag));
2556 }
John McCall9d232c82013-03-07 21:37:08 +00002557 case TEK_Aggregate: {
Chris Lattner800588f2010-07-29 06:26:06 +00002558 llvm::Value *DestPtr = ReturnValue.getValue();
2559 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00002560
Chris Lattner800588f2010-07-29 06:26:06 +00002561 if (!DestPtr) {
2562 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
2563 DestIsVolatile = false;
2564 }
Eli Friedmanbadea572011-05-17 21:08:01 +00002565 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00002566 return RValue::getAggregate(DestPtr);
2567 }
John McCall9d232c82013-03-07 21:37:08 +00002568 case TEK_Scalar: {
2569 // If the argument doesn't match, perform a bitcast to coerce it. This
2570 // can happen due to trivial type mismatches.
2571 llvm::Value *V = CI;
2572 if (V->getType() != RetIRTy)
2573 V = Builder.CreateBitCast(V, RetIRTy);
2574 return RValue::get(V);
2575 }
2576 }
2577 llvm_unreachable("bad evaluation kind");
Chris Lattner800588f2010-07-29 06:26:06 +00002578 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002579
Anders Carlssond2490a92009-12-24 20:40:36 +00002580 llvm::Value *DestPtr = ReturnValue.getValue();
2581 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002582
Anders Carlssond2490a92009-12-24 20:40:36 +00002583 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00002584 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00002585 DestIsVolatile = false;
2586 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002587
Chris Lattner117e3f42010-07-30 04:02:24 +00002588 // If the value is offset in memory, apply the offset now.
2589 llvm::Value *StorePtr = DestPtr;
2590 if (unsigned Offs = RetAI.getDirectOffset()) {
2591 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
2592 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002593 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00002594 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
2595 }
2596 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002597
John McCall9d232c82013-03-07 21:37:08 +00002598 return convertTempToRValue(DestPtr, RetTy);
Daniel Dunbar639ffe42008-09-10 07:04:09 +00002599 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002600
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002601 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00002602 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002603 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002604
David Blaikieb219cfc2011-09-23 05:06:16 +00002605 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002606}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00002607
2608/* VarArg handling */
2609
2610llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2611 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2612}