blob: 372eb5407c9d1677ab5c83b2ef008530849be816 [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,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000031 CallExpr::const_arg_iterator ArgBeg,
32 CallExpr::const_arg_iterator ArgEnd) {
33 assert(MD->isInstance() &&
34 "Trying to emit a member call expr on a static method!");
35
Anders Carlsson27da15b2010-01-01 20:29:01 +000036 CallArgList Args;
37
38 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000039 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000040
Anders Carlssone36a6b32010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +000044 Args.add(RValue::get(VTT), T);
Anders Carlssone36a6b32010-01-02 01:01:18 +000045 }
John McCalla729c622012-02-17 03:33:10 +000046
47 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
48 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssone36a6b32010-01-02 01:01:18 +000049
John McCalla729c622012-02-17 03:33:10 +000050 // And the rest of the call args.
Anders Carlsson27da15b2010-01-01 20:29:01 +000051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
52
John McCalla729c622012-02-17 03:33:10 +000053 return EmitCall(CGM.getTypes().arrangeFunctionCall(FPT->getResultType(), Args,
54 FPT->getExtInfo(),
55 required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000056 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000057}
58
Anders Carlssonc53d9e82011-04-10 18:20:53 +000059// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
60// quite what we want.
61static const Expr *skipNoOpCastsAndParens(const Expr *E) {
62 while (true) {
63 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
64 E = PE->getSubExpr();
65 continue;
66 }
67
68 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
69 if (CE->getCastKind() == CK_NoOp) {
70 E = CE->getSubExpr();
71 continue;
72 }
73 }
74 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
75 if (UO->getOpcode() == UO_Extension) {
76 E = UO->getSubExpr();
77 continue;
78 }
79 }
80 return E;
81 }
82}
83
Anders Carlsson27da15b2010-01-01 20:29:01 +000084/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
85/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000086static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
87 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +000088 const CXXMethodDecl *MD) {
89
Anders Carlsson1ae64c52011-01-29 03:52:01 +000090 // When building with -fapple-kext, all calls must go through the vtable since
91 // the kernel linker can do runtime patching of vtables.
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000093 return false;
94
Anders Carlsson1ae64c52011-01-29 03:52:01 +000095 // If the most derived class is marked final, we know that no subclass can
96 // override this member function and so we can devirtualize it. For example:
97 //
98 // struct A { virtual void f(); }
99 // struct B final : A { };
100 //
101 // void f(B *b) {
102 // b->f();
103 // }
104 //
Rafael Espindola49e860b2012-06-26 17:45:31 +0000105 const CXXRecordDecl *MostDerivedClassDecl =
106 Base->getMostDerivedClassDeclForType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000107 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
108 return true;
109
Anders Carlsson19588aa2011-01-23 21:07:30 +0000110 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000111 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000112 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000113 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000114
Anders Carlsson19588aa2011-01-23 21:07:30 +0000115 // Similarly, if the class itself is marked 'final' it can't be overridden
116 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000117 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000118 return true;
119
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000120 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000121 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
122 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
123 // This is a record decl. We know the type and can devirtualize it.
124 return VD->getType()->isRecordType();
125 }
126
127 return false;
128 }
129
130 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000131 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000132 return true;
133
134 // And calls on bound temporaries.
135 if (isa<CXXBindTemporaryExpr>(Base))
136 return true;
137
138 // Check if this is a call expr that returns a record type.
139 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
140 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000141
Anders Carlsson27da15b2010-01-01 20:29:01 +0000142 // We can't devirtualize the call.
143 return false;
144}
145
Francois Pichet64225792011-01-18 05:04:39 +0000146// Note: This function also emit constructor calls to support a MSVC
147// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000148RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
149 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000150 const Expr *callee = CE->getCallee()->IgnoreParens();
151
152 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000153 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000154
155 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000156 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
157
Devang Patel91bbb552010-09-30 19:05:55 +0000158 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000159 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel401c9162010-10-22 18:56:27 +0000160 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000161 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
162 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
163 DI->getOrCreateRecordType(PTy->getPointeeType(),
164 MD->getParent()->getLocation());
165 }
166 }
167
Anders Carlsson27da15b2010-01-01 20:29:01 +0000168 if (MD->isStatic()) {
169 // The method is static, emit it as we would a regular call.
170 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
171 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
172 ReturnValue, CE->arg_begin(), CE->arg_end());
173 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000174
John McCall0d635f52010-09-03 01:26:39 +0000175 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000176 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000177 if (ME->isArrow())
178 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000179 else
180 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000181
John McCall0d635f52010-09-03 01:26:39 +0000182 if (MD->isTrivial()) {
183 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000184 if (isa<CXXConstructorDecl>(MD) &&
185 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
186 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000187
Sebastian Redl22653ba2011-08-30 19:58:05 +0000188 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
189 // We don't like to generate the trivial copy/move assignment operator
190 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000191 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
192 EmitAggregateCopy(This, RHS, CE->getType());
193 return RValue::get(This);
194 }
195
196 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000197 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
198 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000199 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
200 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
201 CE->arg_begin(), CE->arg_end());
202 return RValue::get(This);
203 }
204 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000205 }
206
John McCall0d635f52010-09-03 01:26:39 +0000207 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000208 const CGFunctionInfo *FInfo = 0;
209 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000210 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
211 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000212 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000213 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
214 cast<CXXConstructorDecl>(MD),
215 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000216 else
John McCalla729c622012-02-17 03:33:10 +0000217 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000218
John McCalla729c622012-02-17 03:33:10 +0000219 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000220
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 // C++ [class.virtual]p12:
222 // Explicit qualification with the scope operator (5.1) suppresses the
223 // virtual call mechanism.
224 //
225 // We also don't emit a virtual call if the base expression has a record type
226 // because then we know what the type is.
Rafael Espindola49e860b2012-06-26 17:45:31 +0000227 const Expr *Base = ME->getBase();
228 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
229 && !canDevirtualizeMemberFunctionCalls(getContext(),
230 Base, MD);
231 const CXXRecordDecl *MostDerivedClassDecl =
232 Base->getMostDerivedClassDeclForType();
233
Anders Carlsson27da15b2010-01-01 20:29:01 +0000234 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000235 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
236 if (UseVirtualCall) {
237 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000238 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000239 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000240 MD->isVirtual() &&
241 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000242 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola727a7712012-06-26 19:18:25 +0000243 else if (ME->hasQualifier())
244 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000245 else {
246 const CXXMethodDecl *DM =
247 Dtor->getCorrespondingMethodInClass(MostDerivedClassDecl);
248 assert(DM);
249 const CXXDestructorDecl *DDtor = cast<CXXDestructorDecl>(DM);
250 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
251 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 }
Francois Pichet64225792011-01-18 05:04:39 +0000253 } else if (const CXXConstructorDecl *Ctor =
254 dyn_cast<CXXConstructorDecl>(MD)) {
255 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000256 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000257 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000258 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000259 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000260 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000261 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000262 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola727a7712012-06-26 19:18:25 +0000263 else if (ME->hasQualifier())
264 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000265 else {
266 const CXXMethodDecl *DerivedMethod =
267 MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
268 assert(DerivedMethod);
269 Callee = CGM.GetAddrOfFunction(DerivedMethod, Ty);
270 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000271 }
272
Anders Carlssone36a6b32010-01-02 01:01:18 +0000273 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000274 CE->arg_begin(), CE->arg_end());
275}
276
277RValue
278CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
279 ReturnValueSlot ReturnValue) {
280 const BinaryOperator *BO =
281 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
282 const Expr *BaseExpr = BO->getLHS();
283 const Expr *MemFnExpr = BO->getRHS();
284
285 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000286 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000287
Anders Carlsson27da15b2010-01-01 20:29:01 +0000288 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000289 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000290 const CXXRecordDecl *RD =
291 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
292
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000294 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295
296 // Emit the 'this' pointer.
297 llvm::Value *This;
298
John McCalle3027922010-08-25 11:45:40 +0000299 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000300 This = EmitScalarExpr(BaseExpr);
301 else
302 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000303
John McCall475999d2010-08-22 00:05:51 +0000304 // Ask the ABI to load the callee. Note that This is modified.
305 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000306 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000307
Anders Carlsson27da15b2010-01-01 20:29:01 +0000308 CallArgList Args;
309
310 QualType ThisType =
311 getContext().getPointerType(getContext().getTagDeclType(RD));
312
313 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000314 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000315
316 // And the rest of the call args
317 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCalla729c622012-02-17 03:33:10 +0000318 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000319 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000320}
321
322RValue
323CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
324 const CXXMethodDecl *MD,
325 ReturnValueSlot ReturnValue) {
326 assert(MD->isInstance() &&
327 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000328 LValue LV = EmitLValue(E->getArg(0));
329 llvm::Value *This = LV.getAddress();
330
Douglas Gregor146b8e92011-09-06 16:26:56 +0000331 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
332 MD->isTrivial()) {
333 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
334 QualType Ty = E->getType();
335 EmitAggregateCopy(This, Src, Ty);
336 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000337 }
338
Anders Carlssonc36783e2011-05-08 20:32:23 +0000339 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000340 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000341 E->arg_begin() + 1, E->arg_end());
342}
343
Peter Collingbournefe883422011-10-06 18:29:37 +0000344RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
345 ReturnValueSlot ReturnValue) {
346 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
347}
348
Eli Friedmanfde961d2011-10-14 02:27:24 +0000349static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
350 llvm::Value *DestPtr,
351 const CXXRecordDecl *Base) {
352 if (Base->isEmpty())
353 return;
354
355 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
356
357 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
358 CharUnits Size = Layout.getNonVirtualSize();
359 CharUnits Align = Layout.getNonVirtualAlign();
360
361 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
362
363 // If the type contains a pointer to data member we can't memset it to zero.
364 // Instead, create a null constant and copy it to the destination.
365 // TODO: there are other patterns besides zero that we can usefully memset,
366 // like -1, which happens to be the pattern used by member-pointers.
367 // TODO: isZeroInitializable can be over-conservative in the case where a
368 // virtual base contains a member pointer.
369 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
370 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
371
372 llvm::GlobalVariable *NullVariable =
373 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
374 /*isConstant=*/true,
375 llvm::GlobalVariable::PrivateLinkage,
376 NullConstant, Twine());
377 NullVariable->setAlignment(Align.getQuantity());
378 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
379
380 // Get and call the appropriate llvm.memcpy overload.
381 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
382 return;
383 }
384
385 // Otherwise, just memset the whole thing to zero. This is legal
386 // because in LLVM, all default initializers (other than the ones we just
387 // handled above) are guaranteed to have a bit pattern of all zeros.
388 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
389 Align.getQuantity());
390}
391
Anders Carlsson27da15b2010-01-01 20:29:01 +0000392void
John McCall7a626f62010-09-15 10:14:12 +0000393CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
394 AggValueSlot Dest) {
395 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000396 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000397
398 // If we require zero initialization before (or instead of) calling the
399 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000400 // constructor, emit the zero initialization now, unless destination is
401 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000402 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
403 switch (E->getConstructionKind()) {
404 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000405 case CXXConstructExpr::CK_Complete:
406 EmitNullInitialization(Dest.getAddr(), E->getType());
407 break;
408 case CXXConstructExpr::CK_VirtualBase:
409 case CXXConstructExpr::CK_NonVirtualBase:
410 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
411 break;
412 }
413 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000414
415 // If this is a call to a trivial default constructor, do nothing.
416 if (CD->isTrivial() && CD->isDefaultConstructor())
417 return;
418
John McCall8ea46b62010-09-18 00:58:34 +0000419 // Elide the constructor if we're constructing from a temporary.
420 // The temporary check is required because Sema sets this on NRVO
421 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000422 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000423 assert(getContext().hasSameUnqualifiedType(E->getType(),
424 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000425 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
426 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000427 return;
428 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000429 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000430
John McCallf677a8e2011-07-13 06:10:41 +0000431 if (const ConstantArrayType *arrayType
432 = getContext().getAsConstantArrayType(E->getType())) {
433 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000434 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000435 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000436 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000437 bool ForVirtualBase = false;
438
439 switch (E->getConstructionKind()) {
440 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000441 // We should be emitting a constructor; GlobalDecl will assert this
442 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000443 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000444
Alexis Hunt271c3682011-05-03 20:19:28 +0000445 case CXXConstructExpr::CK_Complete:
446 Type = Ctor_Complete;
447 break;
448
449 case CXXConstructExpr::CK_VirtualBase:
450 ForVirtualBase = true;
451 // fall-through
452
453 case CXXConstructExpr::CK_NonVirtualBase:
454 Type = Ctor_Base;
455 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000456
Anders Carlsson27da15b2010-01-01 20:29:01 +0000457 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000458 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000459 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000460 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000461}
462
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000463void
464CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
465 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000466 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000467 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000468 Exp = E->getSubExpr();
469 assert(isa<CXXConstructExpr>(Exp) &&
470 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
471 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
472 const CXXConstructorDecl *CD = E->getConstructor();
473 RunCleanupsScope Scope(*this);
474
475 // If we require zero initialization before (or instead of) calling the
476 // constructor, as can be the case with a non-user-provided default
477 // constructor, emit the zero initialization now.
478 // FIXME. Do I still need this for a copy ctor synthesis?
479 if (E->requiresZeroInitialization())
480 EmitNullInitialization(Dest, E->getType());
481
Chandler Carruth99da11c2010-11-15 13:54:43 +0000482 assert(!getContext().getAsConstantArrayType(E->getType())
483 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000484 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
485 E->arg_begin(), E->arg_end());
486}
487
John McCall8ed55a52010-09-02 09:58:18 +0000488static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
489 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000490 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000491 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000492
John McCall7ec4b432011-05-16 01:05:12 +0000493 // No cookie is required if the operator new[] being used is the
494 // reserved placement operator new[].
495 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000496 return CharUnits::Zero();
497
John McCall284c48f2011-01-27 09:37:56 +0000498 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000499}
500
John McCall036f2f62011-05-15 07:14:44 +0000501static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
502 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000503 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000504 llvm::Value *&numElements,
505 llvm::Value *&sizeWithoutCookie) {
506 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000507
John McCall036f2f62011-05-15 07:14:44 +0000508 if (!e->isArray()) {
509 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
510 sizeWithoutCookie
511 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
512 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000513 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000514
John McCall036f2f62011-05-15 07:14:44 +0000515 // The width of size_t.
516 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
517
John McCall8ed55a52010-09-02 09:58:18 +0000518 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000519 llvm::APInt cookieSize(sizeWidth,
520 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000521
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000522 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000523 // We multiply the size of all dimensions for NumElements.
524 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000525 numElements = CGF.EmitScalarExpr(e->getArraySize());
526 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000527
John McCall036f2f62011-05-15 07:14:44 +0000528 // The number of elements can be have an arbitrary integer type;
529 // essentially, we need to multiply it by a constant factor, add a
530 // cookie size, and verify that the result is representable as a
531 // size_t. That's just a gloss, though, and it's wrong in one
532 // important way: if the count is negative, it's an error even if
533 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000534 bool isSigned
535 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000536 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000537 = cast<llvm::IntegerType>(numElements->getType());
538 unsigned numElementsWidth = numElementsType->getBitWidth();
539
540 // Compute the constant factor.
541 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000542 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000543 = CGF.getContext().getAsConstantArrayType(type)) {
544 type = CAT->getElementType();
545 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000546 }
547
John McCall036f2f62011-05-15 07:14:44 +0000548 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
549 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
550 typeSizeMultiplier *= arraySizeMultiplier;
551
552 // This will be a size_t.
553 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000554
Chris Lattner32ac5832010-07-20 21:55:52 +0000555 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
556 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000557 if (llvm::ConstantInt *numElementsC =
558 dyn_cast<llvm::ConstantInt>(numElements)) {
559 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000560
John McCall036f2f62011-05-15 07:14:44 +0000561 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000562
John McCall036f2f62011-05-15 07:14:44 +0000563 // If 'count' was a negative number, it's an overflow.
564 if (isSigned && count.isNegative())
565 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000566
John McCall036f2f62011-05-15 07:14:44 +0000567 // We want to do all this arithmetic in size_t. If numElements is
568 // wider than that, check whether it's already too big, and if so,
569 // overflow.
570 else if (numElementsWidth > sizeWidth &&
571 numElementsWidth - sizeWidth > count.countLeadingZeros())
572 hasAnyOverflow = true;
573
574 // Okay, compute a count at the right width.
575 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
576
Sebastian Redlf862eb62012-02-22 17:37:52 +0000577 // If there is a brace-initializer, we cannot allocate fewer elements than
578 // there are initializers. If we do, that's treated like an overflow.
579 if (adjustedCount.ult(minElements))
580 hasAnyOverflow = true;
581
John McCall036f2f62011-05-15 07:14:44 +0000582 // Scale numElements by that. This might overflow, but we don't
583 // care because it only overflows if allocationSize does, too, and
584 // if that overflows then we shouldn't use this.
585 numElements = llvm::ConstantInt::get(CGF.SizeTy,
586 adjustedCount * arraySizeMultiplier);
587
588 // Compute the size before cookie, and track whether it overflowed.
589 bool overflow;
590 llvm::APInt allocationSize
591 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
592 hasAnyOverflow |= overflow;
593
594 // Add in the cookie, and check whether it's overflowed.
595 if (cookieSize != 0) {
596 // Save the current size without a cookie. This shouldn't be
597 // used if there was overflow.
598 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
599
600 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
601 hasAnyOverflow |= overflow;
602 }
603
604 // On overflow, produce a -1 so operator new will fail.
605 if (hasAnyOverflow) {
606 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
607 } else {
608 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
609 }
610
611 // Otherwise, we might need to use the overflow intrinsics.
612 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000613 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000614 // 1) if isSigned, we need to check whether numElements is negative;
615 // 2) if numElementsWidth > sizeWidth, we need to check whether
616 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000617 // 3) if minElements > 0, we need to check whether numElements is smaller
618 // than that.
619 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000620 // sizeWithoutCookie := numElements * typeSizeMultiplier
621 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000622 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000623 // size := sizeWithoutCookie + cookieSize
624 // and check whether it overflows.
625
626 llvm::Value *hasOverflow = 0;
627
628 // If numElementsWidth > sizeWidth, then one way or another, we're
629 // going to have to do a comparison for (2), and this happens to
630 // take care of (1), too.
631 if (numElementsWidth > sizeWidth) {
632 llvm::APInt threshold(numElementsWidth, 1);
633 threshold <<= sizeWidth;
634
635 llvm::Value *thresholdV
636 = llvm::ConstantInt::get(numElementsType, threshold);
637
638 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
639 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
640
641 // Otherwise, if we're signed, we want to sext up to size_t.
642 } else if (isSigned) {
643 if (numElementsWidth < sizeWidth)
644 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
645
646 // If there's a non-1 type size multiplier, then we can do the
647 // signedness check at the same time as we do the multiply
648 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000649 // unsigned overflow. Otherwise, we have to do it here. But at least
650 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000651 if (typeSizeMultiplier == 1)
652 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000653 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000654
655 // Otherwise, zext up to size_t if necessary.
656 } else if (numElementsWidth < sizeWidth) {
657 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
658 }
659
660 assert(numElements->getType() == CGF.SizeTy);
661
Sebastian Redlf862eb62012-02-22 17:37:52 +0000662 if (minElements) {
663 // Don't allow allocation of fewer elements than we have initializers.
664 if (!hasOverflow) {
665 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
666 llvm::ConstantInt::get(CGF.SizeTy, minElements));
667 } else if (numElementsWidth > sizeWidth) {
668 // The other existing overflow subsumes this check.
669 // We do an unsigned comparison, since any signed value < -1 is
670 // taken care of either above or below.
671 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
672 CGF.Builder.CreateICmpULT(numElements,
673 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
674 }
675 }
676
John McCall036f2f62011-05-15 07:14:44 +0000677 size = numElements;
678
679 // Multiply by the type size if necessary. This multiplier
680 // includes all the factors for nested arrays.
681 //
682 // This step also causes numElements to be scaled up by the
683 // nested-array factor if necessary. Overflow on this computation
684 // can be ignored because the result shouldn't be used if
685 // allocation fails.
686 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000687 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000688 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000689
690 llvm::Value *tsmV =
691 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
692 llvm::Value *result =
693 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
694
695 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
696 if (hasOverflow)
697 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
698 else
699 hasOverflow = overflowed;
700
701 size = CGF.Builder.CreateExtractValue(result, 0);
702
703 // Also scale up numElements by the array size multiplier.
704 if (arraySizeMultiplier != 1) {
705 // If the base element type size is 1, then we can re-use the
706 // multiply we just did.
707 if (typeSize.isOne()) {
708 assert(arraySizeMultiplier == typeSizeMultiplier);
709 numElements = size;
710
711 // Otherwise we need a separate multiply.
712 } else {
713 llvm::Value *asmV =
714 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
715 numElements = CGF.Builder.CreateMul(numElements, asmV);
716 }
717 }
718 } else {
719 // numElements doesn't need to be scaled.
720 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000721 }
722
John McCall036f2f62011-05-15 07:14:44 +0000723 // Add in the cookie size if necessary.
724 if (cookieSize != 0) {
725 sizeWithoutCookie = size;
726
John McCall036f2f62011-05-15 07:14:44 +0000727 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000728 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000729
730 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
731 llvm::Value *result =
732 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
733
734 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
735 if (hasOverflow)
736 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
737 else
738 hasOverflow = overflowed;
739
740 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000741 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000742
John McCall036f2f62011-05-15 07:14:44 +0000743 // If we had any possibility of dynamic overflow, make a select to
744 // overwrite 'size' with an all-ones value, which should cause
745 // operator new to throw.
746 if (hasOverflow)
747 size = CGF.Builder.CreateSelect(hasOverflow,
748 llvm::Constant::getAllOnesValue(CGF.SizeTy),
749 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000750 }
John McCall8ed55a52010-09-02 09:58:18 +0000751
John McCall036f2f62011-05-15 07:14:44 +0000752 if (cookieSize == 0)
753 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000754 else
John McCall036f2f62011-05-15 07:14:44 +0000755 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000756
John McCall036f2f62011-05-15 07:14:44 +0000757 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000758}
759
Sebastian Redlf862eb62012-02-22 17:37:52 +0000760static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
761 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000762
Eli Friedman38cd36d2011-12-03 02:13:40 +0000763 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000764 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000765 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000766 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000767 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000768 else if (AllocType->isAnyComplexType())
769 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
770 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000771 else {
772 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000773 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000774 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000775 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000776 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000777 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000778
779 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000780 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000781}
782
783void
784CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000785 QualType elementType,
786 llvm::Value *beginPtr,
787 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000788 if (!E->hasInitializer())
789 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000790
Sebastian Redlf862eb62012-02-22 17:37:52 +0000791 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000792 // Find the end of the array, hoisted out of the loop.
793 llvm::Value *endPtr =
794 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
795
Sebastian Redlf862eb62012-02-22 17:37:52 +0000796 unsigned initializerElements = 0;
797
798 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000799 llvm::AllocaInst *endOfInit = 0;
800 QualType::DestructionKind dtorKind = elementType.isDestructedType();
801 EHScopeStack::stable_iterator cleanup;
802 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000803 // If the initializer is an initializer list, first do the explicit elements.
804 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
805 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000806
807 // Enter a partial-destruction cleanup if necessary.
808 if (needsEHCleanup(dtorKind)) {
809 // In principle we could tell the cleanup where we are more
810 // directly, but the control flow can get so varied here that it
811 // would actually be quite complex. Therefore we go through an
812 // alloca.
813 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
814 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
815 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
816 getDestroyer(dtorKind));
817 cleanup = EHStack.stable_begin();
818 }
819
Sebastian Redlf862eb62012-02-22 17:37:52 +0000820 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000821 // Tell the cleanup that it needs to destroy up to this
822 // element. TODO: some of these stores can be trivially
823 // observed to be unnecessary.
824 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000825 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
826 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
827 }
828
829 // The remaining elements are filled with the array filler expression.
830 Init = ILE->getArrayFiller();
831 }
832
John McCall99210dc2011-09-15 06:49:18 +0000833 // Create the continuation block.
834 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
835
Sebastian Redlf862eb62012-02-22 17:37:52 +0000836 // If the number of elements isn't constant, we have to now check if there is
837 // anything left to initialize.
838 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
839 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000840 if (constNum->getZExtValue() <= initializerElements) {
841 // If there was a cleanup, deactivate it.
842 if (cleanupDominator)
843 DeactivateCleanupBlock(cleanup, cleanupDominator);;
844 return;
845 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000846 } else {
John McCall99210dc2011-09-15 06:49:18 +0000847 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000848 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000849 "array.isempty");
850 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
851 EmitBlock(nonEmptyBB);
852 }
853
854 // Enter the loop.
855 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
856 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
857
858 EmitBlock(loopBB);
859
860 // Set up the current-element phi.
861 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000862 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
863 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000864
Chad Rosierf62290a2012-02-24 00:13:55 +0000865 // Store the new cleanup position for irregular cleanups.
866 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
867
John McCall99210dc2011-09-15 06:49:18 +0000868 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000869 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000870 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
871 getDestroyer(dtorKind));
872 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000873 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000874 }
875
876 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000877 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000878
879 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000880 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000881 DeactivateCleanupBlock(cleanup, cleanupDominator);
882 cleanupDominator->eraseFromParent();
883 }
John McCall99210dc2011-09-15 06:49:18 +0000884
885 // Advance to the next element.
886 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
887
888 // Check whether we've gotten to the end of the array and, if so,
889 // exit the loop.
890 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
891 Builder.CreateCondBr(isEnd, contBB, loopBB);
892 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
893
894 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000895}
896
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000897static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
898 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000899 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000900 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000901 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000902 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000903}
904
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000905static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000906 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000907 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000908 llvm::Value *NumElements,
909 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000910 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000911 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000912 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
913 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000914 bool RequiresZeroInitialization = false;
Douglas Gregord1531032012-02-23 17:07:43 +0000915 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000916 // If new expression did not specify value-initialization, then there
917 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000918 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000919 return;
920
John McCall99210dc2011-09-15 06:49:18 +0000921 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000922 // Optimization: since zero initialization will just set the memory
923 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000924 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000925 return;
926 }
927
928 RequiresZeroInitialization = true;
929 }
John McCallf677a8e2011-07-13 06:10:41 +0000930
Sebastian Redl6047f072012-02-16 12:22:20 +0000931 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
932 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000933 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000934 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000935 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000936 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000937 // Optimization: since zero initialization will just set the memory
938 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000939 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
940 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000941 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000942 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
943 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000944 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000945
Sebastian Redl6047f072012-02-16 12:22:20 +0000946 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000947 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000948
Sebastian Redlf862eb62012-02-22 17:37:52 +0000949 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000950}
951
John McCall824c2f52010-09-14 07:57:04 +0000952namespace {
953 /// A cleanup to call the given 'operator delete' function upon
954 /// abnormal exit from a new expression.
955 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
956 size_t NumPlacementArgs;
957 const FunctionDecl *OperatorDelete;
958 llvm::Value *Ptr;
959 llvm::Value *AllocSize;
960
961 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
962
963 public:
964 static size_t getExtraSize(size_t NumPlacementArgs) {
965 return NumPlacementArgs * sizeof(RValue);
966 }
967
968 CallDeleteDuringNew(size_t NumPlacementArgs,
969 const FunctionDecl *OperatorDelete,
970 llvm::Value *Ptr,
971 llvm::Value *AllocSize)
972 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
973 Ptr(Ptr), AllocSize(AllocSize) {}
974
975 void setPlacementArg(unsigned I, RValue Arg) {
976 assert(I < NumPlacementArgs && "index out of range");
977 getPlacementArgs()[I] = Arg;
978 }
979
John McCall30317fd2011-07-12 20:27:29 +0000980 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +0000981 const FunctionProtoType *FPT
982 = OperatorDelete->getType()->getAs<FunctionProtoType>();
983 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000984 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000985
986 CallArgList DeleteArgs;
987
988 // The first argument is always a void*.
989 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000990 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000991
992 // A member 'operator delete' can take an extra 'size_t' argument.
993 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000994 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000995
996 // Pass the rest of the arguments, which must match exactly.
997 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000998 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000999
1000 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001001 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +00001002 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1003 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1004 }
1005 };
John McCall7f9c92a2010-09-17 00:50:28 +00001006
1007 /// A cleanup to call the given 'operator delete' function upon
1008 /// abnormal exit from a new expression when the new expression is
1009 /// conditional.
1010 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1011 size_t NumPlacementArgs;
1012 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001013 DominatingValue<RValue>::saved_type Ptr;
1014 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001015
John McCallcb5f77f2011-01-28 10:53:53 +00001016 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1017 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001018 }
1019
1020 public:
1021 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001022 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001023 }
1024
1025 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1026 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001027 DominatingValue<RValue>::saved_type Ptr,
1028 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001029 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1030 Ptr(Ptr), AllocSize(AllocSize) {}
1031
John McCallcb5f77f2011-01-28 10:53:53 +00001032 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001033 assert(I < NumPlacementArgs && "index out of range");
1034 getPlacementArgs()[I] = Arg;
1035 }
1036
John McCall30317fd2011-07-12 20:27:29 +00001037 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001038 const FunctionProtoType *FPT
1039 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1040 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1041 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1042
1043 CallArgList DeleteArgs;
1044
1045 // The first argument is always a void*.
1046 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001047 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001048
1049 // A member 'operator delete' can take an extra 'size_t' argument.
1050 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001051 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001052 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001053 }
1054
1055 // Pass the rest of the arguments, which must match exactly.
1056 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001057 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001058 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001059 }
1060
1061 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001062 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001063 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1064 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1065 }
1066 };
1067}
1068
1069/// Enter a cleanup to call 'operator delete' if the initializer in a
1070/// new-expression throws.
1071static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1072 const CXXNewExpr *E,
1073 llvm::Value *NewPtr,
1074 llvm::Value *AllocSize,
1075 const CallArgList &NewArgs) {
1076 // If we're not inside a conditional branch, then the cleanup will
1077 // dominate and we can do the easier (and more efficient) thing.
1078 if (!CGF.isInConditionalBranch()) {
1079 CallDeleteDuringNew *Cleanup = CGF.EHStack
1080 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1081 E->getNumPlacementArgs(),
1082 E->getOperatorDelete(),
1083 NewPtr, AllocSize);
1084 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001085 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001086
1087 return;
1088 }
1089
1090 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001091 DominatingValue<RValue>::saved_type SavedNewPtr =
1092 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1093 DominatingValue<RValue>::saved_type SavedAllocSize =
1094 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001095
1096 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001097 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001098 E->getNumPlacementArgs(),
1099 E->getOperatorDelete(),
1100 SavedNewPtr,
1101 SavedAllocSize);
1102 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001103 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001104 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001105
John McCallf4beacd2011-11-10 10:43:54 +00001106 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001107}
1108
Anders Carlssoncc52f652009-09-22 22:53:17 +00001109llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001110 // The element type being allocated.
1111 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001112
John McCall75f94982011-03-07 03:12:35 +00001113 // 1. Build a call to the allocation function.
1114 FunctionDecl *allocator = E->getOperatorNew();
1115 const FunctionProtoType *allocatorType =
1116 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001117
John McCall75f94982011-03-07 03:12:35 +00001118 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001119
1120 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001121 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001122
Sebastian Redlf862eb62012-02-22 17:37:52 +00001123 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1124 unsigned minElements = 0;
1125 if (E->isArray() && E->hasInitializer()) {
1126 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1127 minElements = ILE->getNumInits();
1128 }
1129
John McCall75f94982011-03-07 03:12:35 +00001130 llvm::Value *numElements = 0;
1131 llvm::Value *allocSizeWithoutCookie = 0;
1132 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001133 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1134 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001135
Eli Friedman43dca6a2011-05-02 17:57:46 +00001136 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001137
1138 // Emit the rest of the arguments.
1139 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001140 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001141
1142 // First, use the types from the function type.
1143 // We start at 1 here because the first argument (the allocation size)
1144 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001145 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1146 ++i, ++placementArg) {
1147 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001148
John McCall75f94982011-03-07 03:12:35 +00001149 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1150 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001151 "type mismatch in call argument!");
1152
John McCall32ea9692011-03-11 20:59:21 +00001153 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001154 }
1155
1156 // Either we've emitted all the call args, or we have a call to a
1157 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001158 assert((placementArg == E->placement_arg_end() ||
1159 allocatorType->isVariadic()) &&
1160 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001161
1162 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001163 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1164 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001165 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001166 }
1167
John McCall7ec4b432011-05-16 01:05:12 +00001168 // Emit the allocation call. If the allocator is a global placement
1169 // operator, just "inline" it directly.
1170 RValue RV;
1171 if (allocator->isReservedGlobalPlacementOperator()) {
1172 assert(allocatorArgs.size() == 2);
1173 RV = allocatorArgs[1].RV;
1174 // TODO: kill any unnecessary computations done for the size
1175 // argument.
1176 } else {
John McCalla729c622012-02-17 03:33:10 +00001177 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1178 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001179 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1180 allocatorArgs, allocator);
1181 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001182
John McCall75f94982011-03-07 03:12:35 +00001183 // Emit a null check on the allocation result if the allocation
1184 // function is allowed to return null (because it has a non-throwing
1185 // exception spec; for this part, we inline
1186 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1187 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001188 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001189 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001190
John McCall75f94982011-03-07 03:12:35 +00001191 llvm::BasicBlock *nullCheckBB = 0;
1192 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001193
John McCall75f94982011-03-07 03:12:35 +00001194 llvm::Value *allocation = RV.getScalarVal();
1195 unsigned AS =
1196 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001197
John McCallf7dcf322011-03-07 01:52:56 +00001198 // The null-check means that the initializer is conditionally
1199 // evaluated.
1200 ConditionalEvaluation conditional(*this);
1201
John McCall75f94982011-03-07 03:12:35 +00001202 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001203 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001204
1205 nullCheckBB = Builder.GetInsertBlock();
1206 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1207 contBB = createBasicBlock("new.cont");
1208
1209 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1210 Builder.CreateCondBr(isNull, contBB, notNullBB);
1211 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001212 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001213
John McCall824c2f52010-09-14 07:57:04 +00001214 // If there's an operator delete, enter a cleanup to call it if an
1215 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001216 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001217 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001218 if (E->getOperatorDelete() &&
1219 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001220 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1221 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001222 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001223 }
1224
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001225 assert((allocSize == allocSizeWithoutCookie) ==
1226 CalculateCookiePadding(*this, E).isZero());
1227 if (allocSize != allocSizeWithoutCookie) {
1228 assert(E->isArray());
1229 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1230 numElements,
1231 E, allocType);
1232 }
1233
Chris Lattner2192fe52011-07-18 04:24:23 +00001234 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001235 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1236 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001237
John McCall99210dc2011-09-15 06:49:18 +00001238 EmitNewInitializer(*this, E, allocType, result, numElements,
1239 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001240 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001241 // NewPtr is a pointer to the base element type. If we're
1242 // allocating an array of arrays, we'll need to cast back to the
1243 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001244 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001245 if (result->getType() != resultType)
1246 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001247 }
John McCall824c2f52010-09-14 07:57:04 +00001248
1249 // Deactivate the 'operator delete' cleanup if we finished
1250 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001251 if (operatorDeleteCleanup.isValid()) {
1252 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1253 cleanupDominator->eraseFromParent();
1254 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001255
John McCall75f94982011-03-07 03:12:35 +00001256 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001257 conditional.end(*this);
1258
John McCall75f94982011-03-07 03:12:35 +00001259 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1260 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001261
Jay Foad20c0f022011-03-30 11:28:58 +00001262 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001263 PHI->addIncoming(result, notNullBB);
1264 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1265 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001266
John McCall75f94982011-03-07 03:12:35 +00001267 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001268 }
John McCall8ed55a52010-09-02 09:58:18 +00001269
John McCall75f94982011-03-07 03:12:35 +00001270 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001271}
1272
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001273void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1274 llvm::Value *Ptr,
1275 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001276 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1277
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001278 const FunctionProtoType *DeleteFTy =
1279 DeleteFD->getType()->getAs<FunctionProtoType>();
1280
1281 CallArgList DeleteArgs;
1282
Anders Carlsson21122cf2009-12-13 20:04:38 +00001283 // Check if we need to pass the size to the delete operator.
1284 llvm::Value *Size = 0;
1285 QualType SizeTy;
1286 if (DeleteFTy->getNumArgs() == 2) {
1287 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001288 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1289 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1290 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001291 }
1292
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001293 QualType ArgTy = DeleteFTy->getArgType(0);
1294 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001295 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001296
Anders Carlsson21122cf2009-12-13 20:04:38 +00001297 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001298 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001299
1300 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001301 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001302 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001303 DeleteArgs, DeleteFD);
1304}
1305
John McCall8ed55a52010-09-02 09:58:18 +00001306namespace {
1307 /// Calls the given 'operator delete' on a single object.
1308 struct CallObjectDelete : EHScopeStack::Cleanup {
1309 llvm::Value *Ptr;
1310 const FunctionDecl *OperatorDelete;
1311 QualType ElementType;
1312
1313 CallObjectDelete(llvm::Value *Ptr,
1314 const FunctionDecl *OperatorDelete,
1315 QualType ElementType)
1316 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1317
John McCall30317fd2011-07-12 20:27:29 +00001318 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001319 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1320 }
1321 };
1322}
1323
1324/// Emit the code for deleting a single object.
1325static void EmitObjectDelete(CodeGenFunction &CGF,
1326 const FunctionDecl *OperatorDelete,
1327 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001328 QualType ElementType,
1329 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001330 // Find the destructor for the type, if applicable. If the
1331 // destructor is virtual, we'll just emit the vcall and return.
1332 const CXXDestructorDecl *Dtor = 0;
1333 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1334 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001335 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001336 Dtor = RD->getDestructor();
1337
1338 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001339 if (UseGlobalDelete) {
1340 // If we're supposed to call the global delete, make sure we do so
1341 // even if the destructor throws.
1342 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1343 Ptr, OperatorDelete,
1344 ElementType);
1345 }
1346
Chris Lattner2192fe52011-07-18 04:24:23 +00001347 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001348 CGF.getTypes().GetFunctionType(
1349 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001350
1351 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001352 = CGF.BuildVirtualCall(Dtor,
1353 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1354 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001355 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1356 0, 0);
1357
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001358 if (UseGlobalDelete) {
1359 CGF.PopCleanupBlock();
1360 }
1361
John McCall8ed55a52010-09-02 09:58:18 +00001362 return;
1363 }
1364 }
1365 }
1366
1367 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001368 // This doesn't have to a conditional cleanup because we're going
1369 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001370 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1371 Ptr, OperatorDelete, ElementType);
1372
1373 if (Dtor)
1374 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1375 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001376 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001377 ElementType->isObjCLifetimeType()) {
1378 switch (ElementType.getObjCLifetime()) {
1379 case Qualifiers::OCL_None:
1380 case Qualifiers::OCL_ExplicitNone:
1381 case Qualifiers::OCL_Autoreleasing:
1382 break;
John McCall8ed55a52010-09-02 09:58:18 +00001383
John McCall31168b02011-06-15 23:02:42 +00001384 case Qualifiers::OCL_Strong: {
1385 // Load the pointer value.
1386 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1387 ElementType.isVolatileQualified());
1388
1389 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1390 break;
1391 }
1392
1393 case Qualifiers::OCL_Weak:
1394 CGF.EmitARCDestroyWeak(Ptr);
1395 break;
1396 }
1397 }
1398
John McCall8ed55a52010-09-02 09:58:18 +00001399 CGF.PopCleanupBlock();
1400}
1401
1402namespace {
1403 /// Calls the given 'operator delete' on an array of objects.
1404 struct CallArrayDelete : EHScopeStack::Cleanup {
1405 llvm::Value *Ptr;
1406 const FunctionDecl *OperatorDelete;
1407 llvm::Value *NumElements;
1408 QualType ElementType;
1409 CharUnits CookieSize;
1410
1411 CallArrayDelete(llvm::Value *Ptr,
1412 const FunctionDecl *OperatorDelete,
1413 llvm::Value *NumElements,
1414 QualType ElementType,
1415 CharUnits CookieSize)
1416 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1417 ElementType(ElementType), CookieSize(CookieSize) {}
1418
John McCall30317fd2011-07-12 20:27:29 +00001419 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001420 const FunctionProtoType *DeleteFTy =
1421 OperatorDelete->getType()->getAs<FunctionProtoType>();
1422 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1423
1424 CallArgList Args;
1425
1426 // Pass the pointer as the first argument.
1427 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1428 llvm::Value *DeletePtr
1429 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001430 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001431
1432 // Pass the original requested size as the second argument.
1433 if (DeleteFTy->getNumArgs() == 2) {
1434 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001435 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001436 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1437
1438 CharUnits ElementTypeSize =
1439 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1440
1441 // The size of an element, multiplied by the number of elements.
1442 llvm::Value *Size
1443 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1444 Size = CGF.Builder.CreateMul(Size, NumElements);
1445
1446 // Plus the size of the cookie if applicable.
1447 if (!CookieSize.isZero()) {
1448 llvm::Value *CookieSizeV
1449 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1450 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1451 }
1452
Eli Friedman43dca6a2011-05-02 17:57:46 +00001453 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001454 }
1455
1456 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001457 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001458 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1459 ReturnValueSlot(), Args, OperatorDelete);
1460 }
1461 };
1462}
1463
1464/// Emit the code for deleting an array of objects.
1465static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001466 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001467 llvm::Value *deletedPtr,
1468 QualType elementType) {
1469 llvm::Value *numElements = 0;
1470 llvm::Value *allocatedPtr = 0;
1471 CharUnits cookieSize;
1472 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1473 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001474
John McCallca2c56f2011-07-13 01:41:37 +00001475 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001476
1477 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001478 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001479 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001480 allocatedPtr, operatorDelete,
1481 numElements, elementType,
1482 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001483
John McCallca2c56f2011-07-13 01:41:37 +00001484 // Destroy the elements.
1485 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1486 assert(numElements && "no element count for a type with a destructor!");
1487
John McCallca2c56f2011-07-13 01:41:37 +00001488 llvm::Value *arrayEnd =
1489 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001490
1491 // Note that it is legal to allocate a zero-length array, and we
1492 // can never fold the check away because the length should always
1493 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001494 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1495 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001496 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001497 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001498 }
1499
John McCallca2c56f2011-07-13 01:41:37 +00001500 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001501 CGF.PopCleanupBlock();
1502}
1503
Anders Carlssoncc52f652009-09-22 22:53:17 +00001504void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001505
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001506 // Get at the argument before we performed the implicit conversion
1507 // to void*.
1508 const Expr *Arg = E->getArgument();
1509 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001510 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001511 ICE->getType()->isVoidPointerType())
1512 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001513 else
1514 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001515 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001516
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001517 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001518
1519 // Null check the pointer.
1520 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1521 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1522
Anders Carlsson98981b12011-04-11 00:30:07 +00001523 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001524
1525 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1526 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001527
John McCall8ed55a52010-09-02 09:58:18 +00001528 // We might be deleting a pointer to array. If so, GEP down to the
1529 // first non-array element.
1530 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1531 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1532 if (DeleteTy->isConstantArrayType()) {
1533 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001534 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001535
1536 GEP.push_back(Zero); // point at the outermost array
1537
1538 // For each layer of array type we're pointing at:
1539 while (const ConstantArrayType *Arr
1540 = getContext().getAsConstantArrayType(DeleteTy)) {
1541 // 1. Unpeel the array type.
1542 DeleteTy = Arr->getElementType();
1543
1544 // 2. GEP to the first element of the array.
1545 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001546 }
John McCall8ed55a52010-09-02 09:58:18 +00001547
Jay Foad040dd822011-07-22 08:16:57 +00001548 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001549 }
1550
Douglas Gregor04f36212010-09-02 17:38:50 +00001551 assert(ConvertTypeForMem(DeleteTy) ==
1552 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001553
1554 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001555 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001556 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001557 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1558 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001559 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001560
Anders Carlssoncc52f652009-09-22 22:53:17 +00001561 EmitBlock(DeleteEnd);
1562}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001563
Anders Carlsson0c633502011-04-11 14:13:40 +00001564static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1565 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001566 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001567
1568 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1569}
1570
1571static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001572 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001573 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001574 CGF.Builder.CreateUnreachable();
1575}
1576
Anders Carlsson940f02d2011-04-18 00:57:03 +00001577static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1578 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001579 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001580 // Get the vtable pointer.
1581 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1582
1583 // C++ [expr.typeid]p2:
1584 // If the glvalue expression is obtained by applying the unary * operator to
1585 // a pointer and the pointer is a null pointer value, the typeid expression
1586 // throws the std::bad_typeid exception.
1587 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1588 if (UO->getOpcode() == UO_Deref) {
1589 llvm::BasicBlock *BadTypeidBlock =
1590 CGF.createBasicBlock("typeid.bad_typeid");
1591 llvm::BasicBlock *EndBlock =
1592 CGF.createBasicBlock("typeid.end");
1593
1594 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1595 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1596
1597 CGF.EmitBlock(BadTypeidBlock);
1598 EmitBadTypeidCall(CGF);
1599 CGF.EmitBlock(EndBlock);
1600 }
1601 }
1602
1603 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1604 StdTypeInfoPtrTy->getPointerTo());
1605
1606 // Load the type info.
1607 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1608 return CGF.Builder.CreateLoad(Value);
1609}
1610
John McCalle4df6c82011-01-28 08:37:24 +00001611llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001612 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001613 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001614
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001615 if (E->isTypeOperand()) {
1616 llvm::Constant *TypeInfo =
1617 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001618 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001619 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001620
Anders Carlsson940f02d2011-04-18 00:57:03 +00001621 // C++ [expr.typeid]p2:
1622 // When typeid is applied to a glvalue expression whose type is a
1623 // polymorphic class type, the result refers to a std::type_info object
1624 // representing the type of the most derived object (that is, the dynamic
1625 // type) to which the glvalue refers.
1626 if (E->getExprOperand()->isGLValue()) {
1627 if (const RecordType *RT =
1628 E->getExprOperand()->getType()->getAs<RecordType>()) {
1629 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1630 if (RD->isPolymorphic())
1631 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1632 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001633 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001634 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001635
1636 QualType OperandTy = E->getExprOperand()->getType();
1637 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1638 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001639}
Mike Stump65511702009-11-16 06:50:58 +00001640
Anders Carlsson882d7902011-04-11 00:46:40 +00001641static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1642 // void *__dynamic_cast(const void *sub,
1643 // const abi::__class_type_info *src,
1644 // const abi::__class_type_info *dst,
1645 // std::ptrdiff_t src2dst_offset);
1646
Chris Lattnerece04092012-02-07 00:39:47 +00001647 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001648 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001649 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1650
Chris Lattnera5f58b02011-07-09 17:41:47 +00001651 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001652
Chris Lattner2192fe52011-07-18 04:24:23 +00001653 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001654 llvm::FunctionType::get(Int8PtrTy, Args, false);
1655
1656 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1657}
1658
1659static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1660 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001661 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001662 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1663}
1664
Anders Carlssonc1c99712011-04-11 01:45:29 +00001665static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001666 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001667 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001668 CGF.Builder.CreateUnreachable();
1669}
1670
Anders Carlsson882d7902011-04-11 00:46:40 +00001671static llvm::Value *
1672EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1673 QualType SrcTy, QualType DestTy,
1674 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001675 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001676 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001677 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001678
1679 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1680 if (PTy->getPointeeType()->isVoidType()) {
1681 // C++ [expr.dynamic.cast]p7:
1682 // If T is "pointer to cv void," then the result is a pointer to the
1683 // most derived object pointed to by v.
1684
1685 // Get the vtable pointer.
1686 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1687
1688 // Get the offset-to-top from the vtable.
1689 llvm::Value *OffsetToTop =
1690 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1691 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1692
1693 // Finally, add the offset to the pointer.
1694 Value = CGF.EmitCastToVoidPtr(Value);
1695 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1696
1697 return CGF.Builder.CreateBitCast(Value, DestLTy);
1698 }
1699 }
1700
1701 QualType SrcRecordTy;
1702 QualType DestRecordTy;
1703
1704 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1705 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1706 DestRecordTy = DestPTy->getPointeeType();
1707 } else {
1708 SrcRecordTy = SrcTy;
1709 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1710 }
1711
1712 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1713 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1714
1715 llvm::Value *SrcRTTI =
1716 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1717 llvm::Value *DestRTTI =
1718 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1719
1720 // FIXME: Actually compute a hint here.
1721 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1722
1723 // Emit the call to __dynamic_cast.
1724 Value = CGF.EmitCastToVoidPtr(Value);
1725 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1726 SrcRTTI, DestRTTI, OffsetHint);
1727 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1728
1729 /// C++ [expr.dynamic.cast]p9:
1730 /// A failed cast to reference type throws std::bad_cast
1731 if (DestTy->isReferenceType()) {
1732 llvm::BasicBlock *BadCastBlock =
1733 CGF.createBasicBlock("dynamic_cast.bad_cast");
1734
1735 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1736 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1737
1738 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001739 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001740 }
1741
1742 return Value;
1743}
1744
Anders Carlssonc1c99712011-04-11 01:45:29 +00001745static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1746 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001747 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001748 if (DestTy->isPointerType())
1749 return llvm::Constant::getNullValue(DestLTy);
1750
1751 /// C++ [expr.dynamic.cast]p9:
1752 /// A failed cast to reference type throws std::bad_cast
1753 EmitBadCastCall(CGF);
1754
1755 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1756 return llvm::UndefValue::get(DestLTy);
1757}
1758
Anders Carlsson882d7902011-04-11 00:46:40 +00001759llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001760 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001761 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001762
Anders Carlssonc1c99712011-04-11 01:45:29 +00001763 if (DCE->isAlwaysNull())
1764 return EmitDynamicCastToNull(*this, DestTy);
1765
1766 QualType SrcTy = DCE->getSubExpr()->getType();
1767
Anders Carlsson882d7902011-04-11 00:46:40 +00001768 // C++ [expr.dynamic.cast]p4:
1769 // If the value of v is a null pointer value in the pointer case, the result
1770 // is the null pointer value of type T.
1771 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001772
Anders Carlsson882d7902011-04-11 00:46:40 +00001773 llvm::BasicBlock *CastNull = 0;
1774 llvm::BasicBlock *CastNotNull = 0;
1775 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001776
Anders Carlsson882d7902011-04-11 00:46:40 +00001777 if (ShouldNullCheckSrcValue) {
1778 CastNull = createBasicBlock("dynamic_cast.null");
1779 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1780
1781 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1782 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1783 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001784 }
1785
Anders Carlsson882d7902011-04-11 00:46:40 +00001786 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1787
1788 if (ShouldNullCheckSrcValue) {
1789 EmitBranch(CastEnd);
1790
1791 EmitBlock(CastNull);
1792 EmitBranch(CastEnd);
1793 }
1794
1795 EmitBlock(CastEnd);
1796
1797 if (ShouldNullCheckSrcValue) {
1798 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1799 PHI->addIncoming(Value, CastNotNull);
1800 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1801
1802 Value = PHI;
1803 }
1804
1805 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001806}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001807
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001808void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001809 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001810 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1811 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001812
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001813 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1814 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1815 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001816 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001817 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001818
David Blaikie40ed2972012-06-06 20:45:41 +00001819 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001820 ArrayRef<VarDecl *> ArrayIndexes;
1821 if (CurField->getType()->isArrayType())
1822 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001823 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001824 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001825}