blob: 631923002e340e71325b49f77b74705b9cfe1510 [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
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlssoncc52f652009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson27da15b2010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
Richard Smithe30752c2012-10-09 19:52:38 +000027 SourceLocation CallLoc,
Anders Carlsson27da15b2010-01-01 20:29:01 +000028 llvm::Value *Callee,
29 ReturnValueSlot ReturnValue,
30 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000031 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000032 CallExpr::const_arg_iterator ArgBeg,
33 CallExpr::const_arg_iterator ArgEnd) {
34 assert(MD->isInstance() &&
35 "Trying to emit a member call expr on a static method!");
36
Richard Smith69d0d262012-08-24 00:54:33 +000037 // C++11 [class.mfct.non-static]p2:
38 // If a non-static member function of a class X is called for an object that
39 // is not of type X, or of a type derived from X, the behavior is undefined.
Richard Smithe30752c2012-10-09 19:52:38 +000040 EmitTypeCheck(TCK_MemberCall, CallLoc, This,
Richard Smith4d1458e2012-09-08 02:08:36 +000041 getContext().getRecordType(MD->getParent()));
Richard Smith69d0d262012-08-24 00:54:33 +000042
Anders Carlsson27da15b2010-01-01 20:29:01 +000043 CallArgList Args;
44
45 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000046 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000047
Anders Carlssone36a6b32010-01-02 01:01:18 +000048 // If there is a VTT parameter, emit it.
49 if (VTT) {
50 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +000051 Args.add(RValue::get(VTT), T);
Anders Carlssone36a6b32010-01-02 01:01:18 +000052 }
John McCalla729c622012-02-17 03:33:10 +000053
54 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
55 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssone36a6b32010-01-02 01:01:18 +000056
John McCalla729c622012-02-17 03:33:10 +000057 // And the rest of the call args.
Anders Carlsson27da15b2010-01-01 20:29:01 +000058 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
59
John McCall8dda7b22012-07-07 06:41:13 +000060 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000061 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000062}
63
Anders Carlssonc53d9e82011-04-10 18:20:53 +000064// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
65// quite what we want.
66static const Expr *skipNoOpCastsAndParens(const Expr *E) {
67 while (true) {
68 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
69 E = PE->getSubExpr();
70 continue;
71 }
72
73 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
74 if (CE->getCastKind() == CK_NoOp) {
75 E = CE->getSubExpr();
76 continue;
77 }
78 }
79 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
80 if (UO->getOpcode() == UO_Extension) {
81 E = UO->getSubExpr();
82 continue;
83 }
84 }
85 return E;
86 }
87}
88
Anders Carlsson27da15b2010-01-01 20:29:01 +000089/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
90/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000091static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
92 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +000093 const CXXMethodDecl *MD) {
94
Anders Carlsson1ae64c52011-01-29 03:52:01 +000095 // When building with -fapple-kext, all calls must go through the vtable since
96 // the kernel linker can do runtime patching of vtables.
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000098 return false;
99
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000100 // If the most derived class is marked final, we know that no subclass can
101 // override this member function and so we can devirtualize it. For example:
102 //
103 // struct A { virtual void f(); }
104 // struct B final : A { };
105 //
106 // void f(B *b) {
107 // b->f();
108 // }
109 //
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +0000110 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000111 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
112 return true;
113
Anders Carlsson19588aa2011-01-23 21:07:30 +0000114 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000115 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000116 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000117 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000118
Anders Carlsson19588aa2011-01-23 21:07:30 +0000119 // Similarly, if the class itself is marked 'final' it can't be overridden
120 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000121 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000122 return true;
123
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000124 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000125 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
126 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
127 // This is a record decl. We know the type and can devirtualize it.
128 return VD->getType()->isRecordType();
129 }
130
131 return false;
132 }
Richard Smith48c15312012-08-15 22:59:28 +0000133
134 // We can devirtualize calls on an object accessed by a class member access
135 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
136 // a derived class object constructed in the same location.
137 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
138 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
139 return VD->getType()->isRecordType();
140
Anders Carlsson27da15b2010-01-01 20:29:01 +0000141 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000142 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000143 return true;
144
145 // And calls on bound temporaries.
146 if (isa<CXXBindTemporaryExpr>(Base))
147 return true;
148
149 // Check if this is a call expr that returns a record type.
150 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
151 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000152
Anders Carlsson27da15b2010-01-01 20:29:01 +0000153 // We can't devirtualize the call.
154 return false;
155}
156
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000157static CXXRecordDecl *getCXXRecord(const Expr *E) {
158 QualType T = E->getType();
159 if (const PointerType *PTy = T->getAs<PointerType>())
160 T = PTy->getPointeeType();
161 const RecordType *Ty = T->castAs<RecordType>();
162 return cast<CXXRecordDecl>(Ty->getDecl());
163}
164
Francois Pichet64225792011-01-18 05:04:39 +0000165// Note: This function also emit constructor calls to support a MSVC
166// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000167RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
168 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000169 const Expr *callee = CE->getCallee()->IgnoreParens();
170
171 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000172 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000173
174 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
176
Devang Patel91bbb552010-09-30 19:05:55 +0000177 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000178 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel401c9162010-10-22 18:56:27 +0000179 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000180 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
181 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
182 DI->getOrCreateRecordType(PTy->getPointeeType(),
183 MD->getParent()->getLocation());
184 }
185 }
186
Anders Carlsson27da15b2010-01-01 20:29:01 +0000187 if (MD->isStatic()) {
188 // The method is static, emit it as we would a regular call.
189 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
190 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
191 ReturnValue, CE->arg_begin(), CE->arg_end());
192 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000193
John McCall0d635f52010-09-03 01:26:39 +0000194 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000195 const Expr *Base = ME->getBase();
196 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000197
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000198 const CXXMethodDecl *DevirtualizedMethod = NULL;
199 if (CanUseVirtualCall &&
200 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
201 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
202 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
203 assert(DevirtualizedMethod);
204 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
205 const Expr *Inner = Base->ignoreParenBaseCasts();
206 if (getCXXRecord(Inner) == DevirtualizedClass)
207 // If the class of the Inner expression is where the dynamic method
208 // is defined, build the this pointer from it.
209 Base = Inner;
210 else if (getCXXRecord(Base) != DevirtualizedClass) {
211 // If the method is defined in a class that is not the best dynamic
212 // one or the one of the full expression, we would have to build
213 // a derived-to-base cast to compute the correct this pointer, but
214 // we don't have support for that yet, so do a virtual call.
215 DevirtualizedMethod = NULL;
216 }
Rafael Espindolab27564a2012-06-28 17:57:36 +0000217 // If the return types are not the same, this might be a case where more
218 // code needs to run to compensate for it. For example, the derived
219 // method might return a type that inherits form from the return
220 // type of MD and has a prefix.
221 // For now we just avoid devirtualizing these covariant cases.
222 if (DevirtualizedMethod &&
223 DevirtualizedMethod->getResultType().getCanonicalType() !=
224 MD->getResultType().getCanonicalType())
Rafael Espindoladebc71c2012-06-28 15:11:39 +0000225 DevirtualizedMethod = NULL;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000226 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000227
Anders Carlsson27da15b2010-01-01 20:29:01 +0000228 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000229 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000230 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000231 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000232 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000233
Anders Carlsson27da15b2010-01-01 20:29:01 +0000234
John McCall0d635f52010-09-03 01:26:39 +0000235 if (MD->isTrivial()) {
236 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000237 if (isa<CXXConstructorDecl>(MD) &&
238 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
239 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000240
Sebastian Redl22653ba2011-08-30 19:58:05 +0000241 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
242 // We don't like to generate the trivial copy/move assignment operator
243 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000244 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000245 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000246 return RValue::get(This);
247 }
248
249 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000250 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
251 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000252 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
253 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
254 CE->arg_begin(), CE->arg_end());
255 return RValue::get(This);
256 }
257 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000258 }
259
John McCall0d635f52010-09-03 01:26:39 +0000260 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000261 const CGFunctionInfo *FInfo = 0;
262 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000263 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
264 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000265 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000266 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
267 cast<CXXConstructorDecl>(MD),
268 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000269 else
John McCalla729c622012-02-17 03:33:10 +0000270 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000271
John McCalla729c622012-02-17 03:33:10 +0000272 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000273
Anders Carlsson27da15b2010-01-01 20:29:01 +0000274 // C++ [class.virtual]p12:
275 // Explicit qualification with the scope operator (5.1) suppresses the
276 // virtual call mechanism.
277 //
278 // We also don't emit a virtual call if the base expression has a record type
279 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000280 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola49e860b2012-06-26 17:45:31 +0000281
Anders Carlsson27da15b2010-01-01 20:29:01 +0000282 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000283 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
284 if (UseVirtualCall) {
285 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000286 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000288 MD->isVirtual() &&
289 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000290 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000291 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000292 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000293 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000294 const CXXDestructorDecl *DDtor =
295 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000296 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
297 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 }
Francois Pichet64225792011-01-18 05:04:39 +0000299 } else if (const CXXConstructorDecl *Ctor =
300 dyn_cast<CXXConstructorDecl>(MD)) {
301 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000302 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000303 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000304 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000305 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000306 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000307 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000308 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000309 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000310 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000311 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000312 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000313 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000314 }
315
Richard Smithe30752c2012-10-09 19:52:38 +0000316 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
317 /*VTT=*/0, CE->arg_begin(), CE->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000318}
319
320RValue
321CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
322 ReturnValueSlot ReturnValue) {
323 const BinaryOperator *BO =
324 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
325 const Expr *BaseExpr = BO->getLHS();
326 const Expr *MemFnExpr = BO->getRHS();
327
328 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000329 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000330
Anders Carlsson27da15b2010-01-01 20:29:01 +0000331 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000332 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000333 const CXXRecordDecl *RD =
334 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
335
Anders Carlsson27da15b2010-01-01 20:29:01 +0000336 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000337 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000338
339 // Emit the 'this' pointer.
340 llvm::Value *This;
341
John McCalle3027922010-08-25 11:45:40 +0000342 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000343 This = EmitScalarExpr(BaseExpr);
344 else
345 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000346
Richard Smithe30752c2012-10-09 19:52:38 +0000347 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
348 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000349
John McCall475999d2010-08-22 00:05:51 +0000350 // Ask the ABI to load the callee. Note that This is modified.
351 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000352 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000353
Anders Carlsson27da15b2010-01-01 20:29:01 +0000354 CallArgList Args;
355
356 QualType ThisType =
357 getContext().getPointerType(getContext().getTagDeclType(RD));
358
359 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000360 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000361
362 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000363
364 // And the rest of the call args
365 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall8dda7b22012-07-07 06:41:13 +0000366 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000367 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000368}
369
370RValue
371CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
372 const CXXMethodDecl *MD,
373 ReturnValueSlot ReturnValue) {
374 assert(MD->isInstance() &&
375 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000376 LValue LV = EmitLValue(E->getArg(0));
377 llvm::Value *This = LV.getAddress();
378
Douglas Gregor146b8e92011-09-06 16:26:56 +0000379 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
380 MD->isTrivial()) {
381 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
382 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000383 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000384 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000385 }
386
Anders Carlssonc36783e2011-05-08 20:32:23 +0000387 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smithe30752c2012-10-09 19:52:38 +0000388 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
389 /*VTT=*/0, E->arg_begin() + 1, E->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000390}
391
Peter Collingbournefe883422011-10-06 18:29:37 +0000392RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
393 ReturnValueSlot ReturnValue) {
394 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
395}
396
Eli Friedmanfde961d2011-10-14 02:27:24 +0000397static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
398 llvm::Value *DestPtr,
399 const CXXRecordDecl *Base) {
400 if (Base->isEmpty())
401 return;
402
403 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
404
405 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
406 CharUnits Size = Layout.getNonVirtualSize();
407 CharUnits Align = Layout.getNonVirtualAlign();
408
409 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
410
411 // If the type contains a pointer to data member we can't memset it to zero.
412 // Instead, create a null constant and copy it to the destination.
413 // TODO: there are other patterns besides zero that we can usefully memset,
414 // like -1, which happens to be the pattern used by member-pointers.
415 // TODO: isZeroInitializable can be over-conservative in the case where a
416 // virtual base contains a member pointer.
417 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
418 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
419
420 llvm::GlobalVariable *NullVariable =
421 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
422 /*isConstant=*/true,
423 llvm::GlobalVariable::PrivateLinkage,
424 NullConstant, Twine());
425 NullVariable->setAlignment(Align.getQuantity());
426 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
427
428 // Get and call the appropriate llvm.memcpy overload.
429 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
430 return;
431 }
432
433 // Otherwise, just memset the whole thing to zero. This is legal
434 // because in LLVM, all default initializers (other than the ones we just
435 // handled above) are guaranteed to have a bit pattern of all zeros.
436 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
437 Align.getQuantity());
438}
439
Anders Carlsson27da15b2010-01-01 20:29:01 +0000440void
John McCall7a626f62010-09-15 10:14:12 +0000441CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
442 AggValueSlot Dest) {
443 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000444 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000445
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
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000448 // constructor, emit the zero initialization now, unless destination is
449 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000450 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
451 switch (E->getConstructionKind()) {
452 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000453 case CXXConstructExpr::CK_Complete:
454 EmitNullInitialization(Dest.getAddr(), E->getType());
455 break;
456 case CXXConstructExpr::CK_VirtualBase:
457 case CXXConstructExpr::CK_NonVirtualBase:
458 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
459 break;
460 }
461 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000462
463 // If this is a call to a trivial default constructor, do nothing.
464 if (CD->isTrivial() && CD->isDefaultConstructor())
465 return;
466
John McCall8ea46b62010-09-18 00:58:34 +0000467 // Elide the constructor if we're constructing from a temporary.
468 // The temporary check is required because Sema sets this on NRVO
469 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000471 assert(getContext().hasSameUnqualifiedType(E->getType(),
472 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000473 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
474 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000475 return;
476 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000477 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000478
John McCallf677a8e2011-07-13 06:10:41 +0000479 if (const ConstantArrayType *arrayType
480 = getContext().getAsConstantArrayType(E->getType())) {
481 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000482 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000483 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000484 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000485 bool ForVirtualBase = false;
486
487 switch (E->getConstructionKind()) {
488 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000489 // We should be emitting a constructor; GlobalDecl will assert this
490 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000491 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000492
Alexis Hunt271c3682011-05-03 20:19:28 +0000493 case CXXConstructExpr::CK_Complete:
494 Type = Ctor_Complete;
495 break;
496
497 case CXXConstructExpr::CK_VirtualBase:
498 ForVirtualBase = true;
499 // fall-through
500
501 case CXXConstructExpr::CK_NonVirtualBase:
502 Type = Ctor_Base;
503 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000504
Anders Carlsson27da15b2010-01-01 20:29:01 +0000505 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000506 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000507 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000508 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000509}
510
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000511void
512CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
513 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000514 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000515 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000516 Exp = E->getSubExpr();
517 assert(isa<CXXConstructExpr>(Exp) &&
518 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
519 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
520 const CXXConstructorDecl *CD = E->getConstructor();
521 RunCleanupsScope Scope(*this);
522
523 // If we require zero initialization before (or instead of) calling the
524 // constructor, as can be the case with a non-user-provided default
525 // constructor, emit the zero initialization now.
526 // FIXME. Do I still need this for a copy ctor synthesis?
527 if (E->requiresZeroInitialization())
528 EmitNullInitialization(Dest, E->getType());
529
Chandler Carruth99da11c2010-11-15 13:54:43 +0000530 assert(!getContext().getAsConstantArrayType(E->getType())
531 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000532 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
533 E->arg_begin(), E->arg_end());
534}
535
John McCall8ed55a52010-09-02 09:58:18 +0000536static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
537 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000538 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000539 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000540
John McCall7ec4b432011-05-16 01:05:12 +0000541 // No cookie is required if the operator new[] being used is the
542 // reserved placement operator new[].
543 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000544 return CharUnits::Zero();
545
John McCall284c48f2011-01-27 09:37:56 +0000546 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000547}
548
John McCall036f2f62011-05-15 07:14:44 +0000549static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
550 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000551 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000552 llvm::Value *&numElements,
553 llvm::Value *&sizeWithoutCookie) {
554 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000555
John McCall036f2f62011-05-15 07:14:44 +0000556 if (!e->isArray()) {
557 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
558 sizeWithoutCookie
559 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
560 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000561 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000562
John McCall036f2f62011-05-15 07:14:44 +0000563 // The width of size_t.
564 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
565
John McCall8ed55a52010-09-02 09:58:18 +0000566 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000567 llvm::APInt cookieSize(sizeWidth,
568 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000569
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000570 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000571 // We multiply the size of all dimensions for NumElements.
572 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000573 numElements = CGF.EmitScalarExpr(e->getArraySize());
574 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000575
John McCall036f2f62011-05-15 07:14:44 +0000576 // The number of elements can be have an arbitrary integer type;
577 // essentially, we need to multiply it by a constant factor, add a
578 // cookie size, and verify that the result is representable as a
579 // size_t. That's just a gloss, though, and it's wrong in one
580 // important way: if the count is negative, it's an error even if
581 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000582 bool isSigned
583 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000584 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000585 = cast<llvm::IntegerType>(numElements->getType());
586 unsigned numElementsWidth = numElementsType->getBitWidth();
587
588 // Compute the constant factor.
589 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000590 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000591 = CGF.getContext().getAsConstantArrayType(type)) {
592 type = CAT->getElementType();
593 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000594 }
595
John McCall036f2f62011-05-15 07:14:44 +0000596 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
597 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
598 typeSizeMultiplier *= arraySizeMultiplier;
599
600 // This will be a size_t.
601 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000602
Chris Lattner32ac5832010-07-20 21:55:52 +0000603 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
604 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000605 if (llvm::ConstantInt *numElementsC =
606 dyn_cast<llvm::ConstantInt>(numElements)) {
607 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000608
John McCall036f2f62011-05-15 07:14:44 +0000609 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000610
John McCall036f2f62011-05-15 07:14:44 +0000611 // If 'count' was a negative number, it's an overflow.
612 if (isSigned && count.isNegative())
613 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000614
John McCall036f2f62011-05-15 07:14:44 +0000615 // We want to do all this arithmetic in size_t. If numElements is
616 // wider than that, check whether it's already too big, and if so,
617 // overflow.
618 else if (numElementsWidth > sizeWidth &&
619 numElementsWidth - sizeWidth > count.countLeadingZeros())
620 hasAnyOverflow = true;
621
622 // Okay, compute a count at the right width.
623 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
624
Sebastian Redlf862eb62012-02-22 17:37:52 +0000625 // If there is a brace-initializer, we cannot allocate fewer elements than
626 // there are initializers. If we do, that's treated like an overflow.
627 if (adjustedCount.ult(minElements))
628 hasAnyOverflow = true;
629
John McCall036f2f62011-05-15 07:14:44 +0000630 // Scale numElements by that. This might overflow, but we don't
631 // care because it only overflows if allocationSize does, too, and
632 // if that overflows then we shouldn't use this.
633 numElements = llvm::ConstantInt::get(CGF.SizeTy,
634 adjustedCount * arraySizeMultiplier);
635
636 // Compute the size before cookie, and track whether it overflowed.
637 bool overflow;
638 llvm::APInt allocationSize
639 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
640 hasAnyOverflow |= overflow;
641
642 // Add in the cookie, and check whether it's overflowed.
643 if (cookieSize != 0) {
644 // Save the current size without a cookie. This shouldn't be
645 // used if there was overflow.
646 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
647
648 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
649 hasAnyOverflow |= overflow;
650 }
651
652 // On overflow, produce a -1 so operator new will fail.
653 if (hasAnyOverflow) {
654 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
655 } else {
656 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
657 }
658
659 // Otherwise, we might need to use the overflow intrinsics.
660 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000661 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000662 // 1) if isSigned, we need to check whether numElements is negative;
663 // 2) if numElementsWidth > sizeWidth, we need to check whether
664 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000665 // 3) if minElements > 0, we need to check whether numElements is smaller
666 // than that.
667 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000668 // sizeWithoutCookie := numElements * typeSizeMultiplier
669 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000670 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000671 // size := sizeWithoutCookie + cookieSize
672 // and check whether it overflows.
673
674 llvm::Value *hasOverflow = 0;
675
676 // If numElementsWidth > sizeWidth, then one way or another, we're
677 // going to have to do a comparison for (2), and this happens to
678 // take care of (1), too.
679 if (numElementsWidth > sizeWidth) {
680 llvm::APInt threshold(numElementsWidth, 1);
681 threshold <<= sizeWidth;
682
683 llvm::Value *thresholdV
684 = llvm::ConstantInt::get(numElementsType, threshold);
685
686 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
687 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
688
689 // Otherwise, if we're signed, we want to sext up to size_t.
690 } else if (isSigned) {
691 if (numElementsWidth < sizeWidth)
692 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
693
694 // If there's a non-1 type size multiplier, then we can do the
695 // signedness check at the same time as we do the multiply
696 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000697 // unsigned overflow. Otherwise, we have to do it here. But at least
698 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000699 if (typeSizeMultiplier == 1)
700 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000701 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000702
703 // Otherwise, zext up to size_t if necessary.
704 } else if (numElementsWidth < sizeWidth) {
705 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
706 }
707
708 assert(numElements->getType() == CGF.SizeTy);
709
Sebastian Redlf862eb62012-02-22 17:37:52 +0000710 if (minElements) {
711 // Don't allow allocation of fewer elements than we have initializers.
712 if (!hasOverflow) {
713 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
714 llvm::ConstantInt::get(CGF.SizeTy, minElements));
715 } else if (numElementsWidth > sizeWidth) {
716 // The other existing overflow subsumes this check.
717 // We do an unsigned comparison, since any signed value < -1 is
718 // taken care of either above or below.
719 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
720 CGF.Builder.CreateICmpULT(numElements,
721 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
722 }
723 }
724
John McCall036f2f62011-05-15 07:14:44 +0000725 size = numElements;
726
727 // Multiply by the type size if necessary. This multiplier
728 // includes all the factors for nested arrays.
729 //
730 // This step also causes numElements to be scaled up by the
731 // nested-array factor if necessary. Overflow on this computation
732 // can be ignored because the result shouldn't be used if
733 // allocation fails.
734 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000735 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000736 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000737
738 llvm::Value *tsmV =
739 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
740 llvm::Value *result =
741 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
742
743 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
744 if (hasOverflow)
745 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
746 else
747 hasOverflow = overflowed;
748
749 size = CGF.Builder.CreateExtractValue(result, 0);
750
751 // Also scale up numElements by the array size multiplier.
752 if (arraySizeMultiplier != 1) {
753 // If the base element type size is 1, then we can re-use the
754 // multiply we just did.
755 if (typeSize.isOne()) {
756 assert(arraySizeMultiplier == typeSizeMultiplier);
757 numElements = size;
758
759 // Otherwise we need a separate multiply.
760 } else {
761 llvm::Value *asmV =
762 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
763 numElements = CGF.Builder.CreateMul(numElements, asmV);
764 }
765 }
766 } else {
767 // numElements doesn't need to be scaled.
768 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000769 }
770
John McCall036f2f62011-05-15 07:14:44 +0000771 // Add in the cookie size if necessary.
772 if (cookieSize != 0) {
773 sizeWithoutCookie = size;
774
John McCall036f2f62011-05-15 07:14:44 +0000775 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000776 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000777
778 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
779 llvm::Value *result =
780 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
781
782 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
783 if (hasOverflow)
784 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
785 else
786 hasOverflow = overflowed;
787
788 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000789 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000790
John McCall036f2f62011-05-15 07:14:44 +0000791 // If we had any possibility of dynamic overflow, make a select to
792 // overwrite 'size' with an all-ones value, which should cause
793 // operator new to throw.
794 if (hasOverflow)
795 size = CGF.Builder.CreateSelect(hasOverflow,
796 llvm::Constant::getAllOnesValue(CGF.SizeTy),
797 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000798 }
John McCall8ed55a52010-09-02 09:58:18 +0000799
John McCall036f2f62011-05-15 07:14:44 +0000800 if (cookieSize == 0)
801 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000802 else
John McCall036f2f62011-05-15 07:14:44 +0000803 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000804
John McCall036f2f62011-05-15 07:14:44 +0000805 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000806}
807
Sebastian Redlf862eb62012-02-22 17:37:52 +0000808static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
809 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000810
Eli Friedman38cd36d2011-12-03 02:13:40 +0000811 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000812 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000813 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000814 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000815 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000816 else if (AllocType->isAnyComplexType())
817 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
818 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000819 else {
820 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000821 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000822 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000823 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000824 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000825 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000826
827 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000828 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000829}
830
831void
832CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000833 QualType elementType,
834 llvm::Value *beginPtr,
835 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000836 if (!E->hasInitializer())
837 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000838
Sebastian Redlf862eb62012-02-22 17:37:52 +0000839 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000840 // Find the end of the array, hoisted out of the loop.
841 llvm::Value *endPtr =
842 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
843
Sebastian Redlf862eb62012-02-22 17:37:52 +0000844 unsigned initializerElements = 0;
845
846 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000847 llvm::AllocaInst *endOfInit = 0;
848 QualType::DestructionKind dtorKind = elementType.isDestructedType();
849 EHScopeStack::stable_iterator cleanup;
850 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000851 // If the initializer is an initializer list, first do the explicit elements.
852 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
853 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000854
855 // Enter a partial-destruction cleanup if necessary.
856 if (needsEHCleanup(dtorKind)) {
857 // In principle we could tell the cleanup where we are more
858 // directly, but the control flow can get so varied here that it
859 // would actually be quite complex. Therefore we go through an
860 // alloca.
861 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
862 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
863 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
864 getDestroyer(dtorKind));
865 cleanup = EHStack.stable_begin();
866 }
867
Sebastian Redlf862eb62012-02-22 17:37:52 +0000868 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000869 // Tell the cleanup that it needs to destroy up to this
870 // element. TODO: some of these stores can be trivially
871 // observed to be unnecessary.
872 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000873 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
874 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
875 }
876
877 // The remaining elements are filled with the array filler expression.
878 Init = ILE->getArrayFiller();
879 }
880
John McCall99210dc2011-09-15 06:49:18 +0000881 // Create the continuation block.
882 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
883
Sebastian Redlf862eb62012-02-22 17:37:52 +0000884 // If the number of elements isn't constant, we have to now check if there is
885 // anything left to initialize.
886 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
887 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000888 if (constNum->getZExtValue() <= initializerElements) {
889 // If there was a cleanup, deactivate it.
890 if (cleanupDominator)
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +0000891 DeactivateCleanupBlock(cleanup, cleanupDominator);
Chad Rosierf62290a2012-02-24 00:13:55 +0000892 return;
893 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000894 } else {
John McCall99210dc2011-09-15 06:49:18 +0000895 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000896 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000897 "array.isempty");
898 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
899 EmitBlock(nonEmptyBB);
900 }
901
902 // Enter the loop.
903 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
904 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
905
906 EmitBlock(loopBB);
907
908 // Set up the current-element phi.
909 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000910 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
911 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000912
Chad Rosierf62290a2012-02-24 00:13:55 +0000913 // Store the new cleanup position for irregular cleanups.
914 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
915
John McCall99210dc2011-09-15 06:49:18 +0000916 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000917 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000918 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
919 getDestroyer(dtorKind));
920 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000921 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000922 }
923
924 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000925 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000926
927 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000928 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000929 DeactivateCleanupBlock(cleanup, cleanupDominator);
930 cleanupDominator->eraseFromParent();
931 }
John McCall99210dc2011-09-15 06:49:18 +0000932
933 // Advance to the next element.
934 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
935
936 // Check whether we've gotten to the end of the array and, if so,
937 // exit the loop.
938 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
939 Builder.CreateCondBr(isEnd, contBB, loopBB);
940 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
941
942 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000943}
944
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000945static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
946 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000947 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000948 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000949 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000950 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000951}
952
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000953static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000954 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000955 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000956 llvm::Value *NumElements,
957 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000958 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000959 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000960 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
961 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregord1531032012-02-23 17:07:43 +0000962 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000963 // If new expression did not specify value-initialization, then there
964 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000965 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000966 return;
967
John McCall99210dc2011-09-15 06:49:18 +0000968 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000969 // Optimization: since zero initialization will just set the memory
970 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000971 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000972 return;
973 }
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000974 }
John McCallf677a8e2011-07-13 06:10:41 +0000975
Sebastian Redl6047f072012-02-16 12:22:20 +0000976 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
977 CCE->arg_begin(), CCE->arg_end(),
Eli Friedman48ddcf22012-08-25 07:11:29 +0000978 CCE->requiresZeroInitialization());
Anders Carlssond040e6b2010-05-03 15:09:17 +0000979 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000980 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000981 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000982 // Optimization: since zero initialization will just set the memory
983 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000984 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
985 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000986 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000987 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
988 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000989 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000990
Sebastian Redl6047f072012-02-16 12:22:20 +0000991 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000992 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000993
Sebastian Redlf862eb62012-02-22 17:37:52 +0000994 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000995}
996
John McCall824c2f52010-09-14 07:57:04 +0000997namespace {
998 /// A cleanup to call the given 'operator delete' function upon
999 /// abnormal exit from a new expression.
1000 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1001 size_t NumPlacementArgs;
1002 const FunctionDecl *OperatorDelete;
1003 llvm::Value *Ptr;
1004 llvm::Value *AllocSize;
1005
1006 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1007
1008 public:
1009 static size_t getExtraSize(size_t NumPlacementArgs) {
1010 return NumPlacementArgs * sizeof(RValue);
1011 }
1012
1013 CallDeleteDuringNew(size_t NumPlacementArgs,
1014 const FunctionDecl *OperatorDelete,
1015 llvm::Value *Ptr,
1016 llvm::Value *AllocSize)
1017 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1018 Ptr(Ptr), AllocSize(AllocSize) {}
1019
1020 void setPlacementArg(unsigned I, RValue Arg) {
1021 assert(I < NumPlacementArgs && "index out of range");
1022 getPlacementArgs()[I] = Arg;
1023 }
1024
John McCall30317fd2011-07-12 20:27:29 +00001025 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +00001026 const FunctionProtoType *FPT
1027 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1028 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +00001029 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001030
1031 CallArgList DeleteArgs;
1032
1033 // The first argument is always a void*.
1034 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001035 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001036
1037 // A member 'operator delete' can take an extra 'size_t' argument.
1038 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001039 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001040
1041 // Pass the rest of the arguments, which must match exactly.
1042 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001043 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001044
1045 // Call 'operator delete'.
John McCall8dda7b22012-07-07 06:41:13 +00001046 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +00001047 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1048 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1049 }
1050 };
John McCall7f9c92a2010-09-17 00:50:28 +00001051
1052 /// A cleanup to call the given 'operator delete' function upon
1053 /// abnormal exit from a new expression when the new expression is
1054 /// conditional.
1055 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1056 size_t NumPlacementArgs;
1057 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001058 DominatingValue<RValue>::saved_type Ptr;
1059 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001060
John McCallcb5f77f2011-01-28 10:53:53 +00001061 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1062 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001063 }
1064
1065 public:
1066 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001067 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001068 }
1069
1070 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1071 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001072 DominatingValue<RValue>::saved_type Ptr,
1073 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001074 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1075 Ptr(Ptr), AllocSize(AllocSize) {}
1076
John McCallcb5f77f2011-01-28 10:53:53 +00001077 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001078 assert(I < NumPlacementArgs && "index out of range");
1079 getPlacementArgs()[I] = Arg;
1080 }
1081
John McCall30317fd2011-07-12 20:27:29 +00001082 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001083 const FunctionProtoType *FPT
1084 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1085 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1086 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1087
1088 CallArgList DeleteArgs;
1089
1090 // The first argument is always a void*.
1091 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001092 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001093
1094 // A member 'operator delete' can take an extra 'size_t' argument.
1095 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001096 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001097 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001098 }
1099
1100 // Pass the rest of the arguments, which must match exactly.
1101 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001102 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001103 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001104 }
1105
1106 // Call 'operator delete'.
John McCall8dda7b22012-07-07 06:41:13 +00001107 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001108 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1109 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1110 }
1111 };
1112}
1113
1114/// Enter a cleanup to call 'operator delete' if the initializer in a
1115/// new-expression throws.
1116static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1117 const CXXNewExpr *E,
1118 llvm::Value *NewPtr,
1119 llvm::Value *AllocSize,
1120 const CallArgList &NewArgs) {
1121 // If we're not inside a conditional branch, then the cleanup will
1122 // dominate and we can do the easier (and more efficient) thing.
1123 if (!CGF.isInConditionalBranch()) {
1124 CallDeleteDuringNew *Cleanup = CGF.EHStack
1125 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1126 E->getNumPlacementArgs(),
1127 E->getOperatorDelete(),
1128 NewPtr, AllocSize);
1129 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001130 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001131
1132 return;
1133 }
1134
1135 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001136 DominatingValue<RValue>::saved_type SavedNewPtr =
1137 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1138 DominatingValue<RValue>::saved_type SavedAllocSize =
1139 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001140
1141 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001142 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001143 E->getNumPlacementArgs(),
1144 E->getOperatorDelete(),
1145 SavedNewPtr,
1146 SavedAllocSize);
1147 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001148 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001149 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001150
John McCallf4beacd2011-11-10 10:43:54 +00001151 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001152}
1153
Anders Carlssoncc52f652009-09-22 22:53:17 +00001154llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001155 // The element type being allocated.
1156 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001157
John McCall75f94982011-03-07 03:12:35 +00001158 // 1. Build a call to the allocation function.
1159 FunctionDecl *allocator = E->getOperatorNew();
1160 const FunctionProtoType *allocatorType =
1161 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001162
John McCall75f94982011-03-07 03:12:35 +00001163 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001164
1165 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001166 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001167
Sebastian Redlf862eb62012-02-22 17:37:52 +00001168 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1169 unsigned minElements = 0;
1170 if (E->isArray() && E->hasInitializer()) {
1171 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1172 minElements = ILE->getNumInits();
1173 }
1174
John McCall75f94982011-03-07 03:12:35 +00001175 llvm::Value *numElements = 0;
1176 llvm::Value *allocSizeWithoutCookie = 0;
1177 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001178 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1179 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001180
Eli Friedman43dca6a2011-05-02 17:57:46 +00001181 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001182
1183 // Emit the rest of the arguments.
1184 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001185 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001186
1187 // First, use the types from the function type.
1188 // We start at 1 here because the first argument (the allocation size)
1189 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001190 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1191 ++i, ++placementArg) {
1192 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001193
John McCall75f94982011-03-07 03:12:35 +00001194 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1195 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001196 "type mismatch in call argument!");
1197
John McCall32ea9692011-03-11 20:59:21 +00001198 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001199 }
1200
1201 // Either we've emitted all the call args, or we have a call to a
1202 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001203 assert((placementArg == E->placement_arg_end() ||
1204 allocatorType->isVariadic()) &&
1205 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001206
1207 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001208 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1209 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001210 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001211 }
1212
John McCall7ec4b432011-05-16 01:05:12 +00001213 // Emit the allocation call. If the allocator is a global placement
1214 // operator, just "inline" it directly.
1215 RValue RV;
1216 if (allocator->isReservedGlobalPlacementOperator()) {
1217 assert(allocatorArgs.size() == 2);
1218 RV = allocatorArgs[1].RV;
1219 // TODO: kill any unnecessary computations done for the size
1220 // argument.
1221 } else {
John McCall8dda7b22012-07-07 06:41:13 +00001222 RV = EmitCall(CGM.getTypes().arrangeFreeFunctionCall(allocatorArgs,
1223 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001224 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1225 allocatorArgs, allocator);
1226 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001227
John McCall75f94982011-03-07 03:12:35 +00001228 // Emit a null check on the allocation result if the allocation
1229 // function is allowed to return null (because it has a non-throwing
1230 // exception spec; for this part, we inline
1231 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1232 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001233 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001234 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001235
John McCall75f94982011-03-07 03:12:35 +00001236 llvm::BasicBlock *nullCheckBB = 0;
1237 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001238
John McCall75f94982011-03-07 03:12:35 +00001239 llvm::Value *allocation = RV.getScalarVal();
1240 unsigned AS =
1241 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001242
John McCallf7dcf322011-03-07 01:52:56 +00001243 // The null-check means that the initializer is conditionally
1244 // evaluated.
1245 ConditionalEvaluation conditional(*this);
1246
John McCall75f94982011-03-07 03:12:35 +00001247 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001248 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001249
1250 nullCheckBB = Builder.GetInsertBlock();
1251 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1252 contBB = createBasicBlock("new.cont");
1253
1254 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1255 Builder.CreateCondBr(isNull, contBB, notNullBB);
1256 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001257 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001258
John McCall824c2f52010-09-14 07:57:04 +00001259 // If there's an operator delete, enter a cleanup to call it if an
1260 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001261 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001262 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001263 if (E->getOperatorDelete() &&
1264 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001265 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1266 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001267 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001268 }
1269
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001270 assert((allocSize == allocSizeWithoutCookie) ==
1271 CalculateCookiePadding(*this, E).isZero());
1272 if (allocSize != allocSizeWithoutCookie) {
1273 assert(E->isArray());
1274 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1275 numElements,
1276 E, allocType);
1277 }
1278
Chris Lattner2192fe52011-07-18 04:24:23 +00001279 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001280 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1281 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001282
John McCall99210dc2011-09-15 06:49:18 +00001283 EmitNewInitializer(*this, E, allocType, result, numElements,
1284 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001285 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001286 // NewPtr is a pointer to the base element type. If we're
1287 // allocating an array of arrays, we'll need to cast back to the
1288 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001289 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001290 if (result->getType() != resultType)
1291 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001292 }
John McCall824c2f52010-09-14 07:57:04 +00001293
1294 // Deactivate the 'operator delete' cleanup if we finished
1295 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001296 if (operatorDeleteCleanup.isValid()) {
1297 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1298 cleanupDominator->eraseFromParent();
1299 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001300
John McCall75f94982011-03-07 03:12:35 +00001301 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001302 conditional.end(*this);
1303
John McCall75f94982011-03-07 03:12:35 +00001304 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1305 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001306
Jay Foad20c0f022011-03-30 11:28:58 +00001307 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001308 PHI->addIncoming(result, notNullBB);
1309 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1310 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001311
John McCall75f94982011-03-07 03:12:35 +00001312 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001313 }
John McCall8ed55a52010-09-02 09:58:18 +00001314
John McCall75f94982011-03-07 03:12:35 +00001315 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001316}
1317
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001318void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1319 llvm::Value *Ptr,
1320 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001321 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1322
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001323 const FunctionProtoType *DeleteFTy =
1324 DeleteFD->getType()->getAs<FunctionProtoType>();
1325
1326 CallArgList DeleteArgs;
1327
Anders Carlsson21122cf2009-12-13 20:04:38 +00001328 // Check if we need to pass the size to the delete operator.
1329 llvm::Value *Size = 0;
1330 QualType SizeTy;
1331 if (DeleteFTy->getNumArgs() == 2) {
1332 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001333 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1334 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1335 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001336 }
1337
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001338 QualType ArgTy = DeleteFTy->getArgType(0);
1339 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001340 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001341
Anders Carlsson21122cf2009-12-13 20:04:38 +00001342 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001343 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001344
1345 // Emit the call to delete.
John McCall8dda7b22012-07-07 06:41:13 +00001346 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001347 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001348 DeleteArgs, DeleteFD);
1349}
1350
John McCall8ed55a52010-09-02 09:58:18 +00001351namespace {
1352 /// Calls the given 'operator delete' on a single object.
1353 struct CallObjectDelete : EHScopeStack::Cleanup {
1354 llvm::Value *Ptr;
1355 const FunctionDecl *OperatorDelete;
1356 QualType ElementType;
1357
1358 CallObjectDelete(llvm::Value *Ptr,
1359 const FunctionDecl *OperatorDelete,
1360 QualType ElementType)
1361 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1362
John McCall30317fd2011-07-12 20:27:29 +00001363 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001364 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1365 }
1366 };
1367}
1368
1369/// Emit the code for deleting a single object.
1370static void EmitObjectDelete(CodeGenFunction &CGF,
1371 const FunctionDecl *OperatorDelete,
1372 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001373 QualType ElementType,
1374 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001375 // Find the destructor for the type, if applicable. If the
1376 // destructor is virtual, we'll just emit the vcall and return.
1377 const CXXDestructorDecl *Dtor = 0;
1378 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1379 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001380 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001381 Dtor = RD->getDestructor();
1382
1383 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001384 if (UseGlobalDelete) {
1385 // If we're supposed to call the global delete, make sure we do so
1386 // even if the destructor throws.
John McCall82fb8922012-09-25 10:10:39 +00001387
1388 // Derive the complete-object pointer, which is what we need
1389 // to pass to the deallocation function.
1390 llvm::Value *completePtr =
1391 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1392
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001393 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall82fb8922012-09-25 10:10:39 +00001394 completePtr, OperatorDelete,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001395 ElementType);
1396 }
1397
Chris Lattner2192fe52011-07-18 04:24:23 +00001398 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001399 CGF.getTypes().GetFunctionType(
1400 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001401
1402 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001403 = CGF.BuildVirtualCall(Dtor,
1404 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1405 Ptr, Ty);
Richard Smithe30752c2012-10-09 19:52:38 +00001406 // FIXME: Provide a source location here.
1407 CGF.EmitCXXMemberCall(Dtor, SourceLocation(), Callee, ReturnValueSlot(),
1408 Ptr, /*VTT=*/0, 0, 0);
John McCall8ed55a52010-09-02 09:58:18 +00001409
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001410 if (UseGlobalDelete) {
1411 CGF.PopCleanupBlock();
1412 }
1413
John McCall8ed55a52010-09-02 09:58:18 +00001414 return;
1415 }
1416 }
1417 }
1418
1419 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001420 // This doesn't have to a conditional cleanup because we're going
1421 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001422 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1423 Ptr, OperatorDelete, ElementType);
1424
1425 if (Dtor)
1426 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1427 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001428 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001429 ElementType->isObjCLifetimeType()) {
1430 switch (ElementType.getObjCLifetime()) {
1431 case Qualifiers::OCL_None:
1432 case Qualifiers::OCL_ExplicitNone:
1433 case Qualifiers::OCL_Autoreleasing:
1434 break;
John McCall8ed55a52010-09-02 09:58:18 +00001435
John McCall31168b02011-06-15 23:02:42 +00001436 case Qualifiers::OCL_Strong: {
1437 // Load the pointer value.
1438 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1439 ElementType.isVolatileQualified());
1440
1441 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1442 break;
1443 }
1444
1445 case Qualifiers::OCL_Weak:
1446 CGF.EmitARCDestroyWeak(Ptr);
1447 break;
1448 }
1449 }
1450
John McCall8ed55a52010-09-02 09:58:18 +00001451 CGF.PopCleanupBlock();
1452}
1453
1454namespace {
1455 /// Calls the given 'operator delete' on an array of objects.
1456 struct CallArrayDelete : EHScopeStack::Cleanup {
1457 llvm::Value *Ptr;
1458 const FunctionDecl *OperatorDelete;
1459 llvm::Value *NumElements;
1460 QualType ElementType;
1461 CharUnits CookieSize;
1462
1463 CallArrayDelete(llvm::Value *Ptr,
1464 const FunctionDecl *OperatorDelete,
1465 llvm::Value *NumElements,
1466 QualType ElementType,
1467 CharUnits CookieSize)
1468 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1469 ElementType(ElementType), CookieSize(CookieSize) {}
1470
John McCall30317fd2011-07-12 20:27:29 +00001471 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001472 const FunctionProtoType *DeleteFTy =
1473 OperatorDelete->getType()->getAs<FunctionProtoType>();
1474 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1475
1476 CallArgList Args;
1477
1478 // Pass the pointer as the first argument.
1479 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1480 llvm::Value *DeletePtr
1481 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001482 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001483
1484 // Pass the original requested size as the second argument.
1485 if (DeleteFTy->getNumArgs() == 2) {
1486 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001487 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001488 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1489
1490 CharUnits ElementTypeSize =
1491 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1492
1493 // The size of an element, multiplied by the number of elements.
1494 llvm::Value *Size
1495 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1496 Size = CGF.Builder.CreateMul(Size, NumElements);
1497
1498 // Plus the size of the cookie if applicable.
1499 if (!CookieSize.isZero()) {
1500 llvm::Value *CookieSizeV
1501 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1502 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1503 }
1504
Eli Friedman43dca6a2011-05-02 17:57:46 +00001505 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001506 }
1507
1508 // Emit the call to delete.
John McCall8dda7b22012-07-07 06:41:13 +00001509 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001510 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1511 ReturnValueSlot(), Args, OperatorDelete);
1512 }
1513 };
1514}
1515
1516/// Emit the code for deleting an array of objects.
1517static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001518 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001519 llvm::Value *deletedPtr,
1520 QualType elementType) {
1521 llvm::Value *numElements = 0;
1522 llvm::Value *allocatedPtr = 0;
1523 CharUnits cookieSize;
1524 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1525 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001526
John McCallca2c56f2011-07-13 01:41:37 +00001527 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001528
1529 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001530 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001531 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001532 allocatedPtr, operatorDelete,
1533 numElements, elementType,
1534 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001535
John McCallca2c56f2011-07-13 01:41:37 +00001536 // Destroy the elements.
1537 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1538 assert(numElements && "no element count for a type with a destructor!");
1539
John McCallca2c56f2011-07-13 01:41:37 +00001540 llvm::Value *arrayEnd =
1541 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001542
1543 // Note that it is legal to allocate a zero-length array, and we
1544 // can never fold the check away because the length should always
1545 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001546 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1547 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001548 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001549 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001550 }
1551
John McCallca2c56f2011-07-13 01:41:37 +00001552 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001553 CGF.PopCleanupBlock();
1554}
1555
Anders Carlssoncc52f652009-09-22 22:53:17 +00001556void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001557 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001558 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001559
1560 // Null check the pointer.
1561 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1562 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1563
Anders Carlsson98981b12011-04-11 00:30:07 +00001564 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001565
1566 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1567 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001568
John McCall8ed55a52010-09-02 09:58:18 +00001569 // We might be deleting a pointer to array. If so, GEP down to the
1570 // first non-array element.
1571 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1572 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1573 if (DeleteTy->isConstantArrayType()) {
1574 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001575 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001576
1577 GEP.push_back(Zero); // point at the outermost array
1578
1579 // For each layer of array type we're pointing at:
1580 while (const ConstantArrayType *Arr
1581 = getContext().getAsConstantArrayType(DeleteTy)) {
1582 // 1. Unpeel the array type.
1583 DeleteTy = Arr->getElementType();
1584
1585 // 2. GEP to the first element of the array.
1586 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001587 }
John McCall8ed55a52010-09-02 09:58:18 +00001588
Jay Foad040dd822011-07-22 08:16:57 +00001589 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001590 }
1591
Douglas Gregor04f36212010-09-02 17:38:50 +00001592 assert(ConvertTypeForMem(DeleteTy) ==
1593 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001594
1595 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001596 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001597 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001598 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1599 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001600 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001601
Anders Carlssoncc52f652009-09-22 22:53:17 +00001602 EmitBlock(DeleteEnd);
1603}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001604
Anders Carlsson0c633502011-04-11 14:13:40 +00001605static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1606 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001607 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001608
1609 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1610}
1611
1612static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001613 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001614 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001615 CGF.Builder.CreateUnreachable();
1616}
1617
Anders Carlsson940f02d2011-04-18 00:57:03 +00001618static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1619 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001620 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001621 // Get the vtable pointer.
1622 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1623
1624 // C++ [expr.typeid]p2:
1625 // If the glvalue expression is obtained by applying the unary * operator to
1626 // a pointer and the pointer is a null pointer value, the typeid expression
1627 // throws the std::bad_typeid exception.
1628 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1629 if (UO->getOpcode() == UO_Deref) {
1630 llvm::BasicBlock *BadTypeidBlock =
1631 CGF.createBasicBlock("typeid.bad_typeid");
1632 llvm::BasicBlock *EndBlock =
1633 CGF.createBasicBlock("typeid.end");
1634
1635 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1636 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1637
1638 CGF.EmitBlock(BadTypeidBlock);
1639 EmitBadTypeidCall(CGF);
1640 CGF.EmitBlock(EndBlock);
1641 }
1642 }
1643
1644 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1645 StdTypeInfoPtrTy->getPointerTo());
1646
1647 // Load the type info.
1648 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1649 return CGF.Builder.CreateLoad(Value);
1650}
1651
John McCalle4df6c82011-01-28 08:37:24 +00001652llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001653 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001654 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001655
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001656 if (E->isTypeOperand()) {
1657 llvm::Constant *TypeInfo =
1658 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001659 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001660 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001661
Anders Carlsson940f02d2011-04-18 00:57:03 +00001662 // C++ [expr.typeid]p2:
1663 // When typeid is applied to a glvalue expression whose type is a
1664 // polymorphic class type, the result refers to a std::type_info object
1665 // representing the type of the most derived object (that is, the dynamic
1666 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001667 if (E->isPotentiallyEvaluated())
1668 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1669 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001670
1671 QualType OperandTy = E->getExprOperand()->getType();
1672 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1673 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001674}
Mike Stump65511702009-11-16 06:50:58 +00001675
Anders Carlsson882d7902011-04-11 00:46:40 +00001676static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1677 // void *__dynamic_cast(const void *sub,
1678 // const abi::__class_type_info *src,
1679 // const abi::__class_type_info *dst,
1680 // std::ptrdiff_t src2dst_offset);
1681
Chris Lattnerece04092012-02-07 00:39:47 +00001682 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001683 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001684 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1685
Chris Lattnera5f58b02011-07-09 17:41:47 +00001686 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001687
Chris Lattner2192fe52011-07-18 04:24:23 +00001688 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001689 llvm::FunctionType::get(Int8PtrTy, Args, false);
1690
1691 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1692}
1693
1694static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1695 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001696 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001697 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1698}
1699
Anders Carlssonc1c99712011-04-11 01:45:29 +00001700static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001701 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001702 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001703 CGF.Builder.CreateUnreachable();
1704}
1705
Anders Carlsson882d7902011-04-11 00:46:40 +00001706static llvm::Value *
1707EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1708 QualType SrcTy, QualType DestTy,
1709 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001710 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001711 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001712 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001713
1714 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1715 if (PTy->getPointeeType()->isVoidType()) {
1716 // C++ [expr.dynamic.cast]p7:
1717 // If T is "pointer to cv void," then the result is a pointer to the
1718 // most derived object pointed to by v.
1719
1720 // Get the vtable pointer.
1721 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1722
1723 // Get the offset-to-top from the vtable.
1724 llvm::Value *OffsetToTop =
1725 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1726 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1727
1728 // Finally, add the offset to the pointer.
1729 Value = CGF.EmitCastToVoidPtr(Value);
1730 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1731
1732 return CGF.Builder.CreateBitCast(Value, DestLTy);
1733 }
1734 }
1735
1736 QualType SrcRecordTy;
1737 QualType DestRecordTy;
1738
1739 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1740 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1741 DestRecordTy = DestPTy->getPointeeType();
1742 } else {
1743 SrcRecordTy = SrcTy;
1744 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1745 }
1746
1747 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1748 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1749
1750 llvm::Value *SrcRTTI =
1751 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1752 llvm::Value *DestRTTI =
1753 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1754
1755 // FIXME: Actually compute a hint here.
1756 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1757
1758 // Emit the call to __dynamic_cast.
1759 Value = CGF.EmitCastToVoidPtr(Value);
1760 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1761 SrcRTTI, DestRTTI, OffsetHint);
1762 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1763
1764 /// C++ [expr.dynamic.cast]p9:
1765 /// A failed cast to reference type throws std::bad_cast
1766 if (DestTy->isReferenceType()) {
1767 llvm::BasicBlock *BadCastBlock =
1768 CGF.createBasicBlock("dynamic_cast.bad_cast");
1769
1770 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1771 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1772
1773 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001774 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001775 }
1776
1777 return Value;
1778}
1779
Anders Carlssonc1c99712011-04-11 01:45:29 +00001780static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1781 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001782 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001783 if (DestTy->isPointerType())
1784 return llvm::Constant::getNullValue(DestLTy);
1785
1786 /// C++ [expr.dynamic.cast]p9:
1787 /// A failed cast to reference type throws std::bad_cast
1788 EmitBadCastCall(CGF);
1789
1790 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1791 return llvm::UndefValue::get(DestLTy);
1792}
1793
Anders Carlsson882d7902011-04-11 00:46:40 +00001794llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001795 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001796 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001797
Anders Carlssonc1c99712011-04-11 01:45:29 +00001798 if (DCE->isAlwaysNull())
1799 return EmitDynamicCastToNull(*this, DestTy);
1800
1801 QualType SrcTy = DCE->getSubExpr()->getType();
1802
Anders Carlsson882d7902011-04-11 00:46:40 +00001803 // C++ [expr.dynamic.cast]p4:
1804 // If the value of v is a null pointer value in the pointer case, the result
1805 // is the null pointer value of type T.
1806 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001807
Anders Carlsson882d7902011-04-11 00:46:40 +00001808 llvm::BasicBlock *CastNull = 0;
1809 llvm::BasicBlock *CastNotNull = 0;
1810 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001811
Anders Carlsson882d7902011-04-11 00:46:40 +00001812 if (ShouldNullCheckSrcValue) {
1813 CastNull = createBasicBlock("dynamic_cast.null");
1814 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1815
1816 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1817 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1818 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001819 }
1820
Anders Carlsson882d7902011-04-11 00:46:40 +00001821 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1822
1823 if (ShouldNullCheckSrcValue) {
1824 EmitBranch(CastEnd);
1825
1826 EmitBlock(CastNull);
1827 EmitBranch(CastEnd);
1828 }
1829
1830 EmitBlock(CastEnd);
1831
1832 if (ShouldNullCheckSrcValue) {
1833 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1834 PHI->addIncoming(Value, CastNotNull);
1835 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1836
1837 Value = PHI;
1838 }
1839
1840 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001841}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001842
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001843void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001844 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001845 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1846 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001847
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001848 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1849 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1850 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001851 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001852 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001853
David Blaikie40ed2972012-06-06 20:45:41 +00001854 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001855 ArrayRef<VarDecl *> ArrayIndexes;
1856 if (CurField->getType()->isArrayType())
1857 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001858 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001859 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001860}