blob: 7387fa7096d5f0724a03d8f1686cb5425e55b0c3 [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"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chris Lattnerce933992010-06-29 16:40:28 +000017#include "ABIInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000019#include "CodeGenModule.h"
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +000020#include "clang/Basic/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 Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Devang Pateld0646bd2008-09-24 01:01:36 +000025#include "llvm/Attributes.h"
Daniel Dunbard14151d2009-03-02 04:32:35 +000026#include "llvm/Support/CallSite.h"
Daniel Dunbar54d1ccb2009-01-27 01:36:03 +000027#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000028#include "llvm/InlineAsm.h"
Eli Friedman97cb5a42011-06-15 22:09:18 +000029#include "llvm/Transforms/Utils/Local.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000030using namespace clang;
31using namespace CodeGen;
32
33/***/
34
John McCall04a67a62010-02-05 21:31:56 +000035static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
36 switch (CC) {
37 default: return llvm::CallingConv::C;
38 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
39 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
Douglas Gregorf813a2c2010-05-18 16:57:00 +000040 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
Anton Korobeynikov414d8962011-04-14 20:06:49 +000041 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
42 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Dawn Perchik52fc3142010-09-03 01:29:35 +000043 // TODO: add support for CC_X86Pascal to llvm
John McCall04a67a62010-02-05 21:31:56 +000044 }
45}
46
John McCall0b0ef0a2010-02-24 07:14:12 +000047/// Derives the 'this' type for codegen purposes, i.e. ignoring method
48/// qualification.
49/// FIXME: address space qualification?
John McCallead608a2010-02-26 00:48:12 +000050static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
51 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
52 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000053}
54
John McCall0b0ef0a2010-02-24 07:14:12 +000055/// Returns the canonical formal type of the given C++ method.
John McCallead608a2010-02-26 00:48:12 +000056static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
57 return MD->getType()->getCanonicalTypeUnqualified()
58 .getAs<FunctionProtoType>();
John McCall0b0ef0a2010-02-24 07:14:12 +000059}
60
61/// Returns the "extra-canonicalized" return type, which discards
62/// qualifiers on the return type. Codegen doesn't care about them,
63/// and it makes ABI code a little easier to be able to assume that
64/// all parameter and return types are top-level unqualified.
John McCallead608a2010-02-26 00:48:12 +000065static CanQualType GetReturnType(QualType RetTy) {
66 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
John McCall0b0ef0a2010-02-24 07:14:12 +000067}
68
69const CGFunctionInfo &
Chris Lattner9cbe4f02011-07-09 17:41:47 +000070CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP) {
John McCallead608a2010-02-26 00:48:12 +000071 return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
72 llvm::SmallVector<CanQualType, 16>(),
Chris Lattner9cbe4f02011-07-09 17:41:47 +000073 FTNP->getExtInfo());
John McCall0b0ef0a2010-02-24 07:14:12 +000074}
75
76/// \param Args - contains any initial parameters besides those
77/// in the formal type
78static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT,
John McCallead608a2010-02-26 00:48:12 +000079 llvm::SmallVectorImpl<CanQualType> &ArgTys,
Chris Lattner9cbe4f02011-07-09 17:41:47 +000080 CanQual<FunctionProtoType> FTP) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +000081 // FIXME: Kill copy.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000082 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbar541b63b2009-02-02 23:23:47 +000083 ArgTys.push_back(FTP->getArgType(i));
John McCallead608a2010-02-26 00:48:12 +000084 CanQualType ResTy = FTP->getResultType().getUnqualifiedType();
Chris Lattner9cbe4f02011-07-09 17:41:47 +000085 return CGT.getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
John McCall0b0ef0a2010-02-24 07:14:12 +000086}
87
88const CGFunctionInfo &
Chris Lattner9cbe4f02011-07-09 17:41:47 +000089CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP) {
John McCallead608a2010-02-26 00:48:12 +000090 llvm::SmallVector<CanQualType, 16> ArgTys;
Chris Lattner9cbe4f02011-07-09 17:41:47 +000091 return ::getFunctionInfo(*this, ArgTys, FTP);
Daniel Dunbarbac7c252009-09-11 22:24:53 +000092}
93
John McCall04a67a62010-02-05 21:31:56 +000094static CallingConv getCallingConventionForDecl(const Decl *D) {
Daniel Dunbarbac7c252009-09-11 22:24:53 +000095 // Set the appropriate calling convention for the Function.
96 if (D->hasAttr<StdCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +000097 return CC_X86StdCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +000098
99 if (D->hasAttr<FastCallAttr>())
John McCall04a67a62010-02-05 21:31:56 +0000100 return CC_X86FastCall;
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000101
Douglas Gregorf813a2c2010-05-18 16:57:00 +0000102 if (D->hasAttr<ThisCallAttr>())
103 return CC_X86ThisCall;
104
Dawn Perchik52fc3142010-09-03 01:29:35 +0000105 if (D->hasAttr<PascalAttr>())
106 return CC_X86Pascal;
107
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000108 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
109 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
110
John McCall04a67a62010-02-05 21:31:56 +0000111 return CC_C;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000112}
113
Anders Carlsson375c31c2009-10-03 19:43:08 +0000114const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *RD,
115 const FunctionProtoType *FTP) {
John McCallead608a2010-02-26 00:48:12 +0000116 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall0b0ef0a2010-02-24 07:14:12 +0000117
Anders Carlsson375c31c2009-10-03 19:43:08 +0000118 // Add the 'this' pointer.
John McCall0b0ef0a2010-02-24 07:14:12 +0000119 ArgTys.push_back(GetThisType(Context, RD));
120
121 return ::getFunctionInfo(*this, ArgTys,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000122 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
Anders Carlsson375c31c2009-10-03 19:43:08 +0000123}
124
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000125const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
John McCallead608a2010-02-26 00:48:12 +0000126 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall0b0ef0a2010-02-24 07:14:12 +0000127
John McCallfc400282010-09-03 01:26:39 +0000128 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
129 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
130
Chris Lattner3eb67ca2009-05-12 20:27:19 +0000131 // Add the 'this' pointer unless this is a static method.
132 if (MD->isInstance())
John McCall0b0ef0a2010-02-24 07:14:12 +0000133 ArgTys.push_back(GetThisType(Context, MD->getParent()));
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000135 return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD));
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000136}
137
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000138const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDecl *D,
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000139 CXXCtorType Type) {
John McCallead608a2010-02-26 00:48:12 +0000140 llvm::SmallVector<CanQualType, 16> ArgTys;
John McCall0b0ef0a2010-02-24 07:14:12 +0000141 ArgTys.push_back(GetThisType(Context, D->getParent()));
John McCall4c40d982010-08-31 07:33:07 +0000142 CanQualType ResTy = Context.VoidTy;
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000143
John McCall4c40d982010-08-31 07:33:07 +0000144 TheCXXABI.BuildConstructorSignature(D, Type, ResTy, ArgTys);
John McCall0b0ef0a2010-02-24 07:14:12 +0000145
John McCall4c40d982010-08-31 07:33:07 +0000146 CanQual<FunctionProtoType> FTP = GetFormalType(D);
147
148 // Add the formal parameters.
149 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
150 ArgTys.push_back(FTP->getArgType(i));
151
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000152 return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000153}
154
155const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDecl *D,
156 CXXDtorType Type) {
John McCall4c40d982010-08-31 07:33:07 +0000157 llvm::SmallVector<CanQualType, 2> ArgTys;
John McCallead608a2010-02-26 00:48:12 +0000158 ArgTys.push_back(GetThisType(Context, D->getParent()));
John McCall4c40d982010-08-31 07:33:07 +0000159 CanQualType ResTy = Context.VoidTy;
John McCall0b0ef0a2010-02-24 07:14:12 +0000160
John McCall4c40d982010-08-31 07:33:07 +0000161 TheCXXABI.BuildDestructorSignature(D, Type, ResTy, ArgTys);
162
163 CanQual<FunctionProtoType> FTP = GetFormalType(D);
164 assert(FTP->getNumArgs() == 0 && "dtor with formal parameters");
165
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000166 return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
Anders Carlssonf6c56e22009-11-25 03:15:49 +0000167}
168
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000169const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Chris Lattner3eb67ca2009-05-12 20:27:19 +0000170 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +0000171 if (MD->isInstance())
172 return getFunctionInfo(MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000173
John McCallead608a2010-02-26 00:48:12 +0000174 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
175 assert(isa<FunctionType>(FTy));
John McCall0b0ef0a2010-02-24 07:14:12 +0000176 if (isa<FunctionNoProtoType>(FTy))
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000177 return getFunctionInfo(FTy.getAs<FunctionNoProtoType>());
John McCallead608a2010-02-26 00:48:12 +0000178 assert(isa<FunctionProtoType>(FTy));
179 return getFunctionInfo(FTy.getAs<FunctionProtoType>());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000180}
181
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000182const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
John McCallead608a2010-02-26 00:48:12 +0000183 llvm::SmallVector<CanQualType, 16> ArgTys;
184 ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getType()));
185 ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000186 // FIXME: Kill copy?
Chris Lattner20732162009-02-20 06:23:21 +0000187 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
John McCall0b0ef0a2010-02-24 07:14:12 +0000188 e = MD->param_end(); i != e; ++i) {
189 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
190 }
John McCallf85e1932011-06-15 23:02:42 +0000191
192 FunctionType::ExtInfo einfo;
193 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD));
194
195 if (getContext().getLangOptions().ObjCAutoRefCount &&
196 MD->hasAttr<NSReturnsRetainedAttr>())
197 einfo = einfo.withProducesResult(true);
198
199 return getFunctionInfo(GetReturnType(MD->getResultType()), ArgTys, einfo);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000200}
201
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000202const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) {
203 // FIXME: Do we need to handle ObjCMethodDecl?
204 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000205
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000206 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
207 return getFunctionInfo(CD, GD.getCtorType());
208
209 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
210 return getFunctionInfo(DD, GD.getDtorType());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000211
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000212 return getFunctionInfo(FD);
213}
214
Mike Stump1eb44332009-09-09 15:08:12 +0000215const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000216 const CallArgList &Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000217 const FunctionType::ExtInfo &Info) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000218 // FIXME: Kill copy.
John McCallead608a2010-02-26 00:48:12 +0000219 llvm::SmallVector<CanQualType, 16> ArgTys;
Mike Stump1eb44332009-09-09 15:08:12 +0000220 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar725ad312009-01-31 02:19:00 +0000221 i != e; ++i)
Eli Friedmanc6d07822011-05-02 18:05:27 +0000222 ArgTys.push_back(Context.getCanonicalParamType(i->Ty));
Rafael Espindola264ba482010-03-30 20:24:48 +0000223 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
Daniel Dunbar725ad312009-01-31 02:19:00 +0000224}
225
Mike Stump1eb44332009-09-09 15:08:12 +0000226const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000227 const FunctionArgList &Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000228 const FunctionType::ExtInfo &Info) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000229 // FIXME: Kill copy.
John McCallead608a2010-02-26 00:48:12 +0000230 llvm::SmallVector<CanQualType, 16> ArgTys;
Mike Stump1eb44332009-09-09 15:08:12 +0000231 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000232 i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000233 ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
Rafael Espindola264ba482010-03-30 20:24:48 +0000234 return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000235}
236
John McCalld26bc762011-03-09 04:27:21 +0000237const CGFunctionInfo &CodeGenTypes::getNullaryFunctionInfo() {
238 llvm::SmallVector<CanQualType, 1> args;
239 return getFunctionInfo(getContext().VoidTy, args, FunctionType::ExtInfo());
240}
241
John McCallead608a2010-02-26 00:48:12 +0000242const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
243 const llvm::SmallVectorImpl<CanQualType> &ArgTys,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000244 const FunctionType::ExtInfo &Info) {
John McCallead608a2010-02-26 00:48:12 +0000245#ifndef NDEBUG
246 for (llvm::SmallVectorImpl<CanQualType>::const_iterator
247 I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I)
248 assert(I->isCanonicalAsParam());
249#endif
250
Rafael Espindola425ef722010-03-30 22:15:11 +0000251 unsigned CC = ClangCallConvToLLVMCallConv(Info.getCC());
John McCall04a67a62010-02-05 21:31:56 +0000252
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000253 // Lookup or create unique function info.
254 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +0000255 CGFunctionInfo::Profile(ID, Info, ResTy,
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000256 ArgTys.begin(), ArgTys.end());
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000257
258 void *InsertPos = 0;
259 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
260 if (FI)
261 return *FI;
262
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000263 // Construct the function info.
John McCallf85e1932011-06-15 23:02:42 +0000264 FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getProducesResult(),
265 Info.getHasRegParm(), Info.getRegParm(), ResTy,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000266 ArgTys.data(), ArgTys.size());
Daniel Dunbar35e67d42009-02-05 00:00:23 +0000267 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000268
269 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000270 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000271
Chris Lattner800588f2010-07-29 06:26:06 +0000272 // Loop over all of the computed argument and return value info. If any of
273 // them are direct or extend without a specified coerce type, specify the
274 // default now.
275 ABIArgInfo &RetInfo = FI->getReturnInfo();
276 if (RetInfo.canHaveCoerceToType() && RetInfo.getCoerceToType() == 0)
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000277 RetInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000278
Chris Lattner800588f2010-07-29 06:26:06 +0000279 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
280 I != E; ++I)
281 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000282 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000283
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000284 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000285}
286
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000287CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
John McCallf85e1932011-06-15 23:02:42 +0000288 bool _NoReturn, bool returnsRetained,
289 bool _HasRegParm, unsigned _RegParm,
John McCallead608a2010-02-26 00:48:12 +0000290 CanQualType ResTy,
Chris Lattnerbb521142010-06-29 18:13:52 +0000291 const CanQualType *ArgTys,
292 unsigned NumArgTys)
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000293 : CallingConvention(_CallingConvention),
John McCall04a67a62010-02-05 21:31:56 +0000294 EffectiveCallingConvention(_CallingConvention),
John McCallf85e1932011-06-15 23:02:42 +0000295 NoReturn(_NoReturn), ReturnsRetained(returnsRetained),
296 HasRegParm(_HasRegParm), RegParm(_RegParm)
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000297{
Chris Lattnerbb521142010-06-29 18:13:52 +0000298 NumArgs = NumArgTys;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000299
Chris Lattnerce700162010-06-28 23:44:11 +0000300 // FIXME: Coallocate with the CGFunctionInfo object.
Chris Lattnerbb521142010-06-29 18:13:52 +0000301 Args = new ArgInfo[1 + NumArgTys];
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000302 Args[0].type = ResTy;
Chris Lattnerbb521142010-06-29 18:13:52 +0000303 for (unsigned i = 0; i != NumArgTys; ++i)
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000304 Args[1 + i].type = ArgTys[i];
305}
306
307/***/
308
John McCall42e06112011-05-15 02:19:42 +0000309void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000310 llvm::SmallVectorImpl<llvm::Type*> &expandedTypes) {
John McCall42e06112011-05-15 02:19:42 +0000311 const RecordType *RT = type->getAsStructureType();
Daniel Dunbar56273772008-09-17 00:51:38 +0000312 assert(RT && "Can only expand structure types.");
313 const RecordDecl *RD = RT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000314 assert(!RD->hasFlexibleArrayMember() &&
Daniel Dunbar56273772008-09-17 00:51:38 +0000315 "Cannot expand structure with flexible array.");
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000317 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
318 i != e; ++i) {
Daniel Dunbar56273772008-09-17 00:51:38 +0000319 const FieldDecl *FD = *i;
Mike Stump1eb44332009-09-09 15:08:12 +0000320 assert(!FD->isBitField() &&
Daniel Dunbar56273772008-09-17 00:51:38 +0000321 "Cannot expand structure with bit-field members.");
Mike Stump1eb44332009-09-09 15:08:12 +0000322
John McCall42e06112011-05-15 02:19:42 +0000323 QualType fieldType = FD->getType();
324 if (fieldType->isRecordType())
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000325 GetExpandedTypes(fieldType, expandedTypes);
Chris Lattnerdeabde22010-07-28 18:24:28 +0000326 else
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000327 expandedTypes.push_back(ConvertType(fieldType));
Daniel Dunbar56273772008-09-17 00:51:38 +0000328 }
329}
330
Mike Stump1eb44332009-09-09 15:08:12 +0000331llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000332CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
333 llvm::Function::arg_iterator AI) {
334 const RecordType *RT = Ty->getAsStructureType();
335 assert(RT && "Can only expand structure types.");
336
337 RecordDecl *RD = RT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338 assert(LV.isSimple() &&
339 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000340 llvm::Value *Addr = LV.getAddress();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000341 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
342 i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000343 FieldDecl *FD = *i;
Daniel Dunbar56273772008-09-17 00:51:38 +0000344 QualType FT = FD->getType();
345
346 // FIXME: What are the right qualifiers here?
Anders Carlssone6d2a532010-01-29 05:05:36 +0000347 LValue LV = EmitLValueForField(Addr, FD, 0);
Daniel Dunbar56273772008-09-17 00:51:38 +0000348 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
349 AI = ExpandTypeFromArgs(FT, LV, AI);
350 } else {
John McCall545d9962011-06-25 02:11:03 +0000351 EmitStoreThroughLValue(RValue::get(AI), LV);
Daniel Dunbar56273772008-09-17 00:51:38 +0000352 ++AI;
353 }
354 }
355
356 return AI;
357}
358
Mike Stump1eb44332009-09-09 15:08:12 +0000359void
360CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Daniel Dunbar56273772008-09-17 00:51:38 +0000361 llvm::SmallVector<llvm::Value*, 16> &Args) {
362 const RecordType *RT = Ty->getAsStructureType();
363 assert(RT && "Can only expand structure types.");
364
365 RecordDecl *RD = RT->getDecl();
366 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
367 llvm::Value *Addr = RV.getAggregateAddr();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000368 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
369 i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000370 FieldDecl *FD = *i;
Daniel Dunbar56273772008-09-17 00:51:38 +0000371 QualType FT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Daniel Dunbar56273772008-09-17 00:51:38 +0000373 // FIXME: What are the right qualifiers here?
Anders Carlssone6d2a532010-01-29 05:05:36 +0000374 LValue LV = EmitLValueForField(Addr, FD, 0);
Daniel Dunbar56273772008-09-17 00:51:38 +0000375 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
376 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
377 } else {
John McCall545d9962011-06-25 02:11:03 +0000378 RValue RV = EmitLoadOfLValue(LV);
Mike Stump1eb44332009-09-09 15:08:12 +0000379 assert(RV.isScalar() &&
Daniel Dunbar56273772008-09-17 00:51:38 +0000380 "Unexpected non-scalar rvalue during struct expansion.");
381 Args.push_back(RV.getScalarVal());
382 }
383 }
384}
385
Chris Lattnere7bb7772010-06-27 06:04:18 +0000386/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-06-27 05:56:15 +0000387/// accessing some number of bytes out of it, try to gep into the struct to get
388/// at its inner goodness. Dive as deep as possible without entering an element
389/// with an in-memory size smaller than DstSize.
390static llvm::Value *
Chris Lattnere7bb7772010-06-27 06:04:18 +0000391EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
392 const llvm::StructType *SrcSTy,
393 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000394 // We can't dive into a zero-element struct.
395 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000396
Chris Lattner08dd2a02010-06-27 05:56:15 +0000397 const llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000398
Chris Lattner08dd2a02010-06-27 05:56:15 +0000399 // If the first elt is at least as large as what we're looking for, or if the
400 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000401 uint64_t FirstEltSize =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000402 CGF.CGM.getTargetData().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000403 if (FirstEltSize < DstSize &&
Chris Lattner08dd2a02010-06-27 05:56:15 +0000404 FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy))
405 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000406
Chris Lattner08dd2a02010-06-27 05:56:15 +0000407 // GEP into the first element.
408 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000409
Chris Lattner08dd2a02010-06-27 05:56:15 +0000410 // If the first element is a struct, recurse.
411 const llvm::Type *SrcTy =
412 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
413 if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000414 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000415
416 return SrcPtr;
417}
418
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000419/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
420/// are either integers or pointers. This does a truncation of the value if it
421/// is too large or a zero extension if it is too small.
422static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
423 const llvm::Type *Ty,
424 CodeGenFunction &CGF) {
425 if (Val->getType() == Ty)
426 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000427
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000428 if (isa<llvm::PointerType>(Val->getType())) {
429 // If this is Pointer->Pointer avoid conversion to and from int.
430 if (isa<llvm::PointerType>(Ty))
431 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000432
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000433 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000434 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000435 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000436
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000437 const llvm::Type *DestIntTy = Ty;
438 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000439 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000440
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000441 if (Val->getType() != DestIntTy)
442 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000443
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000444 if (isa<llvm::PointerType>(Ty))
445 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
446 return Val;
447}
448
Chris Lattner08dd2a02010-06-27 05:56:15 +0000449
450
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000451/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
452/// a pointer to an object of type \arg Ty.
453///
454/// This safely handles the case when the src type is smaller than the
455/// destination type; in this situation the values of bits which not
456/// present in the src are undefined.
457static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
458 const llvm::Type *Ty,
459 CodeGenFunction &CGF) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 const llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000461 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000462
Chris Lattner6ae00692010-06-28 22:51:39 +0000463 // If SrcTy and Ty are the same, just do a load.
464 if (SrcTy == Ty)
465 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000466
Duncan Sands9408c452009-05-09 07:08:47 +0000467 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000468
Chris Lattner08dd2a02010-06-27 05:56:15 +0000469 if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000470 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000471 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
472 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000473
Chris Lattner08dd2a02010-06-27 05:56:15 +0000474 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000475
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000476 // If the source and destination are integer or pointer types, just do an
477 // extension or truncation to the desired type.
478 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
479 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
480 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
481 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
482 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000483
Daniel Dunbarb225be42009-02-03 05:59:18 +0000484 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000485 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000486 // Generally SrcSize is never greater than DstSize, since this means we are
487 // losing bits. However, this can happen in cases where the structure has
488 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000489 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000490 // FIXME: Assert that we aren't truncating non-padding bits when have access
491 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000492 llvm::Value *Casted =
493 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000494 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
495 // FIXME: Use better alignment / avoid requiring aligned load.
496 Load->setAlignment(1);
497 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000498 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000499
Chris Lattner35b21b82010-06-27 01:06:27 +0000500 // Otherwise do coercion through memory. This is stupid, but
501 // simple.
502 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
503 llvm::Value *Casted =
504 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
505 llvm::StoreInst *Store =
506 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
507 // FIXME: Use better alignment / avoid requiring aligned store.
508 Store->setAlignment(1);
509 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000510}
511
Eli Friedmanbadea572011-05-17 21:08:01 +0000512// Function to store a first-class aggregate into memory. We prefer to
513// store the elements rather than the aggregate to be more friendly to
514// fast-isel.
515// FIXME: Do we need to recurse here?
516static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
517 llvm::Value *DestPtr, bool DestIsVolatile,
518 bool LowAlignment) {
519 // Prefer scalar stores to first-class aggregate stores.
520 if (const llvm::StructType *STy =
521 dyn_cast<llvm::StructType>(Val->getType())) {
522 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
523 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
524 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
525 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
526 DestIsVolatile);
527 if (LowAlignment)
528 SI->setAlignment(1);
529 }
530 } else {
531 CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
532 }
533}
534
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000535/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
536/// where the source and destination may have different types.
537///
538/// This safely handles the case when the src type is larger than the
539/// destination type; the upper bits of the src will be lost.
540static void CreateCoercedStore(llvm::Value *Src,
541 llvm::Value *DstPtr,
Anders Carlssond2490a92009-12-24 20:40:36 +0000542 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000543 CodeGenFunction &CGF) {
544 const llvm::Type *SrcTy = Src->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000545 const llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000546 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000547 if (SrcTy == DstTy) {
548 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
549 return;
550 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000551
Chris Lattner6ae00692010-06-28 22:51:39 +0000552 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000553
Chris Lattnere7bb7772010-06-27 06:04:18 +0000554 if (const llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
555 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
556 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
557 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000558
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000559 // If the source and destination are integer or pointer types, just do an
560 // extension or truncation to the desired type.
561 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
562 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
563 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
564 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
565 return;
566 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000567
Duncan Sands9408c452009-05-09 07:08:47 +0000568 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000569
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000570 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000571 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000572 llvm::Value *Casted =
573 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000574 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000575 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000576 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000577 // Otherwise do coercion through memory. This is stupid, but
578 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000579
580 // Generally SrcSize is never greater than DstSize, since this means we are
581 // losing bits. However, this can happen in cases where the structure has
582 // additional padding, for example due to a user specified alignment.
583 //
584 // FIXME: Assert that we aren't truncating non-padding bits when have access
585 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000586 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
587 CGF.Builder.CreateStore(Src, Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000588 llvm::Value *Casted =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000589 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000590 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
591 // FIXME: Use better alignment / avoid requiring aligned load.
592 Load->setAlignment(1);
Anders Carlssond2490a92009-12-24 20:40:36 +0000593 CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000594 }
595}
596
Daniel Dunbar56273772008-09-17 00:51:38 +0000597/***/
598
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000599bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000600 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000601}
602
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000603bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
604 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
605 switch (BT->getKind()) {
606 default:
607 return false;
608 case BuiltinType::Float:
609 return getContext().Target.useObjCFPRetForRealType(TargetInfo::Float);
610 case BuiltinType::Double:
611 return getContext().Target.useObjCFPRetForRealType(TargetInfo::Double);
612 case BuiltinType::LongDouble:
613 return getContext().Target.useObjCFPRetForRealType(
614 TargetInfo::LongDouble);
615 }
616 }
617
618 return false;
619}
620
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000621llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallc0bf4622010-02-23 00:48:20 +0000622 const CGFunctionInfo &FI = getFunctionInfo(GD);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000623
John McCallc0bf4622010-02-23 00:48:20 +0000624 // For definition purposes, don't consider a K&R function variadic.
625 bool Variadic = false;
626 if (const FunctionProtoType *FPT =
627 cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>())
628 Variadic = FPT->isVariadic();
629
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000630 return GetFunctionType(FI, Variadic);
John McCallc0bf4622010-02-23 00:48:20 +0000631}
632
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000633llvm::FunctionType *
634CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool isVariadic) {
635 llvm::SmallVector<llvm::Type*, 8> argTypes;
John McCall42e06112011-05-15 02:19:42 +0000636 const llvm::Type *resultType = 0;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000637
John McCall42e06112011-05-15 02:19:42 +0000638 const ABIArgInfo &retAI = FI.getReturnInfo();
639 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000640 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000641 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000642
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000643 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000644 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000645 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000646 break;
647
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000648 case ABIArgInfo::Indirect: {
John McCall42e06112011-05-15 02:19:42 +0000649 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
650 resultType = llvm::Type::getVoidTy(getLLVMContext());
651
652 QualType ret = FI.getReturnType();
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000653 const llvm::Type *ty = ConvertType(ret);
John McCall42e06112011-05-15 02:19:42 +0000654 unsigned addressSpace = Context.getTargetAddressSpace(ret);
655 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000656 break;
657 }
658
Daniel Dunbar11434922009-01-26 21:26:08 +0000659 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000660 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000661 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000662 }
Mike Stump1eb44332009-09-09 15:08:12 +0000663
664 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000665 ie = FI.arg_end(); it != ie; ++it) {
John McCall42e06112011-05-15 02:19:42 +0000666 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000667
John McCall42e06112011-05-15 02:19:42 +0000668 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +0000669 case ABIArgInfo::Ignore:
670 break;
671
Chris Lattner800588f2010-07-29 06:26:06 +0000672 case ABIArgInfo::Indirect: {
673 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000674 const llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall42e06112011-05-15 02:19:42 +0000675 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +0000676 break;
677 }
678
679 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +0000680 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-06-28 23:44:11 +0000681 // If the coerce-to type is a first class aggregate, flatten it. Either
682 // way is semantically identical, but fast-isel and the optimizer
683 // generally likes scalar values better than FCAs.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000684 llvm::Type *argType = argAI.getCoerceToType();
John McCall42e06112011-05-15 02:19:42 +0000685 if (const llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
686 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
687 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +0000688 } else {
John McCall42e06112011-05-15 02:19:42 +0000689 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +0000690 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000691 break;
Chris Lattner1ed72672010-07-29 06:44:09 +0000692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000694 case ABIArgInfo::Expand:
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000695 GetExpandedTypes(it->type, argTypes);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000696 break;
697 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000698 }
699
John McCall42e06112011-05-15 02:19:42 +0000700 return llvm::FunctionType::get(resultType, argTypes, isVariadic);
Daniel Dunbar3913f182008-09-09 23:48:28 +0000701}
702
John McCall4c40d982010-08-31 07:33:07 +0000703const llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
704 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000705 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000706
Chris Lattnerf742eb02011-07-10 00:18:59 +0000707 if (!isFuncTypeConvertible(FPT))
708 return llvm::StructType::get(getLLVMContext());
709
710 const CGFunctionInfo *Info;
711 if (isa<CXXDestructorDecl>(MD))
712 Info = &getFunctionInfo(cast<CXXDestructorDecl>(MD), GD.getDtorType());
713 else
714 Info = &getFunctionInfo(MD);
715 return GetFunctionType(*Info, FPT->isVariadic());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000716}
717
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000718void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +0000719 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000720 AttributeListType &PAL,
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000721 unsigned &CallingConv) {
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000722 unsigned FuncAttrs = 0;
Devang Patela2c69122008-09-26 22:53:57 +0000723 unsigned RetAttrs = 0;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000724
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000725 CallingConv = FI.getEffectiveCallingConvention();
726
John McCall04a67a62010-02-05 21:31:56 +0000727 if (FI.isNoReturn())
728 FuncAttrs |= llvm::Attribute::NoReturn;
729
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000730 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000731 if (TargetDecl) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000732 if (TargetDecl->hasAttr<NoThrowAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +0000733 FuncAttrs |= llvm::Attribute::NoUnwind;
John McCall9c0c1f32010-07-08 06:48:12 +0000734 else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
735 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000736 if (FPT && FPT->isNothrow(getContext()))
John McCall9c0c1f32010-07-08 06:48:12 +0000737 FuncAttrs |= llvm::Attribute::NoUnwind;
738 }
739
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000740 if (TargetDecl->hasAttr<NoReturnAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +0000741 FuncAttrs |= llvm::Attribute::NoReturn;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000742 if (TargetDecl->hasAttr<ConstAttr>())
Anders Carlsson232eb7d2008-10-05 23:32:53 +0000743 FuncAttrs |= llvm::Attribute::ReadNone;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000744 else if (TargetDecl->hasAttr<PureAttr>())
Daniel Dunbar64c2e072009-04-10 22:14:52 +0000745 FuncAttrs |= llvm::Attribute::ReadOnly;
Ryan Flynn76168e22009-08-09 20:07:29 +0000746 if (TargetDecl->hasAttr<MallocAttr>())
747 RetAttrs |= llvm::Attribute::NoAlias;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000748 }
749
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000750 if (CodeGenOpts.OptimizeSize)
Daniel Dunbar7ab1c3e2009-10-27 19:48:08 +0000751 FuncAttrs |= llvm::Attribute::OptimizeForSize;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000752 if (CodeGenOpts.DisableRedZone)
Devang Patel24095da2009-06-04 23:32:02 +0000753 FuncAttrs |= llvm::Attribute::NoRedZone;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000754 if (CodeGenOpts.NoImplicitFloat)
Devang Patelacebb392009-06-05 22:05:48 +0000755 FuncAttrs |= llvm::Attribute::NoImplicitFloat;
Devang Patel24095da2009-06-04 23:32:02 +0000756
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000757 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000758 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000759 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000760 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000761 case ABIArgInfo::Extend:
Chris Lattner2eb9cdd2010-07-28 23:46:15 +0000762 if (RetTy->hasSignedIntegerRepresentation())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000763 RetAttrs |= llvm::Attribute::SExt;
Chris Lattner2eb9cdd2010-07-28 23:46:15 +0000764 else if (RetTy->hasUnsignedIntegerRepresentation())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000765 RetAttrs |= llvm::Attribute::ZExt;
Chris Lattner800588f2010-07-29 06:26:06 +0000766 break;
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000767 case ABIArgInfo::Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000768 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000769 break;
770
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000771 case ABIArgInfo::Indirect:
Mike Stump1eb44332009-09-09 15:08:12 +0000772 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Chris Lattnerfb97cf22010-04-20 05:44:43 +0000773 llvm::Attribute::StructRet));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000774 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +0000775 // sret disables readnone and readonly
776 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
777 llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000778 break;
779
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000780 case ABIArgInfo::Expand:
Mike Stump1eb44332009-09-09 15:08:12 +0000781 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000782 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000783
Devang Patela2c69122008-09-26 22:53:57 +0000784 if (RetAttrs)
785 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000786
Daniel Dunbar17d3fea2011-02-09 17:54:19 +0000787 // FIXME: RegParm should be reduced in case of global register variable.
Eli Friedmana49218e2011-04-09 08:18:08 +0000788 signed RegParm;
789 if (FI.getHasRegParm())
790 RegParm = FI.getRegParm();
791 else
Daniel Dunbar17d3fea2011-02-09 17:54:19 +0000792 RegParm = CodeGenOpts.NumRegisterParameters;
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000793
794 unsigned PointerWidth = getContext().Target.getPointerWidth(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000795 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000796 ie = FI.arg_end(); it != ie; ++it) {
797 QualType ParamType = it->type;
798 const ABIArgInfo &AI = it->info;
Devang Patel761d7f72008-09-25 21:02:23 +0000799 unsigned Attributes = 0;
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000800
John McCalld8e10d22010-03-27 00:47:27 +0000801 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
802 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +0000803 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000804 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +0000805 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000806 if (ParamType->isSignedIntegerOrEnumerationType())
Chris Lattner800588f2010-07-29 06:26:06 +0000807 Attributes |= llvm::Attribute::SExt;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000808 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Chris Lattner800588f2010-07-29 06:26:06 +0000809 Attributes |= llvm::Attribute::ZExt;
810 // FALL THROUGH
811 case ABIArgInfo::Direct:
812 if (RegParm > 0 &&
813 (ParamType->isIntegerType() || ParamType->isPointerType())) {
814 RegParm -=
815 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
816 if (RegParm >= 0)
817 Attributes |= llvm::Attribute::InReg;
818 }
819 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000820
Chris Lattnerce700162010-06-28 23:44:11 +0000821 if (const llvm::StructType *STy =
Chris Lattner800588f2010-07-29 06:26:06 +0000822 dyn_cast<llvm::StructType>(AI.getCoerceToType()))
823 Index += STy->getNumElements()-1; // 1 will be added below.
824 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000825
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000826 case ABIArgInfo::Indirect:
Anders Carlsson0a8f8472009-09-16 15:53:40 +0000827 if (AI.getIndirectByVal())
828 Attributes |= llvm::Attribute::ByVal;
829
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000830 Attributes |=
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000831 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar0ac86f02009-03-18 19:51:01 +0000832 // byval disables readnone and readonly.
833 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
834 llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000835 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000836
Daniel Dunbar11434922009-01-26 21:26:08 +0000837 case ABIArgInfo::Ignore:
838 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000839 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +0000840
Daniel Dunbar56273772008-09-17 00:51:38 +0000841 case ABIArgInfo::Expand: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000842 llvm::SmallVector<llvm::Type*, 8> types;
Mike Stumpf5408fe2009-05-16 07:57:57 +0000843 // FIXME: This is rather inefficient. Do we ever actually need to do
844 // anything here? The result should be just reconstructed on the other
845 // side, so extension should be a non-issue.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000846 getTypes().GetExpandedTypes(ParamType, types);
John McCall42e06112011-05-15 02:19:42 +0000847 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +0000848 continue;
849 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Devang Patel761d7f72008-09-25 21:02:23 +0000852 if (Attributes)
853 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar56273772008-09-17 00:51:38 +0000854 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000855 }
Devang Patela2c69122008-09-26 22:53:57 +0000856 if (FuncAttrs)
857 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000858}
859
John McCalld26bc762011-03-09 04:27:21 +0000860/// An argument came in as a promoted argument; demote it back to its
861/// declared type.
862static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
863 const VarDecl *var,
864 llvm::Value *value) {
865 const llvm::Type *varType = CGF.ConvertType(var->getType());
866
867 // This can happen with promotions that actually don't change the
868 // underlying type, like the enum promotions.
869 if (value->getType() == varType) return value;
870
871 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
872 && "unexpected promotion type");
873
874 if (isa<llvm::IntegerType>(varType))
875 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
876
877 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
878}
879
Daniel Dunbar88b53962009-02-02 22:03:45 +0000880void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
881 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000882 const FunctionArgList &Args) {
John McCall0cfeb632009-07-28 01:00:58 +0000883 // If this is an implicit-return-zero function, go ahead and
884 // initialize the return value. TODO: it might be nice to have
885 // a more general mechanism for this that didn't require synthesized
886 // return statements.
Chris Lattner121b3fa2010-07-05 20:21:00 +0000887 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +0000888 if (FD->hasImplicitReturnZero()) {
889 QualType RetTy = FD->getResultType().getUnqualifiedType();
890 const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000891 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +0000892 Builder.CreateStore(Zero, ReturnValue);
893 }
894 }
895
Mike Stumpf5408fe2009-05-16 07:57:57 +0000896 // FIXME: We no longer need the types from FunctionArgList; lift up and
897 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +0000898
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000899 // Emit allocs for param decls. Give the LLVM Argument nodes names.
900 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000902 // Name the struct return argument.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000903 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000904 AI->setName("agg.result");
905 ++AI;
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +0000908 assert(FI.arg_size() == Args.size() &&
909 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +0000910 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000911 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +0000912 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
913 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +0000914 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000915 QualType Ty = info_it->type;
916 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000917
John McCalld26bc762011-03-09 04:27:21 +0000918 bool isPromoted =
919 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
920
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000921 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +0000922 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +0000923 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000924
Daniel Dunbar1f745982009-02-05 09:16:39 +0000925 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000926 // Aggregates and complex variables are accessed by reference. All we
927 // need to do is realign the value, if requested
928 if (ArgI.getIndirectRealign()) {
929 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
930
931 // Copy from the incoming argument pointer to the temporary with the
932 // appropriate alignment.
933 //
934 // FIXME: We should have a common utility for generating an aggregate
935 // copy.
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000936 const llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +0000937 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +0000938 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
939 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
940 Builder.CreateMemCpy(Dst,
941 Src,
Ken Dyckfe710082011-01-19 01:58:38 +0000942 llvm::ConstantInt::get(IntPtrTy,
943 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000944 ArgI.getIndirectAlign(),
945 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000946 V = AlignedTemp;
947 }
Daniel Dunbar1f745982009-02-05 09:16:39 +0000948 } else {
949 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +0000950 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
951 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalld26bc762011-03-09 04:27:21 +0000952
953 if (isPromoted)
954 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar1f745982009-02-05 09:16:39 +0000955 }
Devang Patel093ac462011-03-03 20:13:15 +0000956 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar1f745982009-02-05 09:16:39 +0000957 break;
958 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000959
960 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000961 case ABIArgInfo::Direct: {
Chris Lattner800588f2010-07-29 06:26:06 +0000962 // If we have the trivial case, handle it with no muss and fuss.
963 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +0000964 ArgI.getCoerceToType() == ConvertType(Ty) &&
965 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +0000966 assert(AI != Fn->arg_end() && "Argument mismatch!");
967 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000968
John McCalld8e10d22010-03-27 00:47:27 +0000969 if (Arg->getType().isRestrictQualified())
970 AI->addAttr(llvm::Attribute::NoAlias);
971
John McCalld26bc762011-03-09 04:27:21 +0000972 if (isPromoted)
973 V = emitArgumentDemotion(*this, Arg, V);
974
Devang Patel093ac462011-03-03 20:13:15 +0000975 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +0000976 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +0000977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner121b3fa2010-07-05 20:21:00 +0000979 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, "coerce");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000980
Chris Lattnerdeabde22010-07-28 18:24:28 +0000981 // The alignment we need to use is the max of the requested alignment for
982 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000983 unsigned AlignmentToUse =
John McCalld16c2cf2011-02-08 08:22:06 +0000984 CGM.getTargetData().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +0000985 AlignmentToUse = std::max(AlignmentToUse,
986 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000987
Chris Lattnerdeabde22010-07-28 18:24:28 +0000988 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +0000989 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +0000990 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000991
Chris Lattner117e3f42010-07-30 04:02:24 +0000992 // If the value is offset in memory, apply the offset now.
993 if (unsigned Offs = ArgI.getDirectOffset()) {
994 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
995 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000996 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +0000997 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
998 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000999
Chris Lattner309c59f2010-06-29 00:06:42 +00001000 // If the coerce-to type is a first class aggregate, we flatten it and
1001 // pass the elements. Either way is semantically identical, but fast-isel
1002 // and the optimizer generally likes scalar values better than FCAs.
1003 if (const llvm::StructType *STy =
1004 dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
Chris Lattner92826882010-07-05 20:41:41 +00001005 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001006
Chris Lattner92826882010-07-05 20:41:41 +00001007 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1008 assert(AI != Fn->arg_end() && "Argument mismatch!");
1009 AI->setName(Arg->getName() + ".coerce" + llvm::Twine(i));
1010 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1011 Builder.CreateStore(AI++, EltPtr);
Chris Lattner309c59f2010-06-29 00:06:42 +00001012 }
1013 } else {
1014 // Simple case, just do a coerced store of the argument into the alloca.
1015 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001016 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001017 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001018 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001019
1020
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001021 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001022 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001023 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalld26bc762011-03-09 04:27:21 +00001024 if (isPromoted)
1025 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001026 }
Devang Patel093ac462011-03-03 20:13:15 +00001027 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerce700162010-06-28 23:44:11 +00001028 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001029 }
Chris Lattner800588f2010-07-29 06:26:06 +00001030
1031 case ABIArgInfo::Expand: {
1032 // If this structure was expanded into multiple arguments then
1033 // we need to create a temporary and reconstruct it from the
1034 // arguments.
1035 llvm::Value *Temp = CreateMemTemp(Ty, Arg->getName() + ".addr");
Chris Lattner800588f2010-07-29 06:26:06 +00001036 llvm::Function::arg_iterator End =
Daniel Dunbar79c39282010-08-21 03:15:20 +00001037 ExpandTypeFromArgs(Ty, MakeAddrLValue(Temp, Ty), AI);
Devang Patel093ac462011-03-03 20:13:15 +00001038 EmitParmDecl(*Arg, Temp, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001039
1040 // Name the arguments used in expansion and increment AI.
1041 unsigned Index = 0;
1042 for (; AI != End; ++AI, ++Index)
1043 AI->setName(Arg->getName() + "." + llvm::Twine(Index));
1044 continue;
1045 }
1046
1047 case ABIArgInfo::Ignore:
1048 // Initialize the local variable appropriately.
1049 if (hasAggregateLLVMType(Ty))
Devang Patel093ac462011-03-03 20:13:15 +00001050 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001051 else
Devang Patel093ac462011-03-03 20:13:15 +00001052 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1053 ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001054
1055 // Skip increment, no matching LLVM parameter.
1056 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001057 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001058
1059 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001060 }
1061 assert(AI == Fn->arg_end() && "Argument mismatch!");
1062}
1063
John McCallf85e1932011-06-15 23:02:42 +00001064/// Try to emit a fused autorelease of a return result.
1065static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1066 llvm::Value *result) {
1067 // We must be immediately followed the cast.
1068 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1069 if (BB->empty()) return 0;
1070 if (&BB->back() != result) return 0;
1071
1072 const llvm::Type *resultType = result->getType();
1073
1074 // result is in a BasicBlock and is therefore an Instruction.
1075 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1076
1077 llvm::SmallVector<llvm::Instruction*,4> insnsToKill;
1078
1079 // Look for:
1080 // %generator = bitcast %type1* %generator2 to %type2*
1081 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1082 // We would have emitted this as a constant if the operand weren't
1083 // an Instruction.
1084 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1085
1086 // Require the generator to be immediately followed by the cast.
1087 if (generator->getNextNode() != bitcast)
1088 return 0;
1089
1090 insnsToKill.push_back(bitcast);
1091 }
1092
1093 // Look for:
1094 // %generator = call i8* @objc_retain(i8* %originalResult)
1095 // or
1096 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1097 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1098 if (!call) return 0;
1099
1100 bool doRetainAutorelease;
1101
1102 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1103 doRetainAutorelease = true;
1104 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1105 .objc_retainAutoreleasedReturnValue) {
1106 doRetainAutorelease = false;
1107
1108 // Look for an inline asm immediately preceding the call and kill it, too.
1109 llvm::Instruction *prev = call->getPrevNode();
1110 if (llvm::CallInst *asmCall = dyn_cast_or_null<llvm::CallInst>(prev))
1111 if (asmCall->getCalledValue()
1112 == CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker)
1113 insnsToKill.push_back(prev);
1114 } else {
1115 return 0;
1116 }
1117
1118 result = call->getArgOperand(0);
1119 insnsToKill.push_back(call);
1120
1121 // Keep killing bitcasts, for sanity. Note that we no longer care
1122 // about precise ordering as long as there's exactly one use.
1123 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1124 if (!bitcast->hasOneUse()) break;
1125 insnsToKill.push_back(bitcast);
1126 result = bitcast->getOperand(0);
1127 }
1128
1129 // Delete all the unnecessary instructions, from latest to earliest.
1130 for (llvm::SmallVectorImpl<llvm::Instruction*>::iterator
1131 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1132 (*i)->eraseFromParent();
1133
1134 // Do the fused retain/autorelease if we were asked to.
1135 if (doRetainAutorelease)
1136 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1137
1138 // Cast back to the result type.
1139 return CGF.Builder.CreateBitCast(result, resultType);
1140}
1141
1142/// Emit an ARC autorelease of the result of a function.
1143static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1144 llvm::Value *result) {
1145 // At -O0, try to emit a fused retain/autorelease.
1146 if (CGF.shouldUseFusedARCCalls())
1147 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1148 return fused;
1149
1150 return CGF.EmitARCAutoreleaseReturnValue(result);
1151}
1152
Chris Lattner35b21b82010-06-27 01:06:27 +00001153void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001154 // Functions with no result always return void.
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001155 if (ReturnValue == 0) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001156 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001157 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001158 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001159
Dan Gohman4751a532010-07-20 20:13:52 +00001160 llvm::DebugLoc RetDbgLoc;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001161 llvm::Value *RV = 0;
1162 QualType RetTy = FI.getReturnType();
1163 const ABIArgInfo &RetAI = FI.getReturnInfo();
1164
1165 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001166 case ABIArgInfo::Indirect: {
1167 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001168 if (RetTy->isAnyComplexType()) {
1169 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1170 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1171 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1172 // Do nothing; aggregrates get evaluated directly into the destination.
1173 } else {
1174 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001175 false, Alignment, RetTy);
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001176 }
1177 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001178 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001179
1180 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001181 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001182 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1183 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001184 // The internal return value temp always will have pointer-to-return-type
1185 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001186
Chris Lattner800588f2010-07-29 06:26:06 +00001187 // If the instruction right before the insertion point is a store to the
1188 // return value, we can elide the load, zap the store, and usually zap the
1189 // alloca.
1190 llvm::BasicBlock *InsertBB = Builder.GetInsertBlock();
1191 llvm::StoreInst *SI = 0;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001192 if (InsertBB->empty() ||
Chris Lattner800588f2010-07-29 06:26:06 +00001193 !(SI = dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
1194 SI->getPointerOperand() != ReturnValue || SI->isVolatile()) {
1195 RV = Builder.CreateLoad(ReturnValue);
1196 } else {
1197 // Get the stored value and nuke the now-dead store.
1198 RetDbgLoc = SI->getDebugLoc();
1199 RV = SI->getValueOperand();
1200 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001201
Chris Lattner800588f2010-07-29 06:26:06 +00001202 // If that was the only use of the return value, nuke it as well now.
1203 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1204 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1205 ReturnValue = 0;
1206 }
Chris Lattner35b21b82010-06-27 01:06:27 +00001207 }
Chris Lattner800588f2010-07-29 06:26:06 +00001208 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001209 llvm::Value *V = ReturnValue;
1210 // If the value is offset in memory, apply the offset now.
1211 if (unsigned Offs = RetAI.getDirectOffset()) {
1212 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1213 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001214 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001215 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1216 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001217
Chris Lattner117e3f42010-07-30 04:02:24 +00001218 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001219 }
John McCallf85e1932011-06-15 23:02:42 +00001220
1221 // In ARC, end functions that return a retainable type with a call
1222 // to objc_autoreleaseReturnValue.
1223 if (AutoreleaseResult) {
1224 assert(getLangOptions().ObjCAutoRefCount &&
1225 !FI.isReturnsRetained() &&
1226 RetTy->isObjCRetainableType());
1227 RV = emitAutoreleaseOfResult(*this, RV);
1228 }
1229
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001230 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001231
Chris Lattner800588f2010-07-29 06:26:06 +00001232 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001233 break;
1234
1235 case ABIArgInfo::Expand:
1236 assert(0 && "Invalid ABI kind for return argument");
1237 }
1238
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001239 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001240 if (!RetDbgLoc.isUnknown())
1241 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001242}
1243
John McCall413ebdb2011-03-11 20:59:21 +00001244void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1245 const VarDecl *param) {
John McCall27360712010-05-26 22:34:26 +00001246 // StartFunction converted the ABI-lowered parameter(s) into a
1247 // local alloca. We need to turn that into an r-value suitable
1248 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001249 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001250
John McCall413ebdb2011-03-11 20:59:21 +00001251 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001252
John McCall27360712010-05-26 22:34:26 +00001253 // For the most part, we just need to load the alloca, except:
1254 // 1) aggregate r-values are actually pointers to temporaries, and
1255 // 2) references to aggregates are pointers directly to the aggregate.
1256 // I don't know why references to non-aggregates are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001257 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1258 if (hasAggregateLLVMType(ref->getPointeeType()))
1259 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001260
1261 // Locals which are references to scalars are represented
1262 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001263 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001264 }
1265
John McCall413ebdb2011-03-11 20:59:21 +00001266 if (type->isAnyComplexType()) {
1267 ComplexPairTy complex = LoadComplexFromAddr(local, /*volatile*/ false);
1268 return args.add(RValue::getComplex(complex), type);
1269 }
John McCall27360712010-05-26 22:34:26 +00001270
John McCall413ebdb2011-03-11 20:59:21 +00001271 if (hasAggregateLLVMType(type))
1272 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001273
John McCall413ebdb2011-03-11 20:59:21 +00001274 unsigned alignment = getContext().getDeclAlign(param).getQuantity();
1275 llvm::Value *value = EmitLoadOfScalar(local, false, alignment, type);
1276 return args.add(RValue::get(value), type);
John McCall27360712010-05-26 22:34:26 +00001277}
1278
John McCallf85e1932011-06-15 23:02:42 +00001279static bool isProvablyNull(llvm::Value *addr) {
1280 return isa<llvm::ConstantPointerNull>(addr);
1281}
1282
1283static bool isProvablyNonNull(llvm::Value *addr) {
1284 return isa<llvm::AllocaInst>(addr);
1285}
1286
1287/// Emit the actual writing-back of a writeback.
1288static void emitWriteback(CodeGenFunction &CGF,
1289 const CallArgList::Writeback &writeback) {
1290 llvm::Value *srcAddr = writeback.Address;
1291 assert(!isProvablyNull(srcAddr) &&
1292 "shouldn't have writeback for provably null argument");
1293
1294 llvm::BasicBlock *contBB = 0;
1295
1296 // If the argument wasn't provably non-null, we need to null check
1297 // before doing the store.
1298 bool provablyNonNull = isProvablyNonNull(srcAddr);
1299 if (!provablyNonNull) {
1300 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1301 contBB = CGF.createBasicBlock("icr.done");
1302
1303 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1304 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1305 CGF.EmitBlock(writebackBB);
1306 }
1307
1308 // Load the value to writeback.
1309 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1310
1311 // Cast it back, in case we're writing an id to a Foo* or something.
1312 value = CGF.Builder.CreateBitCast(value,
1313 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1314 "icr.writeback-cast");
1315
1316 // Perform the writeback.
1317 QualType srcAddrType = writeback.AddressType;
1318 CGF.EmitStoreThroughLValue(RValue::get(value),
John McCall545d9962011-06-25 02:11:03 +00001319 CGF.MakeAddrLValue(srcAddr, srcAddrType));
John McCallf85e1932011-06-15 23:02:42 +00001320
1321 // Jump to the continuation block.
1322 if (!provablyNonNull)
1323 CGF.EmitBlock(contBB);
1324}
1325
1326static void emitWritebacks(CodeGenFunction &CGF,
1327 const CallArgList &args) {
1328 for (CallArgList::writeback_iterator
1329 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1330 emitWriteback(CGF, *i);
1331}
1332
1333/// Emit an argument that's being passed call-by-writeback. That is,
1334/// we are passing the address of
1335static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1336 const ObjCIndirectCopyRestoreExpr *CRE) {
1337 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1338
1339 // The dest and src types don't necessarily match in LLVM terms
1340 // because of the crazy ObjC compatibility rules.
1341
1342 const llvm::PointerType *destType =
1343 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1344
1345 // If the address is a constant null, just pass the appropriate null.
1346 if (isProvablyNull(srcAddr)) {
1347 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1348 CRE->getType());
1349 return;
1350 }
1351
1352 QualType srcAddrType =
1353 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1354
1355 // Create the temporary.
1356 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1357 "icr.temp");
1358
1359 // Zero-initialize it if we're not doing a copy-initialization.
1360 bool shouldCopy = CRE->shouldCopy();
1361 if (!shouldCopy) {
1362 llvm::Value *null =
1363 llvm::ConstantPointerNull::get(
1364 cast<llvm::PointerType>(destType->getElementType()));
1365 CGF.Builder.CreateStore(null, temp);
1366 }
1367
1368 llvm::BasicBlock *contBB = 0;
1369
1370 // If the address is *not* known to be non-null, we need to switch.
1371 llvm::Value *finalArgument;
1372
1373 bool provablyNonNull = isProvablyNonNull(srcAddr);
1374 if (provablyNonNull) {
1375 finalArgument = temp;
1376 } else {
1377 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1378
1379 finalArgument = CGF.Builder.CreateSelect(isNull,
1380 llvm::ConstantPointerNull::get(destType),
1381 temp, "icr.argument");
1382
1383 // If we need to copy, then the load has to be conditional, which
1384 // means we need control flow.
1385 if (shouldCopy) {
1386 contBB = CGF.createBasicBlock("icr.cont");
1387 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1388 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1389 CGF.EmitBlock(copyBB);
1390 }
1391 }
1392
1393 // Perform a copy if necessary.
1394 if (shouldCopy) {
1395 LValue srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCall545d9962011-06-25 02:11:03 +00001396 RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
John McCallf85e1932011-06-15 23:02:42 +00001397 assert(srcRV.isScalar());
1398
1399 llvm::Value *src = srcRV.getScalarVal();
1400 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1401 "icr.cast");
1402
1403 // Use an ordinary store, not a store-to-lvalue.
1404 CGF.Builder.CreateStore(src, temp);
1405 }
1406
1407 // Finish the control flow if we needed it.
1408 if (shouldCopy && !provablyNonNull)
1409 CGF.EmitBlock(contBB);
1410
1411 args.addWriteback(srcAddr, srcAddrType, temp);
1412 args.add(RValue::get(finalArgument), CRE->getType());
1413}
1414
John McCall413ebdb2011-03-11 20:59:21 +00001415void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
1416 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00001417 if (const ObjCIndirectCopyRestoreExpr *CRE
1418 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
1419 assert(getContext().getLangOptions().ObjCAutoRefCount);
1420 assert(getContext().hasSameType(E->getType(), type));
1421 return emitWritebackArg(*this, args, CRE);
1422 }
1423
John McCall413ebdb2011-03-11 20:59:21 +00001424 if (type->isReferenceType())
1425 return args.add(EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0),
1426 type);
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Eli Friedman70cbd2a2011-06-15 18:26:32 +00001428 if (hasAggregateLLVMType(type) && !E->getType()->isAnyComplexType() &&
1429 isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00001430 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
1431 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
1432 assert(L.isSimple());
1433 args.add(RValue::getAggregate(L.getAddress(), L.isVolatileQualified()),
1434 type, /*NeedsCopy*/true);
1435 return;
1436 }
1437
John McCall413ebdb2011-03-11 20:59:21 +00001438 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00001439}
1440
John McCallf1549f62010-07-06 01:34:17 +00001441/// Emits a call or invoke instruction to the given function, depending
1442/// on the current state of the EH stack.
1443llvm::CallSite
1444CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
1445 llvm::Value * const *ArgBegin,
1446 llvm::Value * const *ArgEnd,
1447 const llvm::Twine &Name) {
1448 llvm::BasicBlock *InvokeDest = getInvokeDest();
1449 if (!InvokeDest)
1450 return Builder.CreateCall(Callee, ArgBegin, ArgEnd, Name);
1451
1452 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
1453 llvm::InvokeInst *Invoke = Builder.CreateInvoke(Callee, ContBB, InvokeDest,
1454 ArgBegin, ArgEnd, Name);
1455 EmitBlock(ContBB);
1456 return Invoke;
1457}
1458
Daniel Dunbar88b53962009-02-02 22:03:45 +00001459RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001460 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001461 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00001462 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00001463 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00001464 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001465 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001466 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001467
1468 // Handle struct-return functions by passing a pointer to the
1469 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001470 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001471 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001472
1473
Chris Lattner5db7ae52009-06-13 00:26:38 +00001474 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00001475 // alloca to hold the result, unless one is given to us.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001476 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlssond2490a92009-12-24 20:40:36 +00001477 llvm::Value *Value = ReturnValue.getValue();
1478 if (!Value)
Daniel Dunbar195337d2010-02-09 02:48:28 +00001479 Value = CreateMemTemp(RetTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00001480 Args.push_back(Value);
1481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001483 assert(CallInfo.arg_size() == CallArgs.size() &&
1484 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00001485 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001486 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001487 I != E; ++I, ++info_it) {
1488 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00001489 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00001490
Eli Friedman97cb5a42011-06-15 22:09:18 +00001491 unsigned TypeAlign =
Eli Friedmanc6d07822011-05-02 18:05:27 +00001492 getContext().getTypeAlignInChars(I->Ty).getQuantity();
Daniel Dunbar56273772008-09-17 00:51:38 +00001493 switch (ArgInfo.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001494 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001495 if (RV.isScalar() || RV.isComplex()) {
1496 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00001497 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1498 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
1499 AI->setAlignment(ArgInfo.getIndirectAlign());
1500 Args.push_back(AI);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001501 if (RV.isScalar())
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001502 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false,
Eli Friedman97cb5a42011-06-15 22:09:18 +00001503 TypeAlign, I->Ty);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001504 else
Mike Stump1eb44332009-09-09 15:08:12 +00001505 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001506 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001507 // We want to avoid creating an unnecessary temporary+copy here;
1508 // however, we need one in two cases:
1509 // 1. If the argument is not byval, and we are required to copy the
1510 // source. (This case doesn't occur on any common architecture.)
1511 // 2. If the argument is byval, RV is not sufficiently aligned, and
1512 // we cannot force it to be sufficiently aligned.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001513 llvm::Value *Addr = RV.getAggregateAddr();
1514 unsigned Align = ArgInfo.getIndirectAlign();
1515 const llvm::TargetData *TD = &CGM.getTargetData();
1516 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
1517 (ArgInfo.getIndirectByVal() && TypeAlign < Align &&
1518 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align)) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001519 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001520 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1521 if (Align > AI->getAlignment())
1522 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001523 Args.push_back(AI);
Eli Friedman97cb5a42011-06-15 22:09:18 +00001524 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001525 } else {
1526 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001527 Args.push_back(Addr);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001528 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001529 }
1530 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001531 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001532
Daniel Dunbar11434922009-01-26 21:26:08 +00001533 case ABIArgInfo::Ignore:
1534 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001535
Chris Lattner800588f2010-07-29 06:26:06 +00001536 case ABIArgInfo::Extend:
1537 case ABIArgInfo::Direct: {
1538 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001539 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
1540 ArgInfo.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001541 if (RV.isScalar())
1542 Args.push_back(RV.getScalarVal());
1543 else
1544 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
1545 break;
1546 }
Daniel Dunbar11434922009-01-26 21:26:08 +00001547
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001548 // FIXME: Avoid the conversion through memory if possible.
1549 llvm::Value *SrcPtr;
1550 if (RV.isScalar()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00001551 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Eli Friedman97cb5a42011-06-15 22:09:18 +00001552 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, TypeAlign, I->Ty);
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001553 } else if (RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00001554 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001555 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001556 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001557 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001558
Chris Lattner117e3f42010-07-30 04:02:24 +00001559 // If the value is offset in memory, apply the offset now.
1560 if (unsigned Offs = ArgInfo.getDirectOffset()) {
1561 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
1562 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001563 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001564 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
1565
1566 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001567
Chris Lattnerce700162010-06-28 23:44:11 +00001568 // If the coerce-to type is a first class aggregate, we flatten it and
1569 // pass the elements. Either way is semantically identical, but fast-isel
1570 // and the optimizer generally likes scalar values better than FCAs.
1571 if (const llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00001572 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chris Lattner92826882010-07-05 20:41:41 +00001573 SrcPtr = Builder.CreateBitCast(SrcPtr,
1574 llvm::PointerType::getUnqual(STy));
1575 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1576 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00001577 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
1578 // We don't know what we're loading from.
1579 LI->setAlignment(1);
1580 Args.push_back(LI);
Chris Lattner309c59f2010-06-29 00:06:42 +00001581 }
Chris Lattnerce700162010-06-28 23:44:11 +00001582 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00001583 // In the simple case, just pass the coerced loaded value.
1584 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1585 *this));
Chris Lattnerce700162010-06-28 23:44:11 +00001586 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001587
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001588 break;
1589 }
1590
Daniel Dunbar56273772008-09-17 00:51:38 +00001591 case ABIArgInfo::Expand:
Eli Friedmanc6d07822011-05-02 18:05:27 +00001592 ExpandTypeToArgs(I->Ty, RV, Args);
Daniel Dunbar56273772008-09-17 00:51:38 +00001593 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001594 }
1595 }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Chris Lattner5db7ae52009-06-13 00:26:38 +00001597 // If the callee is a bitcast of a function to a varargs pointer to function
1598 // type, check to see if we can remove the bitcast. This handles some cases
1599 // with unprototyped functions.
1600 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
1601 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
1602 const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
1603 const llvm::FunctionType *CurFT =
1604 cast<llvm::FunctionType>(CurPT->getElementType());
1605 const llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Chris Lattner5db7ae52009-06-13 00:26:38 +00001607 if (CE->getOpcode() == llvm::Instruction::BitCast &&
1608 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00001609 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00001610 ActualFT->getNumParams() == Args.size() &&
1611 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00001612 bool ArgsMatch = true;
1613 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
1614 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
1615 ArgsMatch = false;
1616 break;
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattner5db7ae52009-06-13 00:26:38 +00001619 // Strip the cast if we can get away with it. This is a nice cleanup,
1620 // but also allows us to inline the function at -O0 if it is marked
1621 // always_inline.
1622 if (ArgsMatch)
1623 Callee = CalleeF;
1624 }
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001627
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001628 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00001629 CodeGen::AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001630 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001631 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1632 AttributeList.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001633
John McCallf1549f62010-07-06 01:34:17 +00001634 llvm::BasicBlock *InvokeDest = 0;
1635 if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind))
1636 InvokeDest = getInvokeDest();
1637
Daniel Dunbard14151d2009-03-02 04:32:35 +00001638 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00001639 if (!InvokeDest) {
Jay Foadbeaaccd2009-05-21 09:52:38 +00001640 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001641 } else {
1642 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Mike Stump1eb44332009-09-09 15:08:12 +00001643 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001644 Args.data(), Args.data()+Args.size());
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001645 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00001646 }
Chris Lattnerce933992010-06-29 16:40:28 +00001647 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00001648 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00001649
Daniel Dunbard14151d2009-03-02 04:32:35 +00001650 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001651 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00001652
1653 // If the call doesn't return, finish the basic block and clear the
1654 // insertion point; this allows the rest of IRgen to discard
1655 // unreachable code.
1656 if (CS.doesNotReturn()) {
1657 Builder.CreateUnreachable();
1658 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Mike Stumpf5408fe2009-05-16 07:57:57 +00001660 // FIXME: For now, emit a dummy basic block because expr emitters in
1661 // generally are not ready to handle emitting expressions at unreachable
1662 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00001663 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Daniel Dunbard14151d2009-03-02 04:32:35 +00001665 // Return a reasonable RValue.
1666 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001667 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00001668
1669 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001670 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001671 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001672
John McCallf85e1932011-06-15 23:02:42 +00001673 // Emit any writebacks immediately. Arguably this should happen
1674 // after any return-value munging.
1675 if (CallArgs.hasWritebacks())
1676 emitWritebacks(*this, CallArgs);
1677
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001678 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001679 case ABIArgInfo::Indirect: {
1680 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001681 if (RetTy->isAnyComplexType())
Daniel Dunbar56273772008-09-17 00:51:38 +00001682 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattner34030842009-03-22 00:32:22 +00001683 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar56273772008-09-17 00:51:38 +00001684 return RValue::getAggregate(Args[0]);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001685 return RValue::get(EmitLoadOfScalar(Args[0], false, Alignment, RetTy));
1686 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001687
Daniel Dunbar11434922009-01-26 21:26:08 +00001688 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001689 // If we are ignoring an argument that had a result, make sure to
1690 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00001691 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001692
Chris Lattner800588f2010-07-29 06:26:06 +00001693 case ABIArgInfo::Extend:
1694 case ABIArgInfo::Direct: {
Chris Lattner117e3f42010-07-30 04:02:24 +00001695 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1696 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001697 if (RetTy->isAnyComplexType()) {
1698 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1699 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1700 return RValue::getComplex(std::make_pair(Real, Imag));
1701 }
1702 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1703 llvm::Value *DestPtr = ReturnValue.getValue();
1704 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00001705
Chris Lattner800588f2010-07-29 06:26:06 +00001706 if (!DestPtr) {
1707 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
1708 DestIsVolatile = false;
1709 }
Eli Friedmanbadea572011-05-17 21:08:01 +00001710 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00001711 return RValue::getAggregate(DestPtr);
1712 }
1713 return RValue::get(CI);
1714 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001715
Anders Carlssond2490a92009-12-24 20:40:36 +00001716 llvm::Value *DestPtr = ReturnValue.getValue();
1717 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001718
Anders Carlssond2490a92009-12-24 20:40:36 +00001719 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00001720 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00001721 DestIsVolatile = false;
1722 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001723
Chris Lattner117e3f42010-07-30 04:02:24 +00001724 // If the value is offset in memory, apply the offset now.
1725 llvm::Value *StorePtr = DestPtr;
1726 if (unsigned Offs = RetAI.getDirectOffset()) {
1727 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
1728 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001729 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001730 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1731 }
1732 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001733
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001734 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Anders Carlssonad3d6912008-11-25 22:21:48 +00001735 if (RetTy->isAnyComplexType())
Anders Carlssond2490a92009-12-24 20:40:36 +00001736 return RValue::getComplex(LoadComplexFromAddr(DestPtr, false));
Chris Lattner34030842009-03-22 00:32:22 +00001737 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssond2490a92009-12-24 20:40:36 +00001738 return RValue::getAggregate(DestPtr);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001739 return RValue::get(EmitLoadOfScalar(DestPtr, false, Alignment, RetTy));
Daniel Dunbar639ffe42008-09-10 07:04:09 +00001740 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001741
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001742 case ABIArgInfo::Expand:
Mike Stump1eb44332009-09-09 15:08:12 +00001743 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001744 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001745
1746 assert(0 && "Unhandled ABIArgInfo::Kind");
1747 return RValue::get(0);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001748}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001749
1750/* VarArg handling */
1751
1752llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1753 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1754}