blob: 6e3b70cef8576ecba4770fcef0f55cf5bded9296 [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(),
Chris Lattner5f9e2722011-07-23 10:55:15 +000072 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,
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 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) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000090 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) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 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) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000126 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) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000140 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) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000157 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) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000183 SmallVector<CanQualType, 16> ArgTys;
John McCallead608a2010-02-26 00:48:12 +0000184 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?
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000187 for (ObjCMethodDecl::param_const_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.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000219 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.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000230 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() {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 SmallVector<CanQualType, 1> args;
John McCalld26bc762011-03-09 04:27:21 +0000239 return getFunctionInfo(getContext().VoidTy, args, FunctionType::ExtInfo());
240}
241
John McCallead608a2010-02-26 00:48:12 +0000242const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000243 const 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
Chris Lattner5f9e2722011-07-23 10:55:15 +0000246 for (SmallVectorImpl<CanQualType>::const_iterator
John McCallead608a2010-02-26 00:48:12 +0000247 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;
Chris Lattnerbe5f3322011-07-10 01:10:18 +0000255 CGFunctionInfo::Profile(ID, Info, ResTy, ArgTys.begin(), ArgTys.end());
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000256
257 void *InsertPos = 0;
258 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
259 if (FI)
260 return *FI;
261
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000262 // Construct the function info.
John McCallf85e1932011-06-15 23:02:42 +0000263 FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getProducesResult(),
264 Info.getHasRegParm(), Info.getRegParm(), ResTy,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000265 ArgTys.data(), ArgTys.size());
Daniel Dunbar35e67d42009-02-05 00:00:23 +0000266 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000267
Chris Lattner71305cc2011-07-15 05:16:14 +0000268 bool Inserted = FunctionsBeingProcessed.insert(FI); (void)Inserted;
269 assert(Inserted && "Recursively being processed?");
270
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000271 // Compute ABI information.
Chris Lattneree5dcd02010-07-29 02:31:05 +0000272 getABIInfo().computeInfo(*FI);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000273
Chris Lattner800588f2010-07-29 06:26:06 +0000274 // Loop over all of the computed argument and return value info. If any of
275 // them are direct or extend without a specified coerce type, specify the
276 // default now.
277 ABIArgInfo &RetInfo = FI->getReturnInfo();
278 if (RetInfo.canHaveCoerceToType() && RetInfo.getCoerceToType() == 0)
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000279 RetInfo.setCoerceToType(ConvertType(FI->getReturnType()));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000280
Chris Lattner800588f2010-07-29 06:26:06 +0000281 for (CGFunctionInfo::arg_iterator I = FI->arg_begin(), E = FI->arg_end();
282 I != E; ++I)
283 if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() == 0)
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000284 I->info.setCoerceToType(ConvertType(I->type));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000285
Chris Lattnerd26c0712011-07-15 06:41:05 +0000286 bool Erased = FunctionsBeingProcessed.erase(FI); (void)Erased;
287 assert(Erased && "Not in set?");
288
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000289 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000290}
291
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000292CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
John McCallf85e1932011-06-15 23:02:42 +0000293 bool _NoReturn, bool returnsRetained,
294 bool _HasRegParm, unsigned _RegParm,
John McCallead608a2010-02-26 00:48:12 +0000295 CanQualType ResTy,
Chris Lattnerbb521142010-06-29 18:13:52 +0000296 const CanQualType *ArgTys,
297 unsigned NumArgTys)
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000298 : CallingConvention(_CallingConvention),
John McCall04a67a62010-02-05 21:31:56 +0000299 EffectiveCallingConvention(_CallingConvention),
John McCallf85e1932011-06-15 23:02:42 +0000300 NoReturn(_NoReturn), ReturnsRetained(returnsRetained),
301 HasRegParm(_HasRegParm), RegParm(_RegParm)
Daniel Dunbarbac7c252009-09-11 22:24:53 +0000302{
Chris Lattnerbb521142010-06-29 18:13:52 +0000303 NumArgs = NumArgTys;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000304
Chris Lattnerce700162010-06-28 23:44:11 +0000305 // FIXME: Coallocate with the CGFunctionInfo object.
Chris Lattnerbb521142010-06-29 18:13:52 +0000306 Args = new ArgInfo[1 + NumArgTys];
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000307 Args[0].type = ResTy;
Chris Lattnerbb521142010-06-29 18:13:52 +0000308 for (unsigned i = 0; i != NumArgTys; ++i)
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000309 Args[1 + i].type = ArgTys[i];
310}
311
312/***/
313
John McCall42e06112011-05-15 02:19:42 +0000314void CodeGenTypes::GetExpandedTypes(QualType type,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000315 SmallVectorImpl<llvm::Type*> &expandedTypes) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000316 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(type)) {
317 uint64_t NumElts = AT->getSize().getZExtValue();
318 for (uint64_t Elt = 0; Elt < NumElts; ++Elt)
319 GetExpandedTypes(AT->getElementType(), expandedTypes);
320 } else if (const RecordType *RT = type->getAsStructureType()) {
321 const RecordDecl *RD = RT->getDecl();
322 assert(!RD->hasFlexibleArrayMember() &&
323 "Cannot expand structure with flexible array.");
324 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000325 i != e; ++i) {
Bob Wilson194f06a2011-08-03 05:58:22 +0000326 const FieldDecl *FD = *i;
327 assert(!FD->isBitField() &&
328 "Cannot expand structure with bit-field members.");
329 GetExpandedTypes(FD->getType(), expandedTypes);
330 }
331 } else if (const ComplexType *CT = type->getAs<ComplexType>()) {
332 llvm::Type *EltTy = ConvertType(CT->getElementType());
333 expandedTypes.push_back(EltTy);
334 expandedTypes.push_back(EltTy);
335 } else
336 expandedTypes.push_back(ConvertType(type));
Daniel Dunbar56273772008-09-17 00:51:38 +0000337}
338
Mike Stump1eb44332009-09-09 15:08:12 +0000339llvm::Function::arg_iterator
Daniel Dunbar56273772008-09-17 00:51:38 +0000340CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
341 llvm::Function::arg_iterator AI) {
Mike Stump1eb44332009-09-09 15:08:12 +0000342 assert(LV.isSimple() &&
343 "Unexpected non-simple lvalue during struct expansion.");
Daniel Dunbar56273772008-09-17 00:51:38 +0000344 llvm::Value *Addr = LV.getAddress();
Daniel Dunbar56273772008-09-17 00:51:38 +0000345
Bob Wilson194f06a2011-08-03 05:58:22 +0000346 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
347 unsigned NumElts = AT->getSize().getZExtValue();
348 QualType EltTy = AT->getElementType();
349 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
350 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
351 LValue LV = MakeAddrLValue(EltAddr, EltTy);
352 AI = ExpandTypeFromArgs(EltTy, LV, AI);
Daniel Dunbar56273772008-09-17 00:51:38 +0000353 }
Bob Wilson194f06a2011-08-03 05:58:22 +0000354 } else if (const RecordType *RT = Ty->getAsStructureType()) {
355 RecordDecl *RD = RT->getDecl();
356 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
357 i != e; ++i) {
358 FieldDecl *FD = *i;
359 QualType FT = FD->getType();
360
361 // FIXME: What are the right qualifiers here?
362 LValue LV = EmitLValueForField(Addr, FD, 0);
363 AI = ExpandTypeFromArgs(FT, LV, AI);
364 }
365 } else if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
366 QualType EltTy = CT->getElementType();
367 llvm::Value *RealAddr = Builder.CreateStructGEP(Addr, 0, "real");
368 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, EltTy));
Bob Wilsonbfcacd92011-10-22 21:42:34 +0000369 llvm::Value *ImagAddr = Builder.CreateStructGEP(Addr, 1, "imag");
Bob Wilson194f06a2011-08-03 05:58:22 +0000370 EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, EltTy));
371 } else {
372 EmitStoreThroughLValue(RValue::get(AI), LV);
373 ++AI;
Daniel Dunbar56273772008-09-17 00:51:38 +0000374 }
375
376 return AI;
377}
378
Chris Lattnere7bb7772010-06-27 06:04:18 +0000379/// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
Chris Lattner08dd2a02010-06-27 05:56:15 +0000380/// accessing some number of bytes out of it, try to gep into the struct to get
381/// at its inner goodness. Dive as deep as possible without entering an element
382/// with an in-memory size smaller than DstSize.
383static llvm::Value *
Chris Lattnere7bb7772010-06-27 06:04:18 +0000384EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000385 llvm::StructType *SrcSTy,
Chris Lattnere7bb7772010-06-27 06:04:18 +0000386 uint64_t DstSize, CodeGenFunction &CGF) {
Chris Lattner08dd2a02010-06-27 05:56:15 +0000387 // We can't dive into a zero-element struct.
388 if (SrcSTy->getNumElements() == 0) return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000389
Chris Lattner2acc6e32011-07-18 04:24:23 +0000390 llvm::Type *FirstElt = SrcSTy->getElementType(0);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000391
Chris Lattner08dd2a02010-06-27 05:56:15 +0000392 // If the first elt is at least as large as what we're looking for, or if the
393 // first element is the same size as the whole struct, we can enter it.
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000394 uint64_t FirstEltSize =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000395 CGF.CGM.getTargetData().getTypeAllocSize(FirstElt);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000396 if (FirstEltSize < DstSize &&
Chris Lattner08dd2a02010-06-27 05:56:15 +0000397 FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy))
398 return SrcPtr;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000399
Chris Lattner08dd2a02010-06-27 05:56:15 +0000400 // GEP into the first element.
401 SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000402
Chris Lattner08dd2a02010-06-27 05:56:15 +0000403 // If the first element is a struct, recurse.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000404 llvm::Type *SrcTy =
Chris Lattner08dd2a02010-06-27 05:56:15 +0000405 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000406 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
Chris Lattnere7bb7772010-06-27 06:04:18 +0000407 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000408
409 return SrcPtr;
410}
411
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000412/// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
413/// are either integers or pointers. This does a truncation of the value if it
414/// is too large or a zero extension if it is too small.
415static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000416 llvm::Type *Ty,
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000417 CodeGenFunction &CGF) {
418 if (Val->getType() == Ty)
419 return Val;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000420
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000421 if (isa<llvm::PointerType>(Val->getType())) {
422 // If this is Pointer->Pointer avoid conversion to and from int.
423 if (isa<llvm::PointerType>(Ty))
424 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000425
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000426 // Convert the pointer to an integer so we can play with its width.
Chris Lattner77b89b82010-06-27 07:15:29 +0000427 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000428 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000429
Chris Lattner2acc6e32011-07-18 04:24:23 +0000430 llvm::Type *DestIntTy = Ty;
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000431 if (isa<llvm::PointerType>(DestIntTy))
Chris Lattner77b89b82010-06-27 07:15:29 +0000432 DestIntTy = CGF.IntPtrTy;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000433
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000434 if (Val->getType() != DestIntTy)
435 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000436
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000437 if (isa<llvm::PointerType>(Ty))
438 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
439 return Val;
440}
441
Chris Lattner08dd2a02010-06-27 05:56:15 +0000442
443
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000444/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
445/// a pointer to an object of type \arg Ty.
446///
447/// This safely handles the case when the src type is smaller than the
448/// destination type; in this situation the values of bits which not
449/// present in the src are undefined.
450static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000451 llvm::Type *Ty,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000452 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000453 llvm::Type *SrcTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000454 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000455
Chris Lattner6ae00692010-06-28 22:51:39 +0000456 // If SrcTy and Ty are the same, just do a load.
457 if (SrcTy == Ty)
458 return CGF.Builder.CreateLoad(SrcPtr);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000459
Duncan Sands9408c452009-05-09 07:08:47 +0000460 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000461
Chris Lattner2acc6e32011-07-18 04:24:23 +0000462 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000463 SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
Chris Lattner08dd2a02010-06-27 05:56:15 +0000464 SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
465 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000466
Chris Lattner08dd2a02010-06-27 05:56:15 +0000467 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000468
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000469 // If the source and destination are integer or pointer types, just do an
470 // extension or truncation to the desired type.
471 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
472 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
473 llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
474 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
475 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000476
Daniel Dunbarb225be42009-02-03 05:59:18 +0000477 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000478 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000479 // Generally SrcSize is never greater than DstSize, since this means we are
480 // losing bits. However, this can happen in cases where the structure has
481 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +0000482 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000483 // FIXME: Assert that we aren't truncating non-padding bits when have access
484 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000485 llvm::Value *Casted =
486 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000487 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
488 // FIXME: Use better alignment / avoid requiring aligned load.
489 Load->setAlignment(1);
490 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000491 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000492
Chris Lattner35b21b82010-06-27 01:06:27 +0000493 // Otherwise do coercion through memory. This is stupid, but
494 // simple.
495 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
496 llvm::Value *Casted =
497 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
498 llvm::StoreInst *Store =
499 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
500 // FIXME: Use better alignment / avoid requiring aligned store.
501 Store->setAlignment(1);
502 return CGF.Builder.CreateLoad(Tmp);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000503}
504
Eli Friedmanbadea572011-05-17 21:08:01 +0000505// Function to store a first-class aggregate into memory. We prefer to
506// store the elements rather than the aggregate to be more friendly to
507// fast-isel.
508// FIXME: Do we need to recurse here?
509static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
510 llvm::Value *DestPtr, bool DestIsVolatile,
511 bool LowAlignment) {
512 // Prefer scalar stores to first-class aggregate stores.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000513 if (llvm::StructType *STy =
Eli Friedmanbadea572011-05-17 21:08:01 +0000514 dyn_cast<llvm::StructType>(Val->getType())) {
515 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
516 llvm::Value *EltPtr = CGF.Builder.CreateConstGEP2_32(DestPtr, 0, i);
517 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
518 llvm::StoreInst *SI = CGF.Builder.CreateStore(Elt, EltPtr,
519 DestIsVolatile);
520 if (LowAlignment)
521 SI->setAlignment(1);
522 }
523 } else {
524 CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
525 }
526}
527
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000528/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
529/// where the source and destination may have different types.
530///
531/// This safely handles the case when the src type is larger than the
532/// destination type; the upper bits of the src will be lost.
533static void CreateCoercedStore(llvm::Value *Src,
534 llvm::Value *DstPtr,
Anders Carlssond2490a92009-12-24 20:40:36 +0000535 bool DstIsVolatile,
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000536 CodeGenFunction &CGF) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000537 llvm::Type *SrcTy = Src->getType();
538 llvm::Type *DstTy =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000539 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
Chris Lattner6ae00692010-06-28 22:51:39 +0000540 if (SrcTy == DstTy) {
541 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
542 return;
543 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000544
Chris Lattner6ae00692010-06-28 22:51:39 +0000545 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000546
Chris Lattner2acc6e32011-07-18 04:24:23 +0000547 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
Chris Lattnere7bb7772010-06-27 06:04:18 +0000548 DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
549 DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
550 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000551
Chris Lattner6d11cdb2010-06-27 06:26:04 +0000552 // If the source and destination are integer or pointer types, just do an
553 // extension or truncation to the desired type.
554 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
555 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
556 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
557 CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
558 return;
559 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000560
Duncan Sands9408c452009-05-09 07:08:47 +0000561 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000562
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000563 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000564 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000565 llvm::Value *Casted =
566 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000567 // FIXME: Use better alignment / avoid requiring aligned store.
Eli Friedmanbadea572011-05-17 21:08:01 +0000568 BuildAggStore(CGF, Src, Casted, DstIsVolatile, true);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000569 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000570 // Otherwise do coercion through memory. This is stupid, but
571 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +0000572
573 // Generally SrcSize is never greater than DstSize, since this means we are
574 // losing bits. However, this can happen in cases where the structure has
575 // additional padding, for example due to a user specified alignment.
576 //
577 // FIXME: Assert that we aren't truncating non-padding bits when have access
578 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000579 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
580 CGF.Builder.CreateStore(Src, Tmp);
Mike Stump1eb44332009-09-09 15:08:12 +0000581 llvm::Value *Casted =
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000582 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +0000583 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
584 // FIXME: Use better alignment / avoid requiring aligned load.
585 Load->setAlignment(1);
Anders Carlssond2490a92009-12-24 20:40:36 +0000586 CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile);
Daniel Dunbar275e10d2009-02-02 19:06:38 +0000587 }
588}
589
Daniel Dunbar56273772008-09-17 00:51:38 +0000590/***/
591
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000592bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000593 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000594}
595
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000596bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
597 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
598 switch (BT->getKind()) {
599 default:
600 return false;
601 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000602 return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Float);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000603 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000604 return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Double);
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000605 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000606 return getContext().getTargetInfo().useObjCFPRetForRealType(
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000607 TargetInfo::LongDouble);
608 }
609 }
610
611 return false;
612}
613
Anders Carlssoneea64802011-10-31 16:27:11 +0000614bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
615 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
616 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
617 if (BT->getKind() == BuiltinType::LongDouble)
618 return getContext().getTargetInfo().useObjCFP2RetForComplexLongDouble();
619 }
620 }
621
622 return false;
623}
624
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000625llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
John McCallc0bf4622010-02-23 00:48:20 +0000626 const CGFunctionInfo &FI = getFunctionInfo(GD);
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000627
John McCallc0bf4622010-02-23 00:48:20 +0000628 // For definition purposes, don't consider a K&R function variadic.
629 bool Variadic = false;
630 if (const FunctionProtoType *FPT =
631 cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>())
632 Variadic = FPT->isVariadic();
633
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000634 return GetFunctionType(FI, Variadic);
John McCallc0bf4622010-02-23 00:48:20 +0000635}
636
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000637llvm::FunctionType *
638CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool isVariadic) {
Chris Lattner71305cc2011-07-15 05:16:14 +0000639
640 bool Inserted = FunctionsBeingProcessed.insert(&FI); (void)Inserted;
641 assert(Inserted && "Recursively being processed?");
642
Chris Lattner5f9e2722011-07-23 10:55:15 +0000643 SmallVector<llvm::Type*, 8> argTypes;
Chris Lattner2acc6e32011-07-18 04:24:23 +0000644 llvm::Type *resultType = 0;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000645
John McCall42e06112011-05-15 02:19:42 +0000646 const ABIArgInfo &retAI = FI.getReturnInfo();
647 switch (retAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000648 case ABIArgInfo::Expand:
John McCall42e06112011-05-15 02:19:42 +0000649 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000650
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000651 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000652 case ABIArgInfo::Direct:
John McCall42e06112011-05-15 02:19:42 +0000653 resultType = retAI.getCoerceToType();
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000654 break;
655
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000656 case ABIArgInfo::Indirect: {
John McCall42e06112011-05-15 02:19:42 +0000657 assert(!retAI.getIndirectAlign() && "Align unused on indirect return.");
658 resultType = llvm::Type::getVoidTy(getLLVMContext());
659
660 QualType ret = FI.getReturnType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000661 llvm::Type *ty = ConvertType(ret);
John McCall42e06112011-05-15 02:19:42 +0000662 unsigned addressSpace = Context.getTargetAddressSpace(ret);
663 argTypes.push_back(llvm::PointerType::get(ty, addressSpace));
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000664 break;
665 }
666
Daniel Dunbar11434922009-01-26 21:26:08 +0000667 case ABIArgInfo::Ignore:
John McCall42e06112011-05-15 02:19:42 +0000668 resultType = llvm::Type::getVoidTy(getLLVMContext());
Daniel Dunbar11434922009-01-26 21:26:08 +0000669 break;
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000670 }
Mike Stump1eb44332009-09-09 15:08:12 +0000671
672 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000673 ie = FI.arg_end(); it != ie; ++it) {
John McCall42e06112011-05-15 02:19:42 +0000674 const ABIArgInfo &argAI = it->info;
Mike Stump1eb44332009-09-09 15:08:12 +0000675
John McCall42e06112011-05-15 02:19:42 +0000676 switch (argAI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +0000677 case ABIArgInfo::Ignore:
678 break;
679
Chris Lattner800588f2010-07-29 06:26:06 +0000680 case ABIArgInfo::Indirect: {
681 // indirect arguments are always on the stack, which is addr space #0.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000682 llvm::Type *LTy = ConvertTypeForMem(it->type);
John McCall42e06112011-05-15 02:19:42 +0000683 argTypes.push_back(LTy->getPointerTo());
Chris Lattner800588f2010-07-29 06:26:06 +0000684 break;
685 }
686
687 case ABIArgInfo::Extend:
Chris Lattner1ed72672010-07-29 06:44:09 +0000688 case ABIArgInfo::Direct: {
Chris Lattnerce700162010-06-28 23:44:11 +0000689 // If the coerce-to type is a first class aggregate, flatten it. Either
690 // way is semantically identical, but fast-isel and the optimizer
691 // generally likes scalar values better than FCAs.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000692 llvm::Type *argType = argAI.getCoerceToType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000693 if (llvm::StructType *st = dyn_cast<llvm::StructType>(argType)) {
John McCall42e06112011-05-15 02:19:42 +0000694 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
695 argTypes.push_back(st->getElementType(i));
Chris Lattnerce700162010-06-28 23:44:11 +0000696 } else {
John McCall42e06112011-05-15 02:19:42 +0000697 argTypes.push_back(argType);
Chris Lattnerce700162010-06-28 23:44:11 +0000698 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000699 break;
Chris Lattner1ed72672010-07-29 06:44:09 +0000700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000702 case ABIArgInfo::Expand:
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000703 GetExpandedTypes(it->type, argTypes);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000704 break;
705 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000706 }
707
Chris Lattner71305cc2011-07-15 05:16:14 +0000708 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
709 assert(Erased && "Not in set?");
710
John McCall42e06112011-05-15 02:19:42 +0000711 return llvm::FunctionType::get(resultType, argTypes, isVariadic);
Daniel Dunbar3913f182008-09-09 23:48:28 +0000712}
713
Chris Lattner2acc6e32011-07-18 04:24:23 +0000714llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
John McCall4c40d982010-08-31 07:33:07 +0000715 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000716 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000717
Chris Lattnerf742eb02011-07-10 00:18:59 +0000718 if (!isFuncTypeConvertible(FPT))
719 return llvm::StructType::get(getLLVMContext());
720
721 const CGFunctionInfo *Info;
722 if (isa<CXXDestructorDecl>(MD))
723 Info = &getFunctionInfo(cast<CXXDestructorDecl>(MD), GD.getDtorType());
724 else
725 Info = &getFunctionInfo(MD);
726 return GetFunctionType(*Info, FPT->isVariadic());
Anders Carlssonecf282b2009-11-24 05:08:52 +0000727}
728
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000729void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +0000730 const Decl *TargetDecl,
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000731 AttributeListType &PAL,
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000732 unsigned &CallingConv) {
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000733 unsigned FuncAttrs = 0;
Devang Patela2c69122008-09-26 22:53:57 +0000734 unsigned RetAttrs = 0;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000735
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000736 CallingConv = FI.getEffectiveCallingConvention();
737
John McCall04a67a62010-02-05 21:31:56 +0000738 if (FI.isNoReturn())
739 FuncAttrs |= llvm::Attribute::NoReturn;
740
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000741 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000742 if (TargetDecl) {
Rafael Espindola67004152011-10-12 19:51:18 +0000743 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
744 FuncAttrs |= llvm::Attribute::ReturnsTwice;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000745 if (TargetDecl->hasAttr<NoThrowAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +0000746 FuncAttrs |= llvm::Attribute::NoUnwind;
John McCall9c0c1f32010-07-08 06:48:12 +0000747 else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
748 const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000749 if (FPT && FPT->isNothrow(getContext()))
John McCall9c0c1f32010-07-08 06:48:12 +0000750 FuncAttrs |= llvm::Attribute::NoUnwind;
751 }
752
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000753 if (TargetDecl->hasAttr<NoReturnAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +0000754 FuncAttrs |= llvm::Attribute::NoReturn;
Eric Christopher041087c2011-08-15 22:38:22 +0000755
Rafael Espindolaf87cced2011-10-03 14:59:42 +0000756 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
757 FuncAttrs |= llvm::Attribute::ReturnsTwice;
758
Eric Christopher041087c2011-08-15 22:38:22 +0000759 // 'const' and 'pure' attribute functions are also nounwind.
760 if (TargetDecl->hasAttr<ConstAttr>()) {
Anders Carlsson232eb7d2008-10-05 23:32:53 +0000761 FuncAttrs |= llvm::Attribute::ReadNone;
Eric Christopher041087c2011-08-15 22:38:22 +0000762 FuncAttrs |= llvm::Attribute::NoUnwind;
763 } else if (TargetDecl->hasAttr<PureAttr>()) {
Daniel Dunbar64c2e072009-04-10 22:14:52 +0000764 FuncAttrs |= llvm::Attribute::ReadOnly;
Eric Christopher041087c2011-08-15 22:38:22 +0000765 FuncAttrs |= llvm::Attribute::NoUnwind;
766 }
Ryan Flynn76168e22009-08-09 20:07:29 +0000767 if (TargetDecl->hasAttr<MallocAttr>())
768 RetAttrs |= llvm::Attribute::NoAlias;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000769 }
770
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000771 if (CodeGenOpts.OptimizeSize)
Daniel Dunbar7ab1c3e2009-10-27 19:48:08 +0000772 FuncAttrs |= llvm::Attribute::OptimizeForSize;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000773 if (CodeGenOpts.DisableRedZone)
Devang Patel24095da2009-06-04 23:32:02 +0000774 FuncAttrs |= llvm::Attribute::NoRedZone;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000775 if (CodeGenOpts.NoImplicitFloat)
Devang Patelacebb392009-06-05 22:05:48 +0000776 FuncAttrs |= llvm::Attribute::NoImplicitFloat;
Devang Patel24095da2009-06-04 23:32:02 +0000777
Daniel Dunbara0a99e02009-02-02 23:43:58 +0000778 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000779 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000780 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000781 switch (RetAI.getKind()) {
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000782 case ABIArgInfo::Extend:
Chris Lattner2eb9cdd2010-07-28 23:46:15 +0000783 if (RetTy->hasSignedIntegerRepresentation())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000784 RetAttrs |= llvm::Attribute::SExt;
Chris Lattner2eb9cdd2010-07-28 23:46:15 +0000785 else if (RetTy->hasUnsignedIntegerRepresentation())
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000786 RetAttrs |= llvm::Attribute::ZExt;
Chris Lattner800588f2010-07-29 06:26:06 +0000787 break;
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000788 case ABIArgInfo::Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000789 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000790 break;
791
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000792 case ABIArgInfo::Indirect:
Mike Stump1eb44332009-09-09 15:08:12 +0000793 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Chris Lattnerfb97cf22010-04-20 05:44:43 +0000794 llvm::Attribute::StructRet));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000795 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +0000796 // sret disables readnone and readonly
797 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
798 llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000799 break;
800
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000801 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +0000802 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000803 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000804
Devang Patela2c69122008-09-26 22:53:57 +0000805 if (RetAttrs)
806 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000807
Daniel Dunbar17d3fea2011-02-09 17:54:19 +0000808 // FIXME: RegParm should be reduced in case of global register variable.
Eli Friedmana49218e2011-04-09 08:18:08 +0000809 signed RegParm;
810 if (FI.getHasRegParm())
811 RegParm = FI.getRegParm();
812 else
Daniel Dunbar17d3fea2011-02-09 17:54:19 +0000813 RegParm = CodeGenOpts.NumRegisterParameters;
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000814
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000815 unsigned PointerWidth = getContext().getTargetInfo().getPointerWidth(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000816 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000817 ie = FI.arg_end(); it != ie; ++it) {
818 QualType ParamType = it->type;
819 const ABIArgInfo &AI = it->info;
Devang Patel761d7f72008-09-25 21:02:23 +0000820 unsigned Attributes = 0;
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000821
John McCalld8e10d22010-03-27 00:47:27 +0000822 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
823 // have the corresponding parameter variable. It doesn't make
Daniel Dunbar7f6890e2011-02-10 18:10:07 +0000824 // sense to do it here because parameters are so messed up.
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000825 switch (AI.getKind()) {
Chris Lattner800588f2010-07-29 06:26:06 +0000826 case ABIArgInfo::Extend:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000827 if (ParamType->isSignedIntegerOrEnumerationType())
Chris Lattner800588f2010-07-29 06:26:06 +0000828 Attributes |= llvm::Attribute::SExt;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000829 else if (ParamType->isUnsignedIntegerOrEnumerationType())
Chris Lattner800588f2010-07-29 06:26:06 +0000830 Attributes |= llvm::Attribute::ZExt;
831 // FALL THROUGH
832 case ABIArgInfo::Direct:
833 if (RegParm > 0 &&
834 (ParamType->isIntegerType() || ParamType->isPointerType())) {
835 RegParm -=
836 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
837 if (RegParm >= 0)
838 Attributes |= llvm::Attribute::InReg;
839 }
840 // FIXME: handle sseregparm someday...
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000841
Chris Lattner2acc6e32011-07-18 04:24:23 +0000842 if (llvm::StructType *STy =
Chris Lattner800588f2010-07-29 06:26:06 +0000843 dyn_cast<llvm::StructType>(AI.getCoerceToType()))
844 Index += STy->getNumElements()-1; // 1 will be added below.
845 break;
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +0000846
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000847 case ABIArgInfo::Indirect:
Anders Carlsson0a8f8472009-09-16 15:53:40 +0000848 if (AI.getIndirectByVal())
849 Attributes |= llvm::Attribute::ByVal;
850
Anton Korobeynikov1102f422009-04-04 00:49:24 +0000851 Attributes |=
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000852 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar0ac86f02009-03-18 19:51:01 +0000853 // byval disables readnone and readonly.
854 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
855 llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000856 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000857
Daniel Dunbar11434922009-01-26 21:26:08 +0000858 case ABIArgInfo::Ignore:
859 // Skip increment, no matching LLVM parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000860 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +0000861
Daniel Dunbar56273772008-09-17 00:51:38 +0000862 case ABIArgInfo::Expand: {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000863 SmallVector<llvm::Type*, 8> types;
Mike Stumpf5408fe2009-05-16 07:57:57 +0000864 // FIXME: This is rather inefficient. Do we ever actually need to do
865 // anything here? The result should be just reconstructed on the other
866 // side, so extension should be a non-issue.
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000867 getTypes().GetExpandedTypes(ParamType, types);
John McCall42e06112011-05-15 02:19:42 +0000868 Index += types.size();
Daniel Dunbar56273772008-09-17 00:51:38 +0000869 continue;
870 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000871 }
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Devang Patel761d7f72008-09-25 21:02:23 +0000873 if (Attributes)
874 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar56273772008-09-17 00:51:38 +0000875 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000876 }
Devang Patela2c69122008-09-26 22:53:57 +0000877 if (FuncAttrs)
878 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +0000879}
880
John McCalld26bc762011-03-09 04:27:21 +0000881/// An argument came in as a promoted argument; demote it back to its
882/// declared type.
883static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
884 const VarDecl *var,
885 llvm::Value *value) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000886 llvm::Type *varType = CGF.ConvertType(var->getType());
John McCalld26bc762011-03-09 04:27:21 +0000887
888 // This can happen with promotions that actually don't change the
889 // underlying type, like the enum promotions.
890 if (value->getType() == varType) return value;
891
892 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
893 && "unexpected promotion type");
894
895 if (isa<llvm::IntegerType>(varType))
896 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
897
898 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
899}
900
Daniel Dunbar88b53962009-02-02 22:03:45 +0000901void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
902 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000903 const FunctionArgList &Args) {
John McCall0cfeb632009-07-28 01:00:58 +0000904 // If this is an implicit-return-zero function, go ahead and
905 // initialize the return value. TODO: it might be nice to have
906 // a more general mechanism for this that didn't require synthesized
907 // return statements.
Chris Lattner121b3fa2010-07-05 20:21:00 +0000908 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
John McCall0cfeb632009-07-28 01:00:58 +0000909 if (FD->hasImplicitReturnZero()) {
910 QualType RetTy = FD->getResultType().getUnqualifiedType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000911 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000912 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
John McCall0cfeb632009-07-28 01:00:58 +0000913 Builder.CreateStore(Zero, ReturnValue);
914 }
915 }
916
Mike Stumpf5408fe2009-05-16 07:57:57 +0000917 // FIXME: We no longer need the types from FunctionArgList; lift up and
918 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +0000919
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000920 // Emit allocs for param decls. Give the LLVM Argument nodes names.
921 llvm::Function::arg_iterator AI = Fn->arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000923 // Name the struct return argument.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000924 if (CGM.ReturnTypeUsesSRet(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000925 AI->setName("agg.result");
John McCall410ffb22011-08-25 23:04:34 +0000926 AI->addAttr(llvm::Attribute::NoAlias);
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000927 ++AI;
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +0000930 assert(FI.arg_size() == Args.size() &&
931 "Mismatch between function signature & arguments.");
Devang Patel093ac462011-03-03 20:13:15 +0000932 unsigned ArgNo = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000933 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Devang Patel093ac462011-03-03 20:13:15 +0000934 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
935 i != e; ++i, ++info_it, ++ArgNo) {
John McCalld26bc762011-03-09 04:27:21 +0000936 const VarDecl *Arg = *i;
Daniel Dunbarb225be42009-02-03 05:59:18 +0000937 QualType Ty = info_it->type;
938 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000939
John McCalld26bc762011-03-09 04:27:21 +0000940 bool isPromoted =
941 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
942
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000943 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +0000944 case ABIArgInfo::Indirect: {
Chris Lattnerce700162010-06-28 23:44:11 +0000945 llvm::Value *V = AI;
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000946
Daniel Dunbar1f745982009-02-05 09:16:39 +0000947 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000948 // Aggregates and complex variables are accessed by reference. All we
949 // need to do is realign the value, if requested
950 if (ArgI.getIndirectRealign()) {
951 llvm::Value *AlignedTemp = CreateMemTemp(Ty, "coerce");
952
953 // Copy from the incoming argument pointer to the temporary with the
954 // appropriate alignment.
955 //
956 // FIXME: We should have a common utility for generating an aggregate
957 // copy.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000958 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
Ken Dyckfe710082011-01-19 01:58:38 +0000959 CharUnits Size = getContext().getTypeSizeInChars(Ty);
NAKAMURA Takumic95a8fc2011-03-10 14:02:21 +0000960 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
961 llvm::Value *Src = Builder.CreateBitCast(V, I8PtrTy);
962 Builder.CreateMemCpy(Dst,
963 Src,
Ken Dyckfe710082011-01-19 01:58:38 +0000964 llvm::ConstantInt::get(IntPtrTy,
965 Size.getQuantity()),
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000966 ArgI.getIndirectAlign(),
967 false);
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000968 V = AlignedTemp;
969 }
Daniel Dunbar1f745982009-02-05 09:16:39 +0000970 } else {
971 // Load scalar value from indirect argument.
Ken Dyckfe710082011-01-19 01:58:38 +0000972 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
973 V = EmitLoadOfScalar(V, false, Alignment.getQuantity(), Ty);
John McCalld26bc762011-03-09 04:27:21 +0000974
975 if (isPromoted)
976 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar1f745982009-02-05 09:16:39 +0000977 }
Devang Patel093ac462011-03-03 20:13:15 +0000978 EmitParmDecl(*Arg, V, ArgNo);
Daniel Dunbar1f745982009-02-05 09:16:39 +0000979 break;
980 }
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000981
982 case ABIArgInfo::Extend:
Daniel Dunbar46327aa2009-02-03 06:17:37 +0000983 case ABIArgInfo::Direct: {
Chris Lattner800588f2010-07-29 06:26:06 +0000984 // If we have the trivial case, handle it with no muss and fuss.
985 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +0000986 ArgI.getCoerceToType() == ConvertType(Ty) &&
987 ArgI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +0000988 assert(AI != Fn->arg_end() && "Argument mismatch!");
989 llvm::Value *V = AI;
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000990
John McCalld8e10d22010-03-27 00:47:27 +0000991 if (Arg->getType().isRestrictQualified())
992 AI->addAttr(llvm::Attribute::NoAlias);
993
Chris Lattnerb13eab92011-07-20 06:29:00 +0000994 // Ensure the argument is the correct type.
995 if (V->getType() != ArgI.getCoerceToType())
996 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
997
John McCalld26bc762011-03-09 04:27:21 +0000998 if (isPromoted)
999 V = emitArgumentDemotion(*this, Arg, V);
Chris Lattnerb13eab92011-07-20 06:29:00 +00001000
Devang Patel093ac462011-03-03 20:13:15 +00001001 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001002 break;
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner121b3fa2010-07-05 20:21:00 +00001005 llvm::AllocaInst *Alloca = CreateMemTemp(Ty, "coerce");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001006
Chris Lattnerdeabde22010-07-28 18:24:28 +00001007 // The alignment we need to use is the max of the requested alignment for
1008 // the argument plus the alignment required by our access code below.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001009 unsigned AlignmentToUse =
John McCalld16c2cf2011-02-08 08:22:06 +00001010 CGM.getTargetData().getABITypeAlignment(ArgI.getCoerceToType());
Chris Lattnerdeabde22010-07-28 18:24:28 +00001011 AlignmentToUse = std::max(AlignmentToUse,
1012 (unsigned)getContext().getDeclAlign(Arg).getQuantity());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001013
Chris Lattnerdeabde22010-07-28 18:24:28 +00001014 Alloca->setAlignment(AlignmentToUse);
Chris Lattner121b3fa2010-07-05 20:21:00 +00001015 llvm::Value *V = Alloca;
Chris Lattner117e3f42010-07-30 04:02:24 +00001016 llvm::Value *Ptr = V; // Pointer to store into.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001017
Chris Lattner117e3f42010-07-30 04:02:24 +00001018 // If the value is offset in memory, apply the offset now.
1019 if (unsigned Offs = ArgI.getDirectOffset()) {
1020 Ptr = Builder.CreateBitCast(Ptr, Builder.getInt8PtrTy());
1021 Ptr = Builder.CreateConstGEP1_32(Ptr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001022 Ptr = Builder.CreateBitCast(Ptr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001023 llvm::PointerType::getUnqual(ArgI.getCoerceToType()));
1024 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001025
Chris Lattner309c59f2010-06-29 00:06:42 +00001026 // If the coerce-to type is a first class aggregate, we flatten it and
1027 // pass the elements. Either way is semantically identical, but fast-isel
1028 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001029 if (llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00001030 dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
Chris Lattner92826882010-07-05 20:41:41 +00001031 Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001032
Chris Lattner92826882010-07-05 20:41:41 +00001033 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1034 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001035 AI->setName(Arg->getName() + ".coerce" + Twine(i));
Chris Lattner92826882010-07-05 20:41:41 +00001036 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
1037 Builder.CreateStore(AI++, EltPtr);
Chris Lattner309c59f2010-06-29 00:06:42 +00001038 }
1039 } else {
1040 // Simple case, just do a coerced store of the argument into the alloca.
1041 assert(AI != Fn->arg_end() && "Argument mismatch!");
Chris Lattner225e2862010-06-29 00:14:52 +00001042 AI->setName(Arg->getName() + ".coerce");
Chris Lattner117e3f42010-07-30 04:02:24 +00001043 CreateCoercedStore(AI++, Ptr, /*DestIsVolatile=*/false, *this);
Chris Lattner309c59f2010-06-29 00:06:42 +00001044 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001045
1046
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001047 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001048 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001049 V = EmitLoadOfScalar(V, false, AlignmentToUse, Ty);
John McCalld26bc762011-03-09 04:27:21 +00001050 if (isPromoted)
1051 V = emitArgumentDemotion(*this, Arg, V);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001052 }
Devang Patel093ac462011-03-03 20:13:15 +00001053 EmitParmDecl(*Arg, V, ArgNo);
Chris Lattnerce700162010-06-28 23:44:11 +00001054 continue; // Skip ++AI increment, already done.
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001055 }
Chris Lattner800588f2010-07-29 06:26:06 +00001056
1057 case ABIArgInfo::Expand: {
1058 // If this structure was expanded into multiple arguments then
1059 // we need to create a temporary and reconstruct it from the
1060 // arguments.
1061 llvm::Value *Temp = CreateMemTemp(Ty, Arg->getName() + ".addr");
Chris Lattner800588f2010-07-29 06:26:06 +00001062 llvm::Function::arg_iterator End =
Daniel Dunbar79c39282010-08-21 03:15:20 +00001063 ExpandTypeFromArgs(Ty, MakeAddrLValue(Temp, Ty), AI);
Devang Patel093ac462011-03-03 20:13:15 +00001064 EmitParmDecl(*Arg, Temp, ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001065
1066 // Name the arguments used in expansion and increment AI.
1067 unsigned Index = 0;
1068 for (; AI != End; ++AI, ++Index)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001069 AI->setName(Arg->getName() + "." + Twine(Index));
Chris Lattner800588f2010-07-29 06:26:06 +00001070 continue;
1071 }
1072
1073 case ABIArgInfo::Ignore:
1074 // Initialize the local variable appropriately.
1075 if (hasAggregateLLVMType(Ty))
Devang Patel093ac462011-03-03 20:13:15 +00001076 EmitParmDecl(*Arg, CreateMemTemp(Ty), ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001077 else
Devang Patel093ac462011-03-03 20:13:15 +00001078 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())),
1079 ArgNo);
Chris Lattner800588f2010-07-29 06:26:06 +00001080
1081 // Skip increment, no matching LLVM parameter.
1082 continue;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001083 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001084
1085 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001086 }
1087 assert(AI == Fn->arg_end() && "Argument mismatch!");
1088}
1089
John McCallf85e1932011-06-15 23:02:42 +00001090/// Try to emit a fused autorelease of a return result.
1091static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
1092 llvm::Value *result) {
1093 // We must be immediately followed the cast.
1094 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
1095 if (BB->empty()) return 0;
1096 if (&BB->back() != result) return 0;
1097
Chris Lattner2acc6e32011-07-18 04:24:23 +00001098 llvm::Type *resultType = result->getType();
John McCallf85e1932011-06-15 23:02:42 +00001099
1100 // result is in a BasicBlock and is therefore an Instruction.
1101 llvm::Instruction *generator = cast<llvm::Instruction>(result);
1102
Chris Lattner5f9e2722011-07-23 10:55:15 +00001103 SmallVector<llvm::Instruction*,4> insnsToKill;
John McCallf85e1932011-06-15 23:02:42 +00001104
1105 // Look for:
1106 // %generator = bitcast %type1* %generator2 to %type2*
1107 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
1108 // We would have emitted this as a constant if the operand weren't
1109 // an Instruction.
1110 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
1111
1112 // Require the generator to be immediately followed by the cast.
1113 if (generator->getNextNode() != bitcast)
1114 return 0;
1115
1116 insnsToKill.push_back(bitcast);
1117 }
1118
1119 // Look for:
1120 // %generator = call i8* @objc_retain(i8* %originalResult)
1121 // or
1122 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
1123 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
1124 if (!call) return 0;
1125
1126 bool doRetainAutorelease;
1127
1128 if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
1129 doRetainAutorelease = true;
1130 } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
1131 .objc_retainAutoreleasedReturnValue) {
1132 doRetainAutorelease = false;
1133
1134 // Look for an inline asm immediately preceding the call and kill it, too.
1135 llvm::Instruction *prev = call->getPrevNode();
1136 if (llvm::CallInst *asmCall = dyn_cast_or_null<llvm::CallInst>(prev))
1137 if (asmCall->getCalledValue()
1138 == CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker)
1139 insnsToKill.push_back(prev);
1140 } else {
1141 return 0;
1142 }
1143
1144 result = call->getArgOperand(0);
1145 insnsToKill.push_back(call);
1146
1147 // Keep killing bitcasts, for sanity. Note that we no longer care
1148 // about precise ordering as long as there's exactly one use.
1149 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
1150 if (!bitcast->hasOneUse()) break;
1151 insnsToKill.push_back(bitcast);
1152 result = bitcast->getOperand(0);
1153 }
1154
1155 // Delete all the unnecessary instructions, from latest to earliest.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001156 for (SmallVectorImpl<llvm::Instruction*>::iterator
John McCallf85e1932011-06-15 23:02:42 +00001157 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
1158 (*i)->eraseFromParent();
1159
1160 // Do the fused retain/autorelease if we were asked to.
1161 if (doRetainAutorelease)
1162 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
1163
1164 // Cast back to the result type.
1165 return CGF.Builder.CreateBitCast(result, resultType);
1166}
1167
1168/// Emit an ARC autorelease of the result of a function.
1169static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
1170 llvm::Value *result) {
1171 // At -O0, try to emit a fused retain/autorelease.
1172 if (CGF.shouldUseFusedARCCalls())
1173 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
1174 return fused;
1175
1176 return CGF.EmitARCAutoreleaseReturnValue(result);
1177}
1178
Chris Lattner35b21b82010-06-27 01:06:27 +00001179void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001180 // Functions with no result always return void.
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001181 if (ReturnValue == 0) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001182 Builder.CreateRetVoid();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001183 return;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001184 }
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001185
Dan Gohman4751a532010-07-20 20:13:52 +00001186 llvm::DebugLoc RetDbgLoc;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001187 llvm::Value *RV = 0;
1188 QualType RetTy = FI.getReturnType();
1189 const ABIArgInfo &RetAI = FI.getReturnInfo();
1190
1191 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001192 case ABIArgInfo::Indirect: {
1193 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001194 if (RetTy->isAnyComplexType()) {
1195 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1196 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1197 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1198 // Do nothing; aggregrates get evaluated directly into the destination.
1199 } else {
1200 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001201 false, Alignment, RetTy);
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001202 }
1203 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001204 }
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001205
1206 case ABIArgInfo::Extend:
Chris Lattner800588f2010-07-29 06:26:06 +00001207 case ABIArgInfo::Direct:
Chris Lattner117e3f42010-07-30 04:02:24 +00001208 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
1209 RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001210 // The internal return value temp always will have pointer-to-return-type
1211 // type, just do a load.
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001212
Chris Lattner800588f2010-07-29 06:26:06 +00001213 // If the instruction right before the insertion point is a store to the
1214 // return value, we can elide the load, zap the store, and usually zap the
1215 // alloca.
1216 llvm::BasicBlock *InsertBB = Builder.GetInsertBlock();
1217 llvm::StoreInst *SI = 0;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001218 if (InsertBB->empty() ||
Chris Lattner800588f2010-07-29 06:26:06 +00001219 !(SI = dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
1220 SI->getPointerOperand() != ReturnValue || SI->isVolatile()) {
1221 RV = Builder.CreateLoad(ReturnValue);
1222 } else {
1223 // Get the stored value and nuke the now-dead store.
1224 RetDbgLoc = SI->getDebugLoc();
1225 RV = SI->getValueOperand();
1226 SI->eraseFromParent();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001227
Chris Lattner800588f2010-07-29 06:26:06 +00001228 // If that was the only use of the return value, nuke it as well now.
1229 if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1230 cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1231 ReturnValue = 0;
1232 }
Chris Lattner35b21b82010-06-27 01:06:27 +00001233 }
Chris Lattner800588f2010-07-29 06:26:06 +00001234 } else {
Chris Lattner117e3f42010-07-30 04:02:24 +00001235 llvm::Value *V = ReturnValue;
1236 // If the value is offset in memory, apply the offset now.
1237 if (unsigned Offs = RetAI.getDirectOffset()) {
1238 V = Builder.CreateBitCast(V, Builder.getInt8PtrTy());
1239 V = Builder.CreateConstGEP1_32(V, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001240 V = Builder.CreateBitCast(V,
Chris Lattner117e3f42010-07-30 04:02:24 +00001241 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1242 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001243
Chris Lattner117e3f42010-07-30 04:02:24 +00001244 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
Chris Lattner35b21b82010-06-27 01:06:27 +00001245 }
John McCallf85e1932011-06-15 23:02:42 +00001246
1247 // In ARC, end functions that return a retainable type with a call
1248 // to objc_autoreleaseReturnValue.
1249 if (AutoreleaseResult) {
1250 assert(getLangOptions().ObjCAutoRefCount &&
1251 !FI.isReturnsRetained() &&
1252 RetTy->isObjCRetainableType());
1253 RV = emitAutoreleaseOfResult(*this, RV);
1254 }
1255
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001256 break;
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001257
Chris Lattner800588f2010-07-29 06:26:06 +00001258 case ABIArgInfo::Ignore:
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001259 break;
1260
1261 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001262 llvm_unreachable("Invalid ABI kind for return argument");
Chris Lattnerc6e6dd22010-06-26 23:13:19 +00001263 }
1264
Daniel Dunbar21fcc8f2010-06-30 21:27:58 +00001265 llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
Devang Pateld3f265d2010-07-21 18:08:50 +00001266 if (!RetDbgLoc.isUnknown())
1267 Ret->setDebugLoc(RetDbgLoc);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001268}
1269
John McCall413ebdb2011-03-11 20:59:21 +00001270void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
1271 const VarDecl *param) {
John McCall27360712010-05-26 22:34:26 +00001272 // StartFunction converted the ABI-lowered parameter(s) into a
1273 // local alloca. We need to turn that into an r-value suitable
1274 // for EmitCall.
John McCall413ebdb2011-03-11 20:59:21 +00001275 llvm::Value *local = GetAddrOfLocalVar(param);
John McCall27360712010-05-26 22:34:26 +00001276
John McCall413ebdb2011-03-11 20:59:21 +00001277 QualType type = param->getType();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001278
John McCall27360712010-05-26 22:34:26 +00001279 // For the most part, we just need to load the alloca, except:
1280 // 1) aggregate r-values are actually pointers to temporaries, and
1281 // 2) references to aggregates are pointers directly to the aggregate.
1282 // I don't know why references to non-aggregates are different here.
John McCall413ebdb2011-03-11 20:59:21 +00001283 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1284 if (hasAggregateLLVMType(ref->getPointeeType()))
1285 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001286
1287 // Locals which are references to scalars are represented
1288 // with allocas holding the pointer.
John McCall413ebdb2011-03-11 20:59:21 +00001289 return args.add(RValue::get(Builder.CreateLoad(local)), type);
John McCall27360712010-05-26 22:34:26 +00001290 }
1291
John McCall413ebdb2011-03-11 20:59:21 +00001292 if (type->isAnyComplexType()) {
1293 ComplexPairTy complex = LoadComplexFromAddr(local, /*volatile*/ false);
1294 return args.add(RValue::getComplex(complex), type);
1295 }
John McCall27360712010-05-26 22:34:26 +00001296
John McCall413ebdb2011-03-11 20:59:21 +00001297 if (hasAggregateLLVMType(type))
1298 return args.add(RValue::getAggregate(local), type);
John McCall27360712010-05-26 22:34:26 +00001299
John McCall413ebdb2011-03-11 20:59:21 +00001300 unsigned alignment = getContext().getDeclAlign(param).getQuantity();
1301 llvm::Value *value = EmitLoadOfScalar(local, false, alignment, type);
1302 return args.add(RValue::get(value), type);
John McCall27360712010-05-26 22:34:26 +00001303}
1304
John McCallf85e1932011-06-15 23:02:42 +00001305static bool isProvablyNull(llvm::Value *addr) {
1306 return isa<llvm::ConstantPointerNull>(addr);
1307}
1308
1309static bool isProvablyNonNull(llvm::Value *addr) {
1310 return isa<llvm::AllocaInst>(addr);
1311}
1312
1313/// Emit the actual writing-back of a writeback.
1314static void emitWriteback(CodeGenFunction &CGF,
1315 const CallArgList::Writeback &writeback) {
1316 llvm::Value *srcAddr = writeback.Address;
1317 assert(!isProvablyNull(srcAddr) &&
1318 "shouldn't have writeback for provably null argument");
1319
1320 llvm::BasicBlock *contBB = 0;
1321
1322 // If the argument wasn't provably non-null, we need to null check
1323 // before doing the store.
1324 bool provablyNonNull = isProvablyNonNull(srcAddr);
1325 if (!provablyNonNull) {
1326 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
1327 contBB = CGF.createBasicBlock("icr.done");
1328
1329 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1330 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
1331 CGF.EmitBlock(writebackBB);
1332 }
1333
1334 // Load the value to writeback.
1335 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
1336
1337 // Cast it back, in case we're writing an id to a Foo* or something.
1338 value = CGF.Builder.CreateBitCast(value,
1339 cast<llvm::PointerType>(srcAddr->getType())->getElementType(),
1340 "icr.writeback-cast");
1341
1342 // Perform the writeback.
1343 QualType srcAddrType = writeback.AddressType;
1344 CGF.EmitStoreThroughLValue(RValue::get(value),
John McCall545d9962011-06-25 02:11:03 +00001345 CGF.MakeAddrLValue(srcAddr, srcAddrType));
John McCallf85e1932011-06-15 23:02:42 +00001346
1347 // Jump to the continuation block.
1348 if (!provablyNonNull)
1349 CGF.EmitBlock(contBB);
1350}
1351
1352static void emitWritebacks(CodeGenFunction &CGF,
1353 const CallArgList &args) {
1354 for (CallArgList::writeback_iterator
1355 i = args.writeback_begin(), e = args.writeback_end(); i != e; ++i)
1356 emitWriteback(CGF, *i);
1357}
1358
1359/// Emit an argument that's being passed call-by-writeback. That is,
1360/// we are passing the address of
1361static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
1362 const ObjCIndirectCopyRestoreExpr *CRE) {
1363 llvm::Value *srcAddr = CGF.EmitScalarExpr(CRE->getSubExpr());
1364
1365 // The dest and src types don't necessarily match in LLVM terms
1366 // because of the crazy ObjC compatibility rules.
1367
Chris Lattner2acc6e32011-07-18 04:24:23 +00001368 llvm::PointerType *destType =
John McCallf85e1932011-06-15 23:02:42 +00001369 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
1370
1371 // If the address is a constant null, just pass the appropriate null.
1372 if (isProvablyNull(srcAddr)) {
1373 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
1374 CRE->getType());
1375 return;
1376 }
1377
1378 QualType srcAddrType =
1379 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1380
1381 // Create the temporary.
1382 llvm::Value *temp = CGF.CreateTempAlloca(destType->getElementType(),
1383 "icr.temp");
1384
1385 // Zero-initialize it if we're not doing a copy-initialization.
1386 bool shouldCopy = CRE->shouldCopy();
1387 if (!shouldCopy) {
1388 llvm::Value *null =
1389 llvm::ConstantPointerNull::get(
1390 cast<llvm::PointerType>(destType->getElementType()));
1391 CGF.Builder.CreateStore(null, temp);
1392 }
1393
1394 llvm::BasicBlock *contBB = 0;
1395
1396 // If the address is *not* known to be non-null, we need to switch.
1397 llvm::Value *finalArgument;
1398
1399 bool provablyNonNull = isProvablyNonNull(srcAddr);
1400 if (provablyNonNull) {
1401 finalArgument = temp;
1402 } else {
1403 llvm::Value *isNull = CGF.Builder.CreateIsNull(srcAddr, "icr.isnull");
1404
1405 finalArgument = CGF.Builder.CreateSelect(isNull,
1406 llvm::ConstantPointerNull::get(destType),
1407 temp, "icr.argument");
1408
1409 // If we need to copy, then the load has to be conditional, which
1410 // means we need control flow.
1411 if (shouldCopy) {
1412 contBB = CGF.createBasicBlock("icr.cont");
1413 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
1414 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
1415 CGF.EmitBlock(copyBB);
1416 }
1417 }
1418
1419 // Perform a copy if necessary.
1420 if (shouldCopy) {
1421 LValue srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
John McCall545d9962011-06-25 02:11:03 +00001422 RValue srcRV = CGF.EmitLoadOfLValue(srcLV);
John McCallf85e1932011-06-15 23:02:42 +00001423 assert(srcRV.isScalar());
1424
1425 llvm::Value *src = srcRV.getScalarVal();
1426 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
1427 "icr.cast");
1428
1429 // Use an ordinary store, not a store-to-lvalue.
1430 CGF.Builder.CreateStore(src, temp);
1431 }
1432
1433 // Finish the control flow if we needed it.
1434 if (shouldCopy && !provablyNonNull)
1435 CGF.EmitBlock(contBB);
1436
1437 args.addWriteback(srcAddr, srcAddrType, temp);
1438 args.add(RValue::get(finalArgument), CRE->getType());
1439}
1440
John McCall413ebdb2011-03-11 20:59:21 +00001441void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
1442 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00001443 if (const ObjCIndirectCopyRestoreExpr *CRE
1444 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
1445 assert(getContext().getLangOptions().ObjCAutoRefCount);
1446 assert(getContext().hasSameType(E->getType(), type));
1447 return emitWritebackArg(*this, args, CRE);
1448 }
1449
John McCall8affed52011-08-26 18:42:59 +00001450 assert(type->isReferenceType() == E->isGLValue() &&
1451 "reference binding to unmaterialized r-value!");
1452
John McCallcec52f02011-08-26 21:08:13 +00001453 if (E->isGLValue()) {
1454 assert(E->getObjectKind() == OK_Ordinary);
John McCall413ebdb2011-03-11 20:59:21 +00001455 return args.add(EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0),
1456 type);
John McCallcec52f02011-08-26 21:08:13 +00001457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Eli Friedman70cbd2a2011-06-15 18:26:32 +00001459 if (hasAggregateLLVMType(type) && !E->getType()->isAnyComplexType() &&
1460 isa<ImplicitCastExpr>(E) &&
Eli Friedman55d48482011-05-26 00:10:27 +00001461 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
1462 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
1463 assert(L.isSimple());
1464 args.add(RValue::getAggregate(L.getAddress(), L.isVolatileQualified()),
1465 type, /*NeedsCopy*/true);
1466 return;
1467 }
1468
John McCall413ebdb2011-03-11 20:59:21 +00001469 args.add(EmitAnyExprToTemp(E), type);
Anders Carlsson0139bb92009-04-08 20:47:54 +00001470}
1471
John McCallf1549f62010-07-06 01:34:17 +00001472/// Emits a call or invoke instruction to the given function, depending
1473/// on the current state of the EH stack.
1474llvm::CallSite
1475CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00001476 ArrayRef<llvm::Value *> Args,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001477 const Twine &Name) {
John McCallf1549f62010-07-06 01:34:17 +00001478 llvm::BasicBlock *InvokeDest = getInvokeDest();
1479 if (!InvokeDest)
Jay Foad4c7d9f12011-07-15 08:37:34 +00001480 return Builder.CreateCall(Callee, Args, Name);
John McCallf1549f62010-07-06 01:34:17 +00001481
1482 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
1483 llvm::InvokeInst *Invoke = Builder.CreateInvoke(Callee, ContBB, InvokeDest,
Jay Foad4c7d9f12011-07-15 08:37:34 +00001484 Args, Name);
John McCallf1549f62010-07-06 01:34:17 +00001485 EmitBlock(ContBB);
1486 return Invoke;
1487}
1488
Jay Foad4c7d9f12011-07-15 08:37:34 +00001489llvm::CallSite
1490CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001491 const Twine &Name) {
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00001492 return EmitCallOrInvoke(Callee, ArrayRef<llvm::Value *>(), Name);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001493}
1494
Chris Lattner70855442011-07-12 04:46:18 +00001495static void checkArgMatches(llvm::Value *Elt, unsigned &ArgNo,
1496 llvm::FunctionType *FTy) {
1497 if (ArgNo < FTy->getNumParams())
1498 assert(Elt->getType() == FTy->getParamType(ArgNo));
1499 else
1500 assert(FTy->isVarArg());
1501 ++ArgNo;
1502}
1503
Chris Lattner811bf362011-07-12 06:29:11 +00001504void CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001505 SmallVector<llvm::Value*,16> &Args,
Chris Lattner811bf362011-07-12 06:29:11 +00001506 llvm::FunctionType *IRFuncTy) {
Bob Wilson194f06a2011-08-03 05:58:22 +00001507 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1508 unsigned NumElts = AT->getSize().getZExtValue();
1509 QualType EltTy = AT->getElementType();
1510 llvm::Value *Addr = RV.getAggregateAddr();
1511 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
1512 llvm::Value *EltAddr = Builder.CreateConstGEP2_32(Addr, 0, Elt);
1513 LValue LV = MakeAddrLValue(EltAddr, EltTy);
1514 RValue EltRV;
1515 if (CodeGenFunction::hasAggregateLLVMType(EltTy))
1516 EltRV = RValue::getAggregate(LV.getAddress());
1517 else
1518 EltRV = EmitLoadOfLValue(LV);
1519 ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
Chris Lattner811bf362011-07-12 06:29:11 +00001520 }
Bob Wilson194f06a2011-08-03 05:58:22 +00001521 } else if (const RecordType *RT = Ty->getAsStructureType()) {
1522 RecordDecl *RD = RT->getDecl();
1523 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1524 llvm::Value *Addr = RV.getAggregateAddr();
1525 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1526 i != e; ++i) {
1527 FieldDecl *FD = *i;
1528 QualType FT = FD->getType();
Chris Lattner811bf362011-07-12 06:29:11 +00001529
Bob Wilson194f06a2011-08-03 05:58:22 +00001530 // FIXME: What are the right qualifiers here?
1531 LValue LV = EmitLValueForField(Addr, FD, 0);
1532 RValue FldRV;
1533 if (CodeGenFunction::hasAggregateLLVMType(FT))
1534 FldRV = RValue::getAggregate(LV.getAddress());
1535 else
1536 FldRV = EmitLoadOfLValue(LV);
1537 ExpandTypeToArgs(FT, FldRV, Args, IRFuncTy);
1538 }
1539 } else if (isa<ComplexType>(Ty)) {
1540 ComplexPairTy CV = RV.getComplexVal();
1541 Args.push_back(CV.first);
1542 Args.push_back(CV.second);
1543 } else {
Chris Lattner811bf362011-07-12 06:29:11 +00001544 assert(RV.isScalar() &&
1545 "Unexpected non-scalar rvalue during struct expansion.");
1546
1547 // Insert a bitcast as needed.
1548 llvm::Value *V = RV.getScalarVal();
1549 if (Args.size() < IRFuncTy->getNumParams() &&
1550 V->getType() != IRFuncTy->getParamType(Args.size()))
1551 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(Args.size()));
1552
1553 Args.push_back(V);
1554 }
1555}
1556
1557
Daniel Dunbar88b53962009-02-02 22:03:45 +00001558RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001559 llvm::Value *Callee,
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001560 ReturnValueSlot ReturnValue,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00001561 const CallArgList &CallArgs,
David Chisnalldd5c98f2010-05-01 11:15:56 +00001562 const Decl *TargetDecl,
David Chisnall4b02afc2010-05-02 13:41:58 +00001563 llvm::Instruction **callOrInvoke) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001564 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001565 SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001566
1567 // Handle struct-return functions by passing a pointer to the
1568 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001569 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001570 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Chris Lattner70855442011-07-12 04:46:18 +00001572 // IRArgNo - Keep track of the argument number in the callee we're looking at.
1573 unsigned IRArgNo = 0;
1574 llvm::FunctionType *IRFuncTy =
1575 cast<llvm::FunctionType>(
1576 cast<llvm::PointerType>(Callee->getType())->getElementType());
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattner5db7ae52009-06-13 00:26:38 +00001578 // If the call returns a temporary with struct return, create a temporary
Anders Carlssond2490a92009-12-24 20:40:36 +00001579 // alloca to hold the result, unless one is given to us.
Daniel Dunbardacf9dd2010-07-14 23:39:36 +00001580 if (CGM.ReturnTypeUsesSRet(CallInfo)) {
Anders Carlssond2490a92009-12-24 20:40:36 +00001581 llvm::Value *Value = ReturnValue.getValue();
1582 if (!Value)
Daniel Dunbar195337d2010-02-09 02:48:28 +00001583 Value = CreateMemTemp(RetTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00001584 Args.push_back(Value);
Chris Lattner70855442011-07-12 04:46:18 +00001585 checkArgMatches(Value, IRArgNo, IRFuncTy);
Anders Carlssond2490a92009-12-24 20:40:36 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001588 assert(CallInfo.arg_size() == CallArgs.size() &&
1589 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00001590 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001591 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001592 I != E; ++I, ++info_it) {
1593 const ABIArgInfo &ArgInfo = info_it->info;
Eli Friedmanc6d07822011-05-02 18:05:27 +00001594 RValue RV = I->RV;
Daniel Dunbar56273772008-09-17 00:51:38 +00001595
Eli Friedman97cb5a42011-06-15 22:09:18 +00001596 unsigned TypeAlign =
Eli Friedmanc6d07822011-05-02 18:05:27 +00001597 getContext().getTypeAlignInChars(I->Ty).getQuantity();
Daniel Dunbar56273772008-09-17 00:51:38 +00001598 switch (ArgInfo.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001599 case ABIArgInfo::Indirect: {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001600 if (RV.isScalar() || RV.isComplex()) {
1601 // Make a temporary alloca to pass the argument.
Eli Friedman70cbd2a2011-06-15 18:26:32 +00001602 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1603 if (ArgInfo.getIndirectAlign() > AI->getAlignment())
1604 AI->setAlignment(ArgInfo.getIndirectAlign());
1605 Args.push_back(AI);
Chris Lattner70855442011-07-12 04:46:18 +00001606
Daniel Dunbar1f745982009-02-05 09:16:39 +00001607 if (RV.isScalar())
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001608 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false,
Eli Friedman97cb5a42011-06-15 22:09:18 +00001609 TypeAlign, I->Ty);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001610 else
Mike Stump1eb44332009-09-09 15:08:12 +00001611 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
Chris Lattner70855442011-07-12 04:46:18 +00001612
1613 // Validate argument match.
1614 checkArgMatches(AI, IRArgNo, IRFuncTy);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001615 } else {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001616 // We want to avoid creating an unnecessary temporary+copy here;
1617 // however, we need one in two cases:
1618 // 1. If the argument is not byval, and we are required to copy the
1619 // source. (This case doesn't occur on any common architecture.)
1620 // 2. If the argument is byval, RV is not sufficiently aligned, and
1621 // we cannot force it to be sufficiently aligned.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001622 llvm::Value *Addr = RV.getAggregateAddr();
1623 unsigned Align = ArgInfo.getIndirectAlign();
1624 const llvm::TargetData *TD = &CGM.getTargetData();
1625 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
1626 (ArgInfo.getIndirectByVal() && TypeAlign < Align &&
1627 llvm::getOrEnforceKnownAlignment(Addr, Align, TD) < Align)) {
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001628 // Create an aligned temporary, and copy to it.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001629 llvm::AllocaInst *AI = CreateMemTemp(I->Ty);
1630 if (Align > AI->getAlignment())
1631 AI->setAlignment(Align);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001632 Args.push_back(AI);
Eli Friedman97cb5a42011-06-15 22:09:18 +00001633 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
Chris Lattner70855442011-07-12 04:46:18 +00001634
1635 // Validate argument match.
1636 checkArgMatches(AI, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001637 } else {
1638 // Skip the extra memcpy call.
Eli Friedman97cb5a42011-06-15 22:09:18 +00001639 Args.push_back(Addr);
Chris Lattner70855442011-07-12 04:46:18 +00001640
1641 // Validate argument match.
1642 checkArgMatches(Addr, IRArgNo, IRFuncTy);
Eli Friedmanea5e4da2011-06-14 01:37:52 +00001643 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001644 }
1645 break;
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001646 }
Daniel Dunbar1f745982009-02-05 09:16:39 +00001647
Daniel Dunbar11434922009-01-26 21:26:08 +00001648 case ABIArgInfo::Ignore:
1649 break;
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001650
Chris Lattner800588f2010-07-29 06:26:06 +00001651 case ABIArgInfo::Extend:
1652 case ABIArgInfo::Direct: {
1653 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
Chris Lattner117e3f42010-07-30 04:02:24 +00001654 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
1655 ArgInfo.getDirectOffset() == 0) {
Chris Lattner70855442011-07-12 04:46:18 +00001656 llvm::Value *V;
Chris Lattner800588f2010-07-29 06:26:06 +00001657 if (RV.isScalar())
Chris Lattner70855442011-07-12 04:46:18 +00001658 V = RV.getScalarVal();
Chris Lattner800588f2010-07-29 06:26:06 +00001659 else
Chris Lattner70855442011-07-12 04:46:18 +00001660 V = Builder.CreateLoad(RV.getAggregateAddr());
1661
Chris Lattner21ca1fd2011-07-12 04:53:39 +00001662 // If the argument doesn't match, perform a bitcast to coerce it. This
1663 // can happen due to trivial type mismatches.
1664 if (IRArgNo < IRFuncTy->getNumParams() &&
1665 V->getType() != IRFuncTy->getParamType(IRArgNo))
1666 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRArgNo));
Chris Lattner70855442011-07-12 04:46:18 +00001667 Args.push_back(V);
1668
Chris Lattner70855442011-07-12 04:46:18 +00001669 checkArgMatches(V, IRArgNo, IRFuncTy);
Chris Lattner800588f2010-07-29 06:26:06 +00001670 break;
1671 }
Daniel Dunbar11434922009-01-26 21:26:08 +00001672
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001673 // FIXME: Avoid the conversion through memory if possible.
1674 llvm::Value *SrcPtr;
1675 if (RV.isScalar()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00001676 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Eli Friedman97cb5a42011-06-15 22:09:18 +00001677 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, TypeAlign, I->Ty);
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001678 } else if (RV.isComplex()) {
Eli Friedmanc6d07822011-05-02 18:05:27 +00001679 SrcPtr = CreateMemTemp(I->Ty, "coerce");
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001680 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001681 } else
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001682 SrcPtr = RV.getAggregateAddr();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001683
Chris Lattner117e3f42010-07-30 04:02:24 +00001684 // If the value is offset in memory, apply the offset now.
1685 if (unsigned Offs = ArgInfo.getDirectOffset()) {
1686 SrcPtr = Builder.CreateBitCast(SrcPtr, Builder.getInt8PtrTy());
1687 SrcPtr = Builder.CreateConstGEP1_32(SrcPtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001688 SrcPtr = Builder.CreateBitCast(SrcPtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001689 llvm::PointerType::getUnqual(ArgInfo.getCoerceToType()));
1690
1691 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001692
Chris Lattnerce700162010-06-28 23:44:11 +00001693 // If the coerce-to type is a first class aggregate, we flatten it and
1694 // pass the elements. Either way is semantically identical, but fast-isel
1695 // and the optimizer generally likes scalar values better than FCAs.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001696 if (llvm::StructType *STy =
Chris Lattner309c59f2010-06-29 00:06:42 +00001697 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
Chris Lattner92826882010-07-05 20:41:41 +00001698 SrcPtr = Builder.CreateBitCast(SrcPtr,
1699 llvm::PointerType::getUnqual(STy));
1700 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1701 llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
Chris Lattnerdeabde22010-07-28 18:24:28 +00001702 llvm::LoadInst *LI = Builder.CreateLoad(EltPtr);
1703 // We don't know what we're loading from.
1704 LI->setAlignment(1);
1705 Args.push_back(LI);
Chris Lattner70855442011-07-12 04:46:18 +00001706
1707 // Validate argument match.
1708 checkArgMatches(LI, IRArgNo, IRFuncTy);
Chris Lattner309c59f2010-06-29 00:06:42 +00001709 }
Chris Lattnerce700162010-06-28 23:44:11 +00001710 } else {
Chris Lattner309c59f2010-06-29 00:06:42 +00001711 // In the simple case, just pass the coerced loaded value.
1712 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1713 *this));
Chris Lattner70855442011-07-12 04:46:18 +00001714
1715 // Validate argument match.
1716 checkArgMatches(Args.back(), IRArgNo, IRFuncTy);
Chris Lattnerce700162010-06-28 23:44:11 +00001717 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001718
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001719 break;
1720 }
1721
Daniel Dunbar56273772008-09-17 00:51:38 +00001722 case ABIArgInfo::Expand:
Chris Lattner811bf362011-07-12 06:29:11 +00001723 ExpandTypeToArgs(I->Ty, RV, Args, IRFuncTy);
Chris Lattner70855442011-07-12 04:46:18 +00001724 IRArgNo = Args.size();
Daniel Dunbar56273772008-09-17 00:51:38 +00001725 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001726 }
1727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Chris Lattner5db7ae52009-06-13 00:26:38 +00001729 // If the callee is a bitcast of a function to a varargs pointer to function
1730 // type, check to see if we can remove the bitcast. This handles some cases
1731 // with unprototyped functions.
1732 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
1733 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001734 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
1735 llvm::FunctionType *CurFT =
Chris Lattner5db7ae52009-06-13 00:26:38 +00001736 cast<llvm::FunctionType>(CurPT->getElementType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001737 llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Chris Lattner5db7ae52009-06-13 00:26:38 +00001739 if (CE->getOpcode() == llvm::Instruction::BitCast &&
1740 ActualFT->getReturnType() == CurFT->getReturnType() &&
Chris Lattnerd6bebbf2009-06-23 01:38:41 +00001741 ActualFT->getNumParams() == CurFT->getNumParams() &&
Fariborz Jahanianc0ddef22011-03-01 17:28:13 +00001742 ActualFT->getNumParams() == Args.size() &&
1743 (CurFT->isVarArg() || !ActualFT->isVarArg())) {
Chris Lattner5db7ae52009-06-13 00:26:38 +00001744 bool ArgsMatch = true;
1745 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
1746 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
1747 ArgsMatch = false;
1748 break;
1749 }
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner5db7ae52009-06-13 00:26:38 +00001751 // Strip the cast if we can get away with it. This is a nice cleanup,
1752 // but also allows us to inline the function at -O0 if it is marked
1753 // always_inline.
1754 if (ArgsMatch)
1755 Callee = CalleeF;
1756 }
1757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001759 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +00001760 CodeGen::AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001761 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001762 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1763 AttributeList.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001764
John McCallf1549f62010-07-06 01:34:17 +00001765 llvm::BasicBlock *InvokeDest = 0;
1766 if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind))
1767 InvokeDest = getInvokeDest();
1768
Daniel Dunbard14151d2009-03-02 04:32:35 +00001769 llvm::CallSite CS;
John McCallf1549f62010-07-06 01:34:17 +00001770 if (!InvokeDest) {
Jay Foad4c7d9f12011-07-15 08:37:34 +00001771 CS = Builder.CreateCall(Callee, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001772 } else {
1773 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Jay Foad4c7d9f12011-07-15 08:37:34 +00001774 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, Args);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00001775 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00001776 }
Chris Lattnerce933992010-06-29 16:40:28 +00001777 if (callOrInvoke)
David Chisnall4b02afc2010-05-02 13:41:58 +00001778 *callOrInvoke = CS.getInstruction();
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00001779
Daniel Dunbard14151d2009-03-02 04:32:35 +00001780 CS.setAttributes(Attrs);
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001781 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbard14151d2009-03-02 04:32:35 +00001782
1783 // If the call doesn't return, finish the basic block and clear the
1784 // insertion point; this allows the rest of IRgen to discard
1785 // unreachable code.
1786 if (CS.doesNotReturn()) {
1787 Builder.CreateUnreachable();
1788 Builder.ClearInsertionPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Mike Stumpf5408fe2009-05-16 07:57:57 +00001790 // FIXME: For now, emit a dummy basic block because expr emitters in
1791 // generally are not ready to handle emitting expressions at unreachable
1792 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00001793 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Daniel Dunbard14151d2009-03-02 04:32:35 +00001795 // Return a reasonable RValue.
1796 return GetUndefRValue(RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001797 }
Daniel Dunbard14151d2009-03-02 04:32:35 +00001798
1799 llvm::Instruction *CI = CS.getInstruction();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001800 if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001801 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001802
John McCallf85e1932011-06-15 23:02:42 +00001803 // Emit any writebacks immediately. Arguably this should happen
1804 // after any return-value munging.
1805 if (CallArgs.hasWritebacks())
1806 emitWritebacks(*this, CallArgs);
1807
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001808 switch (RetAI.getKind()) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001809 case ABIArgInfo::Indirect: {
1810 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001811 if (RetTy->isAnyComplexType())
Daniel Dunbar56273772008-09-17 00:51:38 +00001812 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattner34030842009-03-22 00:32:22 +00001813 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar56273772008-09-17 00:51:38 +00001814 return RValue::getAggregate(Args[0]);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001815 return RValue::get(EmitLoadOfScalar(Args[0], false, Alignment, RetTy));
1816 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001817
Daniel Dunbar11434922009-01-26 21:26:08 +00001818 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001819 // If we are ignoring an argument that had a result, make sure to
1820 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00001821 return GetUndefRValue(RetTy);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001822
Chris Lattner800588f2010-07-29 06:26:06 +00001823 case ABIArgInfo::Extend:
1824 case ABIArgInfo::Direct: {
Chris Lattner6af13f32011-07-13 03:59:32 +00001825 llvm::Type *RetIRTy = ConvertType(RetTy);
1826 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
Chris Lattner800588f2010-07-29 06:26:06 +00001827 if (RetTy->isAnyComplexType()) {
1828 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1829 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1830 return RValue::getComplex(std::make_pair(Real, Imag));
1831 }
1832 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1833 llvm::Value *DestPtr = ReturnValue.getValue();
1834 bool DestIsVolatile = ReturnValue.isVolatile();
Daniel Dunbar11434922009-01-26 21:26:08 +00001835
Chris Lattner800588f2010-07-29 06:26:06 +00001836 if (!DestPtr) {
1837 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
1838 DestIsVolatile = false;
1839 }
Eli Friedmanbadea572011-05-17 21:08:01 +00001840 BuildAggStore(*this, CI, DestPtr, DestIsVolatile, false);
Chris Lattner800588f2010-07-29 06:26:06 +00001841 return RValue::getAggregate(DestPtr);
1842 }
Chris Lattner6af13f32011-07-13 03:59:32 +00001843
1844 // If the argument doesn't match, perform a bitcast to coerce it. This
1845 // can happen due to trivial type mismatches.
1846 llvm::Value *V = CI;
1847 if (V->getType() != RetIRTy)
1848 V = Builder.CreateBitCast(V, RetIRTy);
1849 return RValue::get(V);
Chris Lattner800588f2010-07-29 06:26:06 +00001850 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001851
Anders Carlssond2490a92009-12-24 20:40:36 +00001852 llvm::Value *DestPtr = ReturnValue.getValue();
1853 bool DestIsVolatile = ReturnValue.isVolatile();
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001854
Anders Carlssond2490a92009-12-24 20:40:36 +00001855 if (!DestPtr) {
Daniel Dunbar195337d2010-02-09 02:48:28 +00001856 DestPtr = CreateMemTemp(RetTy, "coerce");
Anders Carlssond2490a92009-12-24 20:40:36 +00001857 DestIsVolatile = false;
1858 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001859
Chris Lattner117e3f42010-07-30 04:02:24 +00001860 // If the value is offset in memory, apply the offset now.
1861 llvm::Value *StorePtr = DestPtr;
1862 if (unsigned Offs = RetAI.getDirectOffset()) {
1863 StorePtr = Builder.CreateBitCast(StorePtr, Builder.getInt8PtrTy());
1864 StorePtr = Builder.CreateConstGEP1_32(StorePtr, Offs);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001865 StorePtr = Builder.CreateBitCast(StorePtr,
Chris Lattner117e3f42010-07-30 04:02:24 +00001866 llvm::PointerType::getUnqual(RetAI.getCoerceToType()));
1867 }
1868 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001869
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001870 unsigned Alignment = getContext().getTypeAlignInChars(RetTy).getQuantity();
Anders Carlssonad3d6912008-11-25 22:21:48 +00001871 if (RetTy->isAnyComplexType())
Anders Carlssond2490a92009-12-24 20:40:36 +00001872 return RValue::getComplex(LoadComplexFromAddr(DestPtr, false));
Chris Lattner34030842009-03-22 00:32:22 +00001873 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssond2490a92009-12-24 20:40:36 +00001874 return RValue::getAggregate(DestPtr);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +00001875 return RValue::get(EmitLoadOfScalar(DestPtr, false, Alignment, RetTy));
Daniel Dunbar639ffe42008-09-10 07:04:09 +00001876 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001877
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001878 case ABIArgInfo::Expand:
David Blaikieb219cfc2011-09-23 05:06:16 +00001879 llvm_unreachable("Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001880 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001881
David Blaikieb219cfc2011-09-23 05:06:16 +00001882 llvm_unreachable("Unhandled ABIArgInfo::Kind");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001883}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001884
1885/* VarArg handling */
1886
1887llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1888 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1889}