blob: 25ca4df3a15d4c8a49851996ca01a4d226d1d0ba [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +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// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000027RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
28 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
29 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
30 const CallExpr *CE) {
31 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson27da15b2010-01-01 20:29:01 +000035
Richard Smith69d0d262012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
Richard Smith4d3110a2012-10-25 02:14:12 +000042 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
43 : TCK_MemberCall,
44 CallLoc, This, getContext().getRecordType(MD->getParent()));
Richard Smith69d0d262012-08-24 00:54:33 +000045
Anders Carlsson27da15b2010-01-01 20:29:01 +000046 CallArgList Args;
47
48 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000049 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000050
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000051 // If there is an implicit parameter (e.g. VTT), emit it.
52 if (ImplicitParam) {
53 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000054 }
John McCalla729c622012-02-17 03:33:10 +000055
56 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssone36a6b32010-01-02 01:01:18 +000058
John McCalla729c622012-02-17 03:33:10 +000059 // And the rest of the call args.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000060 CallExpr::const_arg_iterator ArgBeg, ArgEnd;
61 if (CE == nullptr) {
62 ArgBeg = ArgEnd = nullptr;
63 } else if (auto OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
64 // Special case: skip first argument of CXXOperatorCall (it is "this").
65 ArgBeg = OCE->arg_begin() + 1;
66 ArgEnd = OCE->arg_end();
67 } else {
68 ArgBeg = CE->arg_begin();
69 ArgEnd = CE->arg_end();
70 }
Anders Carlsson27da15b2010-01-01 20:29:01 +000071 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
72
John McCall8dda7b22012-07-07 06:41:13 +000073 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000074 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000075}
76
Rafael Espindola3b33c4e2012-06-28 14:28:57 +000077static CXXRecordDecl *getCXXRecord(const Expr *E) {
78 QualType T = E->getType();
79 if (const PointerType *PTy = T->getAs<PointerType>())
80 T = PTy->getPointeeType();
81 const RecordType *Ty = T->castAs<RecordType>();
82 return cast<CXXRecordDecl>(Ty->getDecl());
83}
84
Francois Pichet64225792011-01-18 05:04:39 +000085// Note: This function also emit constructor calls to support a MSVC
86// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +000087RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
88 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +000089 const Expr *callee = CE->getCallee()->IgnoreParens();
90
91 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +000092 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +000093
94 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +000095 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
96
97 if (MD->isStatic()) {
98 // The method is static, emit it as we would a regular call.
99 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000100 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
101 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000102 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000103
John McCall0d635f52010-09-03 01:26:39 +0000104 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000105 const Expr *Base = ME->getBase();
106 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000107
Craig Topper8a13c412014-05-21 05:09:00 +0000108 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000109 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000110 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
111 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
112 assert(DevirtualizedMethod);
113 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
114 const Expr *Inner = Base->ignoreParenBaseCasts();
115 if (getCXXRecord(Inner) == DevirtualizedClass)
116 // If the class of the Inner expression is where the dynamic method
117 // is defined, build the this pointer from it.
118 Base = Inner;
119 else if (getCXXRecord(Base) != DevirtualizedClass) {
120 // If the method is defined in a class that is not the best dynamic
121 // one or the one of the full expression, we would have to build
122 // a derived-to-base cast to compute the correct this pointer, but
123 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000124 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000125 }
Rafael Espindolab27564a2012-06-28 17:57:36 +0000126 // If the return types are not the same, this might be a case where more
127 // code needs to run to compensate for it. For example, the derived
128 // method might return a type that inherits form from the return
129 // type of MD and has a prefix.
130 // For now we just avoid devirtualizing these covariant cases.
131 if (DevirtualizedMethod &&
Alp Toker314cc812014-01-25 16:55:45 +0000132 DevirtualizedMethod->getReturnType().getCanonicalType() !=
133 MD->getReturnType().getCanonicalType())
Craig Topper8a13c412014-05-21 05:09:00 +0000134 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000135 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000136
Anders Carlsson27da15b2010-01-01 20:29:01 +0000137 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000138 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000139 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000140 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000141 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000142
Anders Carlsson27da15b2010-01-01 20:29:01 +0000143
John McCall0d635f52010-09-03 01:26:39 +0000144 if (MD->isTrivial()) {
Craig Topper8a13c412014-05-21 05:09:00 +0000145 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000146 if (isa<CXXConstructorDecl>(MD) &&
147 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000148 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000149
Sebastian Redl22653ba2011-08-30 19:58:05 +0000150 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
151 // We don't like to generate the trivial copy/move assignment operator
152 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000153 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000154 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000155 return RValue::get(This);
156 }
157
158 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000159 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
160 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000161 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
162 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
163 CE->arg_begin(), CE->arg_end());
164 return RValue::get(This);
165 }
166 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000167 }
168
John McCall0d635f52010-09-03 01:26:39 +0000169 // Compute the function type we're calling.
Eli Friedmanade60972012-10-25 00:12:49 +0000170 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000171 const CGFunctionInfo *FInfo = nullptr;
Eli Friedmanade60972012-10-25 00:12:49 +0000172 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
173 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCalla729c622012-02-17 03:33:10 +0000174 Dtor_Complete);
Eli Friedmanade60972012-10-25 00:12:49 +0000175 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
176 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
177 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000178 else
Eli Friedmanade60972012-10-25 00:12:49 +0000179 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000180
Reid Klecknere7de47e2013-07-22 13:51:44 +0000181 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000182
Anders Carlsson27da15b2010-01-01 20:29:01 +0000183 // C++ [class.virtual]p12:
184 // Explicit qualification with the scope operator (5.1) suppresses the
185 // virtual call mechanism.
186 //
187 // We also don't emit a virtual call if the base expression has a record type
188 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000189 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000190 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000191
John McCall0d635f52010-09-03 01:26:39 +0000192 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000193 assert(CE->arg_begin() == CE->arg_end() &&
194 "Destructor shouldn't have explicit parameters");
195 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000196 if (UseVirtualCall) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000197 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000198 This, CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000199 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000200 if (getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000201 MD->isVirtual() &&
202 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000203 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000204 else if (!DevirtualizedMethod)
Reid Klecknere7de47e2013-07-22 13:51:44 +0000205 Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000206 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000207 const CXXDestructorDecl *DDtor =
208 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000209 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
210 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000211 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
212 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000213 }
Craig Topper8a13c412014-05-21 05:09:00 +0000214 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000215 }
216
217 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000218 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000219 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000220 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000222 if (getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000223 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000224 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000225 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000226 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000227 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000228 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000229 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000230 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000231 }
232
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000233 if (MD->isVirtual()) {
234 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
235 *this, MD, This, UseVirtualCall);
236 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000237
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000238 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
239 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000240}
241
242RValue
243CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
244 ReturnValueSlot ReturnValue) {
245 const BinaryOperator *BO =
246 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
247 const Expr *BaseExpr = BO->getLHS();
248 const Expr *MemFnExpr = BO->getRHS();
249
250 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000251 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000252
Anders Carlsson27da15b2010-01-01 20:29:01 +0000253 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000254 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000255 const CXXRecordDecl *RD =
256 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
257
Anders Carlsson27da15b2010-01-01 20:29:01 +0000258 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000259 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000260
261 // Emit the 'this' pointer.
262 llvm::Value *This;
263
John McCalle3027922010-08-25 11:45:40 +0000264 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000265 This = EmitScalarExpr(BaseExpr);
266 else
267 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000268
Richard Smithe30752c2012-10-09 19:52:38 +0000269 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
270 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000271
John McCall475999d2010-08-22 00:05:51 +0000272 // Ask the ABI to load the callee. Note that This is modified.
273 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000274 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000275
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 CallArgList Args;
277
278 QualType ThisType =
279 getContext().getPointerType(getContext().getTagDeclType(RD));
280
281 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000282 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000283
284 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000285
286 // And the rest of the call args
287 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000288 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
289 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000290}
291
292RValue
293CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
294 const CXXMethodDecl *MD,
295 ReturnValueSlot ReturnValue) {
296 assert(MD->isInstance() &&
297 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000298 LValue LV = EmitLValue(E->getArg(0));
299 llvm::Value *This = LV.getAddress();
300
Douglas Gregor146b8e92011-09-06 16:26:56 +0000301 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
302 MD->isTrivial()) {
303 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
304 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000305 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000306 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000307 }
308
Anders Carlssonc36783e2011-05-08 20:32:23 +0000309 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000310 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
311 /*ImplicitParam=*/nullptr, QualType(), E);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312}
313
Peter Collingbournefe883422011-10-06 18:29:37 +0000314RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
315 ReturnValueSlot ReturnValue) {
316 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
317}
318
Eli Friedmanfde961d2011-10-14 02:27:24 +0000319static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
320 llvm::Value *DestPtr,
321 const CXXRecordDecl *Base) {
322 if (Base->isEmpty())
323 return;
324
325 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
326
327 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
328 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000329 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000330
331 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
332
333 // If the type contains a pointer to data member we can't memset it to zero.
334 // Instead, create a null constant and copy it to the destination.
335 // TODO: there are other patterns besides zero that we can usefully memset,
336 // like -1, which happens to be the pattern used by member-pointers.
337 // TODO: isZeroInitializable can be over-conservative in the case where a
338 // virtual base contains a member pointer.
339 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
340 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
341
342 llvm::GlobalVariable *NullVariable =
343 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
344 /*isConstant=*/true,
345 llvm::GlobalVariable::PrivateLinkage,
346 NullConstant, Twine());
347 NullVariable->setAlignment(Align.getQuantity());
348 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
349
350 // Get and call the appropriate llvm.memcpy overload.
351 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
352 return;
353 }
354
355 // Otherwise, just memset the whole thing to zero. This is legal
356 // because in LLVM, all default initializers (other than the ones we just
357 // handled above) are guaranteed to have a bit pattern of all zeros.
358 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
359 Align.getQuantity());
360}
361
Anders Carlsson27da15b2010-01-01 20:29:01 +0000362void
John McCall7a626f62010-09-15 10:14:12 +0000363CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
364 AggValueSlot Dest) {
365 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000366 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000367
368 // If we require zero initialization before (or instead of) calling the
369 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000370 // constructor, emit the zero initialization now, unless destination is
371 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000372 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
373 switch (E->getConstructionKind()) {
374 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000375 case CXXConstructExpr::CK_Complete:
376 EmitNullInitialization(Dest.getAddr(), E->getType());
377 break;
378 case CXXConstructExpr::CK_VirtualBase:
379 case CXXConstructExpr::CK_NonVirtualBase:
380 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
381 break;
382 }
383 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000384
385 // If this is a call to a trivial default constructor, do nothing.
386 if (CD->isTrivial() && CD->isDefaultConstructor())
387 return;
388
John McCall8ea46b62010-09-18 00:58:34 +0000389 // Elide the constructor if we're constructing from a temporary.
390 // The temporary check is required because Sema sets this on NRVO
391 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000392 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000393 assert(getContext().hasSameUnqualifiedType(E->getType(),
394 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000395 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
396 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000397 return;
398 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000399 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000400
John McCallf677a8e2011-07-13 06:10:41 +0000401 if (const ConstantArrayType *arrayType
402 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000403 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000404 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000405 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000406 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000407 bool Delegating = false;
408
Alexis Hunt271c3682011-05-03 20:19:28 +0000409 switch (E->getConstructionKind()) {
410 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000411 // We should be emitting a constructor; GlobalDecl will assert this
412 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000413 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000414 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000415
Alexis Hunt271c3682011-05-03 20:19:28 +0000416 case CXXConstructExpr::CK_Complete:
417 Type = Ctor_Complete;
418 break;
419
420 case CXXConstructExpr::CK_VirtualBase:
421 ForVirtualBase = true;
422 // fall-through
423
424 case CXXConstructExpr::CK_NonVirtualBase:
425 Type = Ctor_Base;
426 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000427
Anders Carlsson27da15b2010-01-01 20:29:01 +0000428 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000429 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000430 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000431 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000432}
433
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000434void
435CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
436 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000437 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000438 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000439 Exp = E->getSubExpr();
440 assert(isa<CXXConstructExpr>(Exp) &&
441 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
442 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
443 const CXXConstructorDecl *CD = E->getConstructor();
444 RunCleanupsScope Scope(*this);
445
446 // If we require zero initialization before (or instead of) calling the
447 // constructor, as can be the case with a non-user-provided default
448 // constructor, emit the zero initialization now.
449 // FIXME. Do I still need this for a copy ctor synthesis?
450 if (E->requiresZeroInitialization())
451 EmitNullInitialization(Dest, E->getType());
452
Chandler Carruth99da11c2010-11-15 13:54:43 +0000453 assert(!getContext().getAsConstantArrayType(E->getType())
454 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000455 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E->arg_begin(), E->arg_end());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000456}
457
John McCall8ed55a52010-09-02 09:58:18 +0000458static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
459 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000460 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000461 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000462
John McCall7ec4b432011-05-16 01:05:12 +0000463 // No cookie is required if the operator new[] being used is the
464 // reserved placement operator new[].
465 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000466 return CharUnits::Zero();
467
John McCall284c48f2011-01-27 09:37:56 +0000468 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000469}
470
John McCall036f2f62011-05-15 07:14:44 +0000471static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
472 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000473 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000474 llvm::Value *&numElements,
475 llvm::Value *&sizeWithoutCookie) {
476 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000477
John McCall036f2f62011-05-15 07:14:44 +0000478 if (!e->isArray()) {
479 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
480 sizeWithoutCookie
481 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
482 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000483 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000484
John McCall036f2f62011-05-15 07:14:44 +0000485 // The width of size_t.
486 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
487
John McCall8ed55a52010-09-02 09:58:18 +0000488 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000489 llvm::APInt cookieSize(sizeWidth,
490 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000491
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000492 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000493 // We multiply the size of all dimensions for NumElements.
494 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000495 numElements = CGF.EmitScalarExpr(e->getArraySize());
496 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000497
John McCall036f2f62011-05-15 07:14:44 +0000498 // The number of elements can be have an arbitrary integer type;
499 // essentially, we need to multiply it by a constant factor, add a
500 // cookie size, and verify that the result is representable as a
501 // size_t. That's just a gloss, though, and it's wrong in one
502 // important way: if the count is negative, it's an error even if
503 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000504 bool isSigned
505 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000506 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000507 = cast<llvm::IntegerType>(numElements->getType());
508 unsigned numElementsWidth = numElementsType->getBitWidth();
509
510 // Compute the constant factor.
511 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000512 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000513 = CGF.getContext().getAsConstantArrayType(type)) {
514 type = CAT->getElementType();
515 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000516 }
517
John McCall036f2f62011-05-15 07:14:44 +0000518 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
519 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
520 typeSizeMultiplier *= arraySizeMultiplier;
521
522 // This will be a size_t.
523 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000524
Chris Lattner32ac5832010-07-20 21:55:52 +0000525 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
526 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000527 if (llvm::ConstantInt *numElementsC =
528 dyn_cast<llvm::ConstantInt>(numElements)) {
529 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000530
John McCall036f2f62011-05-15 07:14:44 +0000531 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000532
John McCall036f2f62011-05-15 07:14:44 +0000533 // If 'count' was a negative number, it's an overflow.
534 if (isSigned && count.isNegative())
535 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000536
John McCall036f2f62011-05-15 07:14:44 +0000537 // We want to do all this arithmetic in size_t. If numElements is
538 // wider than that, check whether it's already too big, and if so,
539 // overflow.
540 else if (numElementsWidth > sizeWidth &&
541 numElementsWidth - sizeWidth > count.countLeadingZeros())
542 hasAnyOverflow = true;
543
544 // Okay, compute a count at the right width.
545 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
546
Sebastian Redlf862eb62012-02-22 17:37:52 +0000547 // If there is a brace-initializer, we cannot allocate fewer elements than
548 // there are initializers. If we do, that's treated like an overflow.
549 if (adjustedCount.ult(minElements))
550 hasAnyOverflow = true;
551
John McCall036f2f62011-05-15 07:14:44 +0000552 // Scale numElements by that. This might overflow, but we don't
553 // care because it only overflows if allocationSize does, too, and
554 // if that overflows then we shouldn't use this.
555 numElements = llvm::ConstantInt::get(CGF.SizeTy,
556 adjustedCount * arraySizeMultiplier);
557
558 // Compute the size before cookie, and track whether it overflowed.
559 bool overflow;
560 llvm::APInt allocationSize
561 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
562 hasAnyOverflow |= overflow;
563
564 // Add in the cookie, and check whether it's overflowed.
565 if (cookieSize != 0) {
566 // Save the current size without a cookie. This shouldn't be
567 // used if there was overflow.
568 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
569
570 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
571 hasAnyOverflow |= overflow;
572 }
573
574 // On overflow, produce a -1 so operator new will fail.
575 if (hasAnyOverflow) {
576 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
577 } else {
578 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
579 }
580
581 // Otherwise, we might need to use the overflow intrinsics.
582 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000583 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000584 // 1) if isSigned, we need to check whether numElements is negative;
585 // 2) if numElementsWidth > sizeWidth, we need to check whether
586 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000587 // 3) if minElements > 0, we need to check whether numElements is smaller
588 // than that.
589 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000590 // sizeWithoutCookie := numElements * typeSizeMultiplier
591 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000592 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000593 // size := sizeWithoutCookie + cookieSize
594 // and check whether it overflows.
595
Craig Topper8a13c412014-05-21 05:09:00 +0000596 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000597
598 // If numElementsWidth > sizeWidth, then one way or another, we're
599 // going to have to do a comparison for (2), and this happens to
600 // take care of (1), too.
601 if (numElementsWidth > sizeWidth) {
602 llvm::APInt threshold(numElementsWidth, 1);
603 threshold <<= sizeWidth;
604
605 llvm::Value *thresholdV
606 = llvm::ConstantInt::get(numElementsType, threshold);
607
608 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
609 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
610
611 // Otherwise, if we're signed, we want to sext up to size_t.
612 } else if (isSigned) {
613 if (numElementsWidth < sizeWidth)
614 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
615
616 // If there's a non-1 type size multiplier, then we can do the
617 // signedness check at the same time as we do the multiply
618 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000619 // unsigned overflow. Otherwise, we have to do it here. But at least
620 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000621 if (typeSizeMultiplier == 1)
622 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000623 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000624
625 // Otherwise, zext up to size_t if necessary.
626 } else if (numElementsWidth < sizeWidth) {
627 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
628 }
629
630 assert(numElements->getType() == CGF.SizeTy);
631
Sebastian Redlf862eb62012-02-22 17:37:52 +0000632 if (minElements) {
633 // Don't allow allocation of fewer elements than we have initializers.
634 if (!hasOverflow) {
635 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
636 llvm::ConstantInt::get(CGF.SizeTy, minElements));
637 } else if (numElementsWidth > sizeWidth) {
638 // The other existing overflow subsumes this check.
639 // We do an unsigned comparison, since any signed value < -1 is
640 // taken care of either above or below.
641 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
642 CGF.Builder.CreateICmpULT(numElements,
643 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
644 }
645 }
646
John McCall036f2f62011-05-15 07:14:44 +0000647 size = numElements;
648
649 // Multiply by the type size if necessary. This multiplier
650 // includes all the factors for nested arrays.
651 //
652 // This step also causes numElements to be scaled up by the
653 // nested-array factor if necessary. Overflow on this computation
654 // can be ignored because the result shouldn't be used if
655 // allocation fails.
656 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000657 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000658 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000659
660 llvm::Value *tsmV =
661 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
662 llvm::Value *result =
663 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
664
665 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
666 if (hasOverflow)
667 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
668 else
669 hasOverflow = overflowed;
670
671 size = CGF.Builder.CreateExtractValue(result, 0);
672
673 // Also scale up numElements by the array size multiplier.
674 if (arraySizeMultiplier != 1) {
675 // If the base element type size is 1, then we can re-use the
676 // multiply we just did.
677 if (typeSize.isOne()) {
678 assert(arraySizeMultiplier == typeSizeMultiplier);
679 numElements = size;
680
681 // Otherwise we need a separate multiply.
682 } else {
683 llvm::Value *asmV =
684 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
685 numElements = CGF.Builder.CreateMul(numElements, asmV);
686 }
687 }
688 } else {
689 // numElements doesn't need to be scaled.
690 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000691 }
692
John McCall036f2f62011-05-15 07:14:44 +0000693 // Add in the cookie size if necessary.
694 if (cookieSize != 0) {
695 sizeWithoutCookie = size;
696
John McCall036f2f62011-05-15 07:14:44 +0000697 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000698 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000699
700 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
701 llvm::Value *result =
702 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
703
704 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
705 if (hasOverflow)
706 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
707 else
708 hasOverflow = overflowed;
709
710 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000711 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000712
John McCall036f2f62011-05-15 07:14:44 +0000713 // If we had any possibility of dynamic overflow, make a select to
714 // overwrite 'size' with an all-ones value, which should cause
715 // operator new to throw.
716 if (hasOverflow)
717 size = CGF.Builder.CreateSelect(hasOverflow,
718 llvm::Constant::getAllOnesValue(CGF.SizeTy),
719 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000720 }
John McCall8ed55a52010-09-02 09:58:18 +0000721
John McCall036f2f62011-05-15 07:14:44 +0000722 if (cookieSize == 0)
723 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000724 else
John McCall036f2f62011-05-15 07:14:44 +0000725 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000726
John McCall036f2f62011-05-15 07:14:44 +0000727 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000728}
729
Sebastian Redlf862eb62012-02-22 17:37:52 +0000730static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
731 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000732 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000733 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000734 switch (CGF.getEvaluationKind(AllocType)) {
735 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000736 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
737 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000738 false);
John McCall47fb9502013-03-07 21:37:08 +0000739 return;
740 case TEK_Complex:
741 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
742 Alignment),
743 /*isInit*/ true);
744 return;
745 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000746 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000747 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000748 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000749 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000750 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000751 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000752 return;
John McCall7a626f62010-09-15 10:14:12 +0000753 }
John McCall47fb9502013-03-07 21:37:08 +0000754 }
755 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000756}
757
758void
Richard Smith06a67e22014-06-03 06:58:52 +0000759CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
760 QualType ElementType,
761 llvm::Value *BeginPtr,
762 llvm::Value *NumElements,
763 llvm::Value *AllocSizeWithoutCookie) {
764 // If we have a type with trivial initialization and no initializer,
765 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000766 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000767 return;
John McCall99210dc2011-09-15 06:49:18 +0000768
Richard Smith06a67e22014-06-03 06:58:52 +0000769 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000770
Richard Smith06a67e22014-06-03 06:58:52 +0000771 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000772
773 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000774 llvm::AllocaInst *EndOfInit = nullptr;
775 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
776 EHScopeStack::stable_iterator Cleanup;
777 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000778
Sebastian Redlf862eb62012-02-22 17:37:52 +0000779 // If the initializer is an initializer list, first do the explicit elements.
780 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000781 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000782
Richard Smith1c96bc52013-12-11 01:40:16 +0000783 // If this is a multi-dimensional array new, we will initialize multiple
784 // elements with each init list element.
785 QualType AllocType = E->getAllocatedType();
786 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
787 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000788 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000789 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000790 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
791 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000792 }
793
Richard Smith06a67e22014-06-03 06:58:52 +0000794 // Enter a partial-destruction Cleanup if necessary.
795 if (needsEHCleanup(DtorKind)) {
796 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000797 // directly, but the control flow can get so varied here that it
798 // would actually be quite complex. Therefore we go through an
799 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000800 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
801 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
802 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
803 getDestroyer(DtorKind));
804 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000805 }
806
Sebastian Redlf862eb62012-02-22 17:37:52 +0000807 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000808 // Tell the cleanup that it needs to destroy up to this
809 // element. TODO: some of these stores can be trivially
810 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000811 if (EndOfInit)
812 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
813 EndOfInit);
814 // FIXME: If the last initializer is an incomplete initializer list for
815 // an array, and we have an array filler, we can fold together the two
816 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000817 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000818 ILE->getInit(i)->getType(), CurPtr);
819 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000820 }
821
822 // The remaining elements are filled with the array filler expression.
823 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000824
Richard Smith06a67e22014-06-03 06:58:52 +0000825 // Extract the initializer for the individual array elements by pulling
826 // out the array filler from all the nested initializer lists. This avoids
827 // generating a nested loop for the initialization.
828 while (Init && Init->getType()->isConstantArrayType()) {
829 auto *SubILE = dyn_cast<InitListExpr>(Init);
830 if (!SubILE)
831 break;
832 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
833 Init = SubILE->getArrayFiller();
834 }
835
836 // Switch back to initializing one base element at a time.
837 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000838 }
839
Richard Smith06a67e22014-06-03 06:58:52 +0000840 // Attempt to perform zero-initialization using memset.
841 auto TryMemsetInitialization = [&]() -> bool {
842 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
843 // we can initialize with a memset to -1.
844 if (!CGM.getTypes().isZeroInitializable(ElementType))
845 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000846
Richard Smith06a67e22014-06-03 06:58:52 +0000847 // Optimization: since zero initialization will just set the memory
848 // to all zeroes, generate a single memset to do it in one shot.
849
850 // Subtract out the size of any elements we've already initialized.
851 auto *RemainingSize = AllocSizeWithoutCookie;
852 if (InitListElements) {
853 // We know this can't overflow; we check this when doing the allocation.
854 auto *InitializedSize = llvm::ConstantInt::get(
855 RemainingSize->getType(),
856 getContext().getTypeSizeInChars(ElementType).getQuantity() *
857 InitListElements);
858 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
859 }
860
861 // Create the memset.
862 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
863 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
864 Alignment.getQuantity(), false);
865 return true;
866 };
867
Richard Smith454a7cd2014-06-03 08:26:00 +0000868 // If all elements have already been initialized, skip any further
869 // initialization.
870 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
871 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
872 // If there was a Cleanup, deactivate it.
873 if (CleanupDominator)
874 DeactivateCleanupBlock(Cleanup, CleanupDominator);
875 return;
876 }
877
878 assert(Init && "have trailing elements to initialize but no initializer");
879
Richard Smith06a67e22014-06-03 06:58:52 +0000880 // If this is a constructor call, try to optimize it out, and failing that
881 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000882 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000883 CXXConstructorDecl *Ctor = CCE->getConstructor();
884 if (Ctor->isTrivial()) {
885 // If new expression did not specify value-initialization, then there
886 // is no initialization.
887 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
888 return;
889
890 if (TryMemsetInitialization())
891 return;
892 }
893
894 // Store the new Cleanup position for irregular Cleanups.
895 //
896 // FIXME: Share this cleanup with the constructor call emission rather than
897 // having it create a cleanup of its own.
898 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
899
900 // Emit a constructor call loop to initialize the remaining elements.
901 if (InitListElements)
902 NumElements = Builder.CreateSub(
903 NumElements,
904 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000905 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000906 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000907 return;
908 }
909
Richard Smith06a67e22014-06-03 06:58:52 +0000910 // If this is value-initialization, we can usually use memset.
911 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000912 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000913 if (TryMemsetInitialization())
914 return;
915
916 // Switch to an ImplicitValueInitExpr for the element type. This handles
917 // only one case: multidimensional array new of pointers to members. In
918 // all other cases, we already have an initializer for the array element.
919 Init = &IVIE;
920 }
921
922 // At this point we should have found an initializer for the individual
923 // elements of the array.
924 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
925 "got wrong type of element to initialize");
926
Richard Smith454a7cd2014-06-03 08:26:00 +0000927 // If we have an empty initializer list, we can usually use memset.
928 if (auto *ILE = dyn_cast<InitListExpr>(Init))
929 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
930 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000931
932 // Create the loop blocks.
933 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
934 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
935 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
936
937 // Find the end of the array, hoisted out of the loop.
938 llvm::Value *EndPtr =
939 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000940
Sebastian Redlf862eb62012-02-22 17:37:52 +0000941 // If the number of elements isn't constant, we have to now check if there is
942 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000943 if (!ConstNum) {
944 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000945 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000946 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000947 }
948
949 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000950 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000951
952 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000953 llvm::PHINode *CurPtrPhi =
954 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
955 CurPtrPhi->addIncoming(CurPtr, EntryBB);
956 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000957
Richard Smith06a67e22014-06-03 06:58:52 +0000958 // Store the new Cleanup position for irregular Cleanups.
959 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000960
Richard Smith06a67e22014-06-03 06:58:52 +0000961 // Enter a partial-destruction Cleanup if necessary.
962 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
963 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
964 getDestroyer(DtorKind));
965 Cleanup = EHStack.stable_begin();
966 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000967 }
968
969 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000970 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +0000971
Richard Smith06a67e22014-06-03 06:58:52 +0000972 // Leave the Cleanup if we entered one.
973 if (CleanupDominator) {
974 DeactivateCleanupBlock(Cleanup, CleanupDominator);
975 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +0000976 }
John McCall99210dc2011-09-15 06:49:18 +0000977
Faisal Vali57ae0562013-12-14 00:40:05 +0000978 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000979 llvm::Value *NextPtr =
980 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
981
John McCall99210dc2011-09-15 06:49:18 +0000982 // Check whether we've gotten to the end of the array and, if so,
983 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000984 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
985 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
986 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +0000987
Richard Smith06a67e22014-06-03 06:58:52 +0000988 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000989}
990
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000991static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000992 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000993 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000994 llvm::Value *NumElements,
995 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000996 if (E->isArray())
997 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
998 AllocSizeWithoutCookie);
999 else if (const Expr *Init = E->getInitializer())
1000 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001001}
1002
Richard Smith8d0dc312013-07-21 23:12:18 +00001003/// Emit a call to an operator new or operator delete function, as implicitly
1004/// created by new-expressions and delete-expressions.
1005static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1006 const FunctionDecl *Callee,
1007 const FunctionProtoType *CalleeType,
1008 const CallArgList &Args) {
1009 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001010 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001011 RValue RV =
1012 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +00001013 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +00001014 Callee, &CallOrInvoke);
1015
1016 /// C++1y [expr.new]p10:
1017 /// [In a new-expression,] an implementation is allowed to omit a call
1018 /// to a replaceable global allocation function.
1019 ///
1020 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001021 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001022 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001023 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001024 // FIXME: Add addAttribute to CallSite.
1025 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1026 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1027 llvm::Attribute::Builtin);
1028 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1029 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1030 llvm::Attribute::Builtin);
1031 else
1032 llvm_unreachable("unexpected kind of call instruction");
1033 }
1034
1035 return RV;
1036}
1037
Richard Smith760520b2014-06-03 23:27:44 +00001038RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1039 const Expr *Arg,
1040 bool IsDelete) {
1041 CallArgList Args;
1042 const Stmt *ArgS = Arg;
1043 EmitCallArgs(Args, *Type->param_type_begin(),
1044 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1045 // Find the allocation or deallocation function that we're calling.
1046 ASTContext &Ctx = getContext();
1047 DeclarationName Name = Ctx.DeclarationNames
1048 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1049 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001050 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1051 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1052 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001053 llvm_unreachable("predeclared global operator new/delete is missing");
1054}
1055
John McCall824c2f52010-09-14 07:57:04 +00001056namespace {
1057 /// A cleanup to call the given 'operator delete' function upon
1058 /// abnormal exit from a new expression.
1059 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1060 size_t NumPlacementArgs;
1061 const FunctionDecl *OperatorDelete;
1062 llvm::Value *Ptr;
1063 llvm::Value *AllocSize;
1064
1065 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1066
1067 public:
1068 static size_t getExtraSize(size_t NumPlacementArgs) {
1069 return NumPlacementArgs * sizeof(RValue);
1070 }
1071
1072 CallDeleteDuringNew(size_t NumPlacementArgs,
1073 const FunctionDecl *OperatorDelete,
1074 llvm::Value *Ptr,
1075 llvm::Value *AllocSize)
1076 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1077 Ptr(Ptr), AllocSize(AllocSize) {}
1078
1079 void setPlacementArg(unsigned I, RValue Arg) {
1080 assert(I < NumPlacementArgs && "index out of range");
1081 getPlacementArgs()[I] = Arg;
1082 }
1083
Craig Topper4f12f102014-03-12 06:41:41 +00001084 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001085 const FunctionProtoType *FPT
1086 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001087 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1088 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001089
1090 CallArgList DeleteArgs;
1091
1092 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001093 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001094 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001095
1096 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001097 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001098 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001099
1100 // Pass the rest of the arguments, which must match exactly.
1101 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001102 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001103
1104 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001105 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001106 }
1107 };
John McCall7f9c92a2010-09-17 00:50:28 +00001108
1109 /// A cleanup to call the given 'operator delete' function upon
1110 /// abnormal exit from a new expression when the new expression is
1111 /// conditional.
1112 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1113 size_t NumPlacementArgs;
1114 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001115 DominatingValue<RValue>::saved_type Ptr;
1116 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001117
John McCallcb5f77f2011-01-28 10:53:53 +00001118 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1119 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001120 }
1121
1122 public:
1123 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001124 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001125 }
1126
1127 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1128 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001129 DominatingValue<RValue>::saved_type Ptr,
1130 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001131 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1132 Ptr(Ptr), AllocSize(AllocSize) {}
1133
John McCallcb5f77f2011-01-28 10:53:53 +00001134 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001135 assert(I < NumPlacementArgs && "index out of range");
1136 getPlacementArgs()[I] = Arg;
1137 }
1138
Craig Topper4f12f102014-03-12 06:41:41 +00001139 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001140 const FunctionProtoType *FPT
1141 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001142 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1143 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001144
1145 CallArgList DeleteArgs;
1146
1147 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001148 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001149 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001150
1151 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001152 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001153 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001154 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001155 }
1156
1157 // Pass the rest of the arguments, which must match exactly.
1158 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001159 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001160 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001161 }
1162
1163 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001164 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001165 }
1166 };
1167}
1168
1169/// Enter a cleanup to call 'operator delete' if the initializer in a
1170/// new-expression throws.
1171static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1172 const CXXNewExpr *E,
1173 llvm::Value *NewPtr,
1174 llvm::Value *AllocSize,
1175 const CallArgList &NewArgs) {
1176 // If we're not inside a conditional branch, then the cleanup will
1177 // dominate and we can do the easier (and more efficient) thing.
1178 if (!CGF.isInConditionalBranch()) {
1179 CallDeleteDuringNew *Cleanup = CGF.EHStack
1180 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1181 E->getNumPlacementArgs(),
1182 E->getOperatorDelete(),
1183 NewPtr, AllocSize);
1184 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001185 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001186
1187 return;
1188 }
1189
1190 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001191 DominatingValue<RValue>::saved_type SavedNewPtr =
1192 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1193 DominatingValue<RValue>::saved_type SavedAllocSize =
1194 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001195
1196 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001197 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001198 E->getNumPlacementArgs(),
1199 E->getOperatorDelete(),
1200 SavedNewPtr,
1201 SavedAllocSize);
1202 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001203 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001204 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001205
John McCallf4beacd2011-11-10 10:43:54 +00001206 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001207}
1208
Anders Carlssoncc52f652009-09-22 22:53:17 +00001209llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001210 // The element type being allocated.
1211 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001212
John McCall75f94982011-03-07 03:12:35 +00001213 // 1. Build a call to the allocation function.
1214 FunctionDecl *allocator = E->getOperatorNew();
1215 const FunctionProtoType *allocatorType =
1216 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001217
John McCall75f94982011-03-07 03:12:35 +00001218 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001219
1220 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001221 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001222
Sebastian Redlf862eb62012-02-22 17:37:52 +00001223 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1224 unsigned minElements = 0;
1225 if (E->isArray() && E->hasInitializer()) {
1226 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1227 minElements = ILE->getNumInits();
1228 }
1229
Craig Topper8a13c412014-05-21 05:09:00 +00001230 llvm::Value *numElements = nullptr;
1231 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001232 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001233 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1234 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001235
Eli Friedman43dca6a2011-05-02 17:57:46 +00001236 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001237
Anders Carlssoncc52f652009-09-22 22:53:17 +00001238 // We start at 1 here because the first argument (the allocation size)
1239 // has already been emitted.
Reid Kleckner739756c2013-12-04 19:23:12 +00001240 EmitCallArgs(allocatorArgs, allocatorType->isVariadic(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001241 allocatorType->param_type_begin() + 1,
1242 allocatorType->param_type_end(), E->placement_arg_begin(),
Reid Kleckner739756c2013-12-04 19:23:12 +00001243 E->placement_arg_end());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001244
John McCall7ec4b432011-05-16 01:05:12 +00001245 // Emit the allocation call. If the allocator is a global placement
1246 // operator, just "inline" it directly.
1247 RValue RV;
1248 if (allocator->isReservedGlobalPlacementOperator()) {
1249 assert(allocatorArgs.size() == 2);
1250 RV = allocatorArgs[1].RV;
1251 // TODO: kill any unnecessary computations done for the size
1252 // argument.
1253 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001254 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001255 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001256
John McCall75f94982011-03-07 03:12:35 +00001257 // Emit a null check on the allocation result if the allocation
1258 // function is allowed to return null (because it has a non-throwing
1259 // exception spec; for this part, we inline
1260 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1261 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001262 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001263 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001264
Craig Topper8a13c412014-05-21 05:09:00 +00001265 llvm::BasicBlock *nullCheckBB = nullptr;
1266 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001267
John McCall75f94982011-03-07 03:12:35 +00001268 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001269 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001270
John McCallf7dcf322011-03-07 01:52:56 +00001271 // The null-check means that the initializer is conditionally
1272 // evaluated.
1273 ConditionalEvaluation conditional(*this);
1274
John McCall75f94982011-03-07 03:12:35 +00001275 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001276 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001277
1278 nullCheckBB = Builder.GetInsertBlock();
1279 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1280 contBB = createBasicBlock("new.cont");
1281
1282 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1283 Builder.CreateCondBr(isNull, contBB, notNullBB);
1284 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001285 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001286
John McCall824c2f52010-09-14 07:57:04 +00001287 // If there's an operator delete, enter a cleanup to call it if an
1288 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001289 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001290 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001291 if (E->getOperatorDelete() &&
1292 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001293 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1294 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001295 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001296 }
1297
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001298 assert((allocSize == allocSizeWithoutCookie) ==
1299 CalculateCookiePadding(*this, E).isZero());
1300 if (allocSize != allocSizeWithoutCookie) {
1301 assert(E->isArray());
1302 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1303 numElements,
1304 E, allocType);
1305 }
1306
Chris Lattner2192fe52011-07-18 04:24:23 +00001307 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001308 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1309 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001310
John McCall99210dc2011-09-15 06:49:18 +00001311 EmitNewInitializer(*this, E, allocType, result, numElements,
1312 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001313 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001314 // NewPtr is a pointer to the base element type. If we're
1315 // allocating an array of arrays, we'll need to cast back to the
1316 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001317 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001318 if (result->getType() != resultType)
1319 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001320 }
John McCall824c2f52010-09-14 07:57:04 +00001321
1322 // Deactivate the 'operator delete' cleanup if we finished
1323 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001324 if (operatorDeleteCleanup.isValid()) {
1325 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1326 cleanupDominator->eraseFromParent();
1327 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001328
John McCall75f94982011-03-07 03:12:35 +00001329 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001330 conditional.end(*this);
1331
John McCall75f94982011-03-07 03:12:35 +00001332 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1333 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001334
Jay Foad20c0f022011-03-30 11:28:58 +00001335 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001336 PHI->addIncoming(result, notNullBB);
1337 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1338 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001339
John McCall75f94982011-03-07 03:12:35 +00001340 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001341 }
John McCall8ed55a52010-09-02 09:58:18 +00001342
John McCall75f94982011-03-07 03:12:35 +00001343 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001344}
1345
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001346void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1347 llvm::Value *Ptr,
1348 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001349 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1350
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001351 const FunctionProtoType *DeleteFTy =
1352 DeleteFD->getType()->getAs<FunctionProtoType>();
1353
1354 CallArgList DeleteArgs;
1355
Anders Carlsson21122cf2009-12-13 20:04:38 +00001356 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001357 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001358 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001359 if (DeleteFTy->getNumParams() == 2) {
1360 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001361 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1362 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1363 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001364 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001365
1366 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001367 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001368 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001369
Anders Carlsson21122cf2009-12-13 20:04:38 +00001370 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001371 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001372
1373 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001374 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001375}
1376
John McCall8ed55a52010-09-02 09:58:18 +00001377namespace {
1378 /// Calls the given 'operator delete' on a single object.
1379 struct CallObjectDelete : EHScopeStack::Cleanup {
1380 llvm::Value *Ptr;
1381 const FunctionDecl *OperatorDelete;
1382 QualType ElementType;
1383
1384 CallObjectDelete(llvm::Value *Ptr,
1385 const FunctionDecl *OperatorDelete,
1386 QualType ElementType)
1387 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1388
Craig Topper4f12f102014-03-12 06:41:41 +00001389 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001390 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1391 }
1392 };
1393}
1394
1395/// Emit the code for deleting a single object.
1396static void EmitObjectDelete(CodeGenFunction &CGF,
1397 const FunctionDecl *OperatorDelete,
1398 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001399 QualType ElementType,
1400 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001401 // Find the destructor for the type, if applicable. If the
1402 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001403 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001404 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1405 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001406 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001407 Dtor = RD->getDestructor();
1408
1409 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001410 if (UseGlobalDelete) {
1411 // If we're supposed to call the global delete, make sure we do so
1412 // even if the destructor throws.
John McCall82fb8922012-09-25 10:10:39 +00001413
1414 // Derive the complete-object pointer, which is what we need
1415 // to pass to the deallocation function.
1416 llvm::Value *completePtr =
1417 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1418
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001419 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall82fb8922012-09-25 10:10:39 +00001420 completePtr, OperatorDelete,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001421 ElementType);
1422 }
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001423
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001424 // FIXME: Provide a source location here even though there's no
1425 // CXXMemberCallExpr for dtor call.
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001426 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001427 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr,
1428 nullptr);
John McCall8ed55a52010-09-02 09:58:18 +00001429
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001430 if (UseGlobalDelete) {
1431 CGF.PopCleanupBlock();
1432 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001433
John McCall8ed55a52010-09-02 09:58:18 +00001434 return;
1435 }
1436 }
1437 }
1438
1439 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001440 // This doesn't have to a conditional cleanup because we're going
1441 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001442 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1443 Ptr, OperatorDelete, ElementType);
1444
1445 if (Dtor)
1446 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001447 /*ForVirtualBase=*/false,
1448 /*Delegating=*/false,
1449 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001450 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001451 ElementType->isObjCLifetimeType()) {
1452 switch (ElementType.getObjCLifetime()) {
1453 case Qualifiers::OCL_None:
1454 case Qualifiers::OCL_ExplicitNone:
1455 case Qualifiers::OCL_Autoreleasing:
1456 break;
John McCall8ed55a52010-09-02 09:58:18 +00001457
John McCall31168b02011-06-15 23:02:42 +00001458 case Qualifiers::OCL_Strong: {
1459 // Load the pointer value.
1460 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1461 ElementType.isVolatileQualified());
1462
John McCallcdda29c2013-03-13 03:10:54 +00001463 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001464 break;
1465 }
1466
1467 case Qualifiers::OCL_Weak:
1468 CGF.EmitARCDestroyWeak(Ptr);
1469 break;
1470 }
1471 }
1472
John McCall8ed55a52010-09-02 09:58:18 +00001473 CGF.PopCleanupBlock();
1474}
1475
1476namespace {
1477 /// Calls the given 'operator delete' on an array of objects.
1478 struct CallArrayDelete : EHScopeStack::Cleanup {
1479 llvm::Value *Ptr;
1480 const FunctionDecl *OperatorDelete;
1481 llvm::Value *NumElements;
1482 QualType ElementType;
1483 CharUnits CookieSize;
1484
1485 CallArrayDelete(llvm::Value *Ptr,
1486 const FunctionDecl *OperatorDelete,
1487 llvm::Value *NumElements,
1488 QualType ElementType,
1489 CharUnits CookieSize)
1490 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1491 ElementType(ElementType), CookieSize(CookieSize) {}
1492
Craig Topper4f12f102014-03-12 06:41:41 +00001493 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001494 const FunctionProtoType *DeleteFTy =
1495 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001496 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001497
1498 CallArgList Args;
1499
1500 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001501 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001502 llvm::Value *DeletePtr
1503 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001504 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001505
1506 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001507 if (DeleteFTy->getNumParams() == 2) {
1508 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001509 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001510 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1511
1512 CharUnits ElementTypeSize =
1513 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1514
1515 // The size of an element, multiplied by the number of elements.
1516 llvm::Value *Size
1517 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1518 Size = CGF.Builder.CreateMul(Size, NumElements);
1519
1520 // Plus the size of the cookie if applicable.
1521 if (!CookieSize.isZero()) {
1522 llvm::Value *CookieSizeV
1523 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1524 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1525 }
1526
Eli Friedman43dca6a2011-05-02 17:57:46 +00001527 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001528 }
1529
1530 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001531 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001532 }
1533 };
1534}
1535
1536/// Emit the code for deleting an array of objects.
1537static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001538 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001539 llvm::Value *deletedPtr,
1540 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001541 llvm::Value *numElements = nullptr;
1542 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001543 CharUnits cookieSize;
1544 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1545 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001546
John McCallca2c56f2011-07-13 01:41:37 +00001547 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001548
1549 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001550 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001551 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001552 allocatedPtr, operatorDelete,
1553 numElements, elementType,
1554 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001555
John McCallca2c56f2011-07-13 01:41:37 +00001556 // Destroy the elements.
1557 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1558 assert(numElements && "no element count for a type with a destructor!");
1559
John McCallca2c56f2011-07-13 01:41:37 +00001560 llvm::Value *arrayEnd =
1561 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001562
1563 // Note that it is legal to allocate a zero-length array, and we
1564 // can never fold the check away because the length should always
1565 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001566 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1567 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001568 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001569 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001570 }
1571
John McCallca2c56f2011-07-13 01:41:37 +00001572 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001573 CGF.PopCleanupBlock();
1574}
1575
Anders Carlssoncc52f652009-09-22 22:53:17 +00001576void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001577 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001578 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001579
1580 // Null check the pointer.
1581 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1582 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1583
Anders Carlsson98981b12011-04-11 00:30:07 +00001584 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001585
1586 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1587 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001588
John McCall8ed55a52010-09-02 09:58:18 +00001589 // We might be deleting a pointer to array. If so, GEP down to the
1590 // first non-array element.
1591 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1592 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1593 if (DeleteTy->isConstantArrayType()) {
1594 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001595 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001596
1597 GEP.push_back(Zero); // point at the outermost array
1598
1599 // For each layer of array type we're pointing at:
1600 while (const ConstantArrayType *Arr
1601 = getContext().getAsConstantArrayType(DeleteTy)) {
1602 // 1. Unpeel the array type.
1603 DeleteTy = Arr->getElementType();
1604
1605 // 2. GEP to the first element of the array.
1606 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001607 }
John McCall8ed55a52010-09-02 09:58:18 +00001608
Jay Foad040dd822011-07-22 08:16:57 +00001609 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001610 }
1611
Douglas Gregor04f36212010-09-02 17:38:50 +00001612 assert(ConvertTypeForMem(DeleteTy) ==
1613 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001614
1615 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001616 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001617 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001618 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1619 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001620 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001621
Anders Carlssoncc52f652009-09-22 22:53:17 +00001622 EmitBlock(DeleteEnd);
1623}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001624
David Majnemer1c3d95e2014-07-19 00:17:06 +00001625static bool isGLValueFromPointerDeref(const Expr *E) {
1626 E = E->IgnoreParens();
1627
1628 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1629 if (!CE->getSubExpr()->isGLValue())
1630 return false;
1631 return isGLValueFromPointerDeref(CE->getSubExpr());
1632 }
1633
1634 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1635 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1636
1637 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1638 if (BO->getOpcode() == BO_Comma)
1639 return isGLValueFromPointerDeref(BO->getRHS());
1640
1641 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1642 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1643 isGLValueFromPointerDeref(ACO->getFalseExpr());
1644
1645 // C++11 [expr.sub]p1:
1646 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1647 if (isa<ArraySubscriptExpr>(E))
1648 return true;
1649
1650 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1651 if (UO->getOpcode() == UO_Deref)
1652 return true;
1653
1654 return false;
1655}
1656
Warren Hunt747e3012014-06-18 21:15:55 +00001657static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001658 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001659 // Get the vtable pointer.
1660 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1661
1662 // C++ [expr.typeid]p2:
1663 // If the glvalue expression is obtained by applying the unary * operator to
1664 // a pointer and the pointer is a null pointer value, the typeid expression
1665 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001666 //
1667 // However, this paragraph's intent is not clear. We choose a very generous
1668 // interpretation which implores us to consider comma operators, conditional
1669 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001670 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001671 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1672 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001673 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001674 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001675 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001676
David Majnemer1162d252014-06-22 19:05:33 +00001677 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1678 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001679
David Majnemer1162d252014-06-22 19:05:33 +00001680 CGF.EmitBlock(BadTypeidBlock);
1681 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1682 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001683 }
1684
David Majnemer1162d252014-06-22 19:05:33 +00001685 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1686 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001687}
1688
John McCalle4df6c82011-01-28 08:37:24 +00001689llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001690 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001691 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001692
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001693 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001694 llvm::Constant *TypeInfo =
1695 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001696 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001697 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001698
Anders Carlsson940f02d2011-04-18 00:57:03 +00001699 // C++ [expr.typeid]p2:
1700 // When typeid is applied to a glvalue expression whose type is a
1701 // polymorphic class type, the result refers to a std::type_info object
1702 // representing the type of the most derived object (that is, the dynamic
1703 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001704 if (E->isPotentiallyEvaluated())
1705 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1706 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001707
1708 QualType OperandTy = E->getExprOperand()->getType();
1709 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1710 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001711}
Mike Stump65511702009-11-16 06:50:58 +00001712
Anders Carlssonc1c99712011-04-11 01:45:29 +00001713static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1714 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001715 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001716 if (DestTy->isPointerType())
1717 return llvm::Constant::getNullValue(DestLTy);
1718
1719 /// C++ [expr.dynamic.cast]p9:
1720 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001721 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1722 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001723
1724 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1725 return llvm::UndefValue::get(DestLTy);
1726}
1727
Anders Carlsson882d7902011-04-11 00:46:40 +00001728llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001729 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001730 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001731
Anders Carlssonc1c99712011-04-11 01:45:29 +00001732 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001733 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1734 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001735
1736 QualType SrcTy = DCE->getSubExpr()->getType();
1737
David Majnemer1162d252014-06-22 19:05:33 +00001738 // C++ [expr.dynamic.cast]p7:
1739 // If T is "pointer to cv void," then the result is a pointer to the most
1740 // derived object pointed to by v.
1741 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1742
1743 bool isDynamicCastToVoid;
1744 QualType SrcRecordTy;
1745 QualType DestRecordTy;
1746 if (DestPTy) {
1747 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1748 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1749 DestRecordTy = DestPTy->getPointeeType();
1750 } else {
1751 isDynamicCastToVoid = false;
1752 SrcRecordTy = SrcTy;
1753 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1754 }
1755
1756 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1757
Anders Carlsson882d7902011-04-11 00:46:40 +00001758 // C++ [expr.dynamic.cast]p4:
1759 // If the value of v is a null pointer value in the pointer case, the result
1760 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001761 bool ShouldNullCheckSrcValue =
1762 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1763 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001764
1765 llvm::BasicBlock *CastNull = nullptr;
1766 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001767 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001768
Anders Carlsson882d7902011-04-11 00:46:40 +00001769 if (ShouldNullCheckSrcValue) {
1770 CastNull = createBasicBlock("dynamic_cast.null");
1771 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1772
1773 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1774 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1775 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001776 }
1777
David Majnemer1162d252014-06-22 19:05:33 +00001778 if (isDynamicCastToVoid) {
1779 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1780 DestTy);
1781 } else {
1782 assert(DestRecordTy->isRecordType() &&
1783 "destination type must be a record type!");
1784 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1785 DestTy, DestRecordTy, CastEnd);
1786 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001787
1788 if (ShouldNullCheckSrcValue) {
1789 EmitBranch(CastEnd);
1790
1791 EmitBlock(CastNull);
1792 EmitBranch(CastEnd);
1793 }
1794
1795 EmitBlock(CastEnd);
1796
1797 if (ShouldNullCheckSrcValue) {
1798 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1799 PHI->addIncoming(Value, CastNotNull);
1800 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1801
1802 Value = PHI;
1803 }
1804
1805 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001806}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001807
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001808void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001809 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001810 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1811 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001812
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001813 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1814 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1815 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001816 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001817 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001818
David Blaikie40ed2972012-06-06 20:45:41 +00001819 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001820 ArrayRef<VarDecl *> ArrayIndexes;
1821 if (CurField->getType()->isArrayType())
1822 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001823 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001824 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001825}