blob: a39e82408d0810a882d9f5afa838c965047a0737 [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 Espindolab7f5a9c2012-06-27 18:18:05 +0000105 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000106 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
107 return true;
108
Anders Carlsson19588aa2011-01-23 21:07:30 +0000109 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000110 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000111 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000112 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000113
Anders Carlsson19588aa2011-01-23 21:07:30 +0000114 // Similarly, if the class itself is marked 'final' it can't be overridden
115 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000116 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000117 return true;
118
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000119 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000120 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
121 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
122 // This is a record decl. We know the type and can devirtualize it.
123 return VD->getType()->isRecordType();
124 }
125
126 return false;
127 }
128
129 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000130 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000131 return true;
132
133 // And calls on bound temporaries.
134 if (isa<CXXBindTemporaryExpr>(Base))
135 return true;
136
137 // Check if this is a call expr that returns a record type.
138 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
139 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000140
Anders Carlsson27da15b2010-01-01 20:29:01 +0000141 // We can't devirtualize the call.
142 return false;
143}
144
Francois Pichet64225792011-01-18 05:04:39 +0000145// Note: This function also emit constructor calls to support a MSVC
146// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000147RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
148 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000149 const Expr *callee = CE->getCallee()->IgnoreParens();
150
151 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000152 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000153
154 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000155 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
156
Devang Patel91bbb552010-09-30 19:05:55 +0000157 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000158 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel401c9162010-10-22 18:56:27 +0000159 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000160 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
161 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
162 DI->getOrCreateRecordType(PTy->getPointeeType(),
163 MD->getParent()->getLocation());
164 }
165 }
166
Anders Carlsson27da15b2010-01-01 20:29:01 +0000167 if (MD->isStatic()) {
168 // The method is static, emit it as we would a regular call.
169 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
170 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
171 ReturnValue, CE->arg_begin(), CE->arg_end());
172 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000173
John McCall0d635f52010-09-03 01:26:39 +0000174 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000175 const Expr *Base = ME->getBase();
176 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
177 bool Devirtualize = CanUseVirtualCall &&
178 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD);
179
180 const Expr *Inner = Base;
181 if (Devirtualize)
182 Inner = Base->ignoreParenBaseCasts();
183
Anders Carlsson27da15b2010-01-01 20:29:01 +0000184 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000185 if (ME->isArrow())
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000186 This = EmitScalarExpr(Inner);
John McCalle26a8722010-12-04 08:14:53 +0000187 else
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000188 This = EmitLValue(Inner).getAddress();
189
Anders Carlsson27da15b2010-01-01 20:29:01 +0000190
John McCall0d635f52010-09-03 01:26:39 +0000191 if (MD->isTrivial()) {
192 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000193 if (isa<CXXConstructorDecl>(MD) &&
194 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
195 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000196
Sebastian Redl22653ba2011-08-30 19:58:05 +0000197 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
198 // We don't like to generate the trivial copy/move assignment operator
199 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000200 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
201 EmitAggregateCopy(This, RHS, CE->getType());
202 return RValue::get(This);
203 }
204
205 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000206 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
207 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000208 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
209 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
210 CE->arg_begin(), CE->arg_end());
211 return RValue::get(This);
212 }
213 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000214 }
215
John McCall0d635f52010-09-03 01:26:39 +0000216 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000217 const CGFunctionInfo *FInfo = 0;
218 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000219 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
220 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000221 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000222 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
223 cast<CXXConstructorDecl>(MD),
224 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000225 else
John McCalla729c622012-02-17 03:33:10 +0000226 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000227
John McCalla729c622012-02-17 03:33:10 +0000228 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000229
Anders Carlsson27da15b2010-01-01 20:29:01 +0000230 // C++ [class.virtual]p12:
231 // Explicit qualification with the scope operator (5.1) suppresses the
232 // virtual call mechanism.
233 //
234 // We also don't emit a virtual call if the base expression has a record type
235 // because then we know what the type is.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000236 bool UseVirtualCall = CanUseVirtualCall && !Devirtualize;
237 const CXXRecordDecl *MostDerivedClassDecl = Inner->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +0000238
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000240 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
241 if (UseVirtualCall) {
242 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000243 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000244 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000245 MD->isVirtual() &&
246 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000247 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000248 else if (!Devirtualize)
Rafael Espindola727a7712012-06-26 19:18:25 +0000249 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000250 else {
251 const CXXMethodDecl *DM =
252 Dtor->getCorrespondingMethodInClass(MostDerivedClassDecl);
253 assert(DM);
254 const CXXDestructorDecl *DDtor = cast<CXXDestructorDecl>(DM);
255 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
256 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000257 }
Francois Pichet64225792011-01-18 05:04:39 +0000258 } else if (const CXXConstructorDecl *Ctor =
259 dyn_cast<CXXConstructorDecl>(MD)) {
260 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000261 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000262 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000263 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000264 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000265 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000266 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000267 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000268 else if (!Devirtualize)
Rafael Espindola727a7712012-06-26 19:18:25 +0000269 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000270 else {
271 const CXXMethodDecl *DerivedMethod =
272 MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
273 assert(DerivedMethod);
274 Callee = CGM.GetAddrOfFunction(DerivedMethod, Ty);
275 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 }
277
Anders Carlssone36a6b32010-01-02 01:01:18 +0000278 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000279 CE->arg_begin(), CE->arg_end());
280}
281
282RValue
283CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
284 ReturnValueSlot ReturnValue) {
285 const BinaryOperator *BO =
286 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
287 const Expr *BaseExpr = BO->getLHS();
288 const Expr *MemFnExpr = BO->getRHS();
289
290 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000291 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000292
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000294 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 const CXXRecordDecl *RD =
296 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
297
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000299 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000300
301 // Emit the 'this' pointer.
302 llvm::Value *This;
303
John McCalle3027922010-08-25 11:45:40 +0000304 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305 This = EmitScalarExpr(BaseExpr);
306 else
307 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000308
John McCall475999d2010-08-22 00:05:51 +0000309 // Ask the ABI to load the callee. Note that This is modified.
310 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000311 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312
Anders Carlsson27da15b2010-01-01 20:29:01 +0000313 CallArgList Args;
314
315 QualType ThisType =
316 getContext().getPointerType(getContext().getTagDeclType(RD));
317
318 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000319 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000320
321 // And the rest of the call args
322 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCalla729c622012-02-17 03:33:10 +0000323 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000324 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000325}
326
327RValue
328CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
329 const CXXMethodDecl *MD,
330 ReturnValueSlot ReturnValue) {
331 assert(MD->isInstance() &&
332 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000333 LValue LV = EmitLValue(E->getArg(0));
334 llvm::Value *This = LV.getAddress();
335
Douglas Gregor146b8e92011-09-06 16:26:56 +0000336 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
337 MD->isTrivial()) {
338 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
339 QualType Ty = E->getType();
340 EmitAggregateCopy(This, Src, Ty);
341 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000342 }
343
Anders Carlssonc36783e2011-05-08 20:32:23 +0000344 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000345 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000346 E->arg_begin() + 1, E->arg_end());
347}
348
Peter Collingbournefe883422011-10-06 18:29:37 +0000349RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
350 ReturnValueSlot ReturnValue) {
351 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
352}
353
Eli Friedmanfde961d2011-10-14 02:27:24 +0000354static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
355 llvm::Value *DestPtr,
356 const CXXRecordDecl *Base) {
357 if (Base->isEmpty())
358 return;
359
360 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
361
362 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
363 CharUnits Size = Layout.getNonVirtualSize();
364 CharUnits Align = Layout.getNonVirtualAlign();
365
366 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
367
368 // If the type contains a pointer to data member we can't memset it to zero.
369 // Instead, create a null constant and copy it to the destination.
370 // TODO: there are other patterns besides zero that we can usefully memset,
371 // like -1, which happens to be the pattern used by member-pointers.
372 // TODO: isZeroInitializable can be over-conservative in the case where a
373 // virtual base contains a member pointer.
374 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
375 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
376
377 llvm::GlobalVariable *NullVariable =
378 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
379 /*isConstant=*/true,
380 llvm::GlobalVariable::PrivateLinkage,
381 NullConstant, Twine());
382 NullVariable->setAlignment(Align.getQuantity());
383 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
384
385 // Get and call the appropriate llvm.memcpy overload.
386 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
387 return;
388 }
389
390 // Otherwise, just memset the whole thing to zero. This is legal
391 // because in LLVM, all default initializers (other than the ones we just
392 // handled above) are guaranteed to have a bit pattern of all zeros.
393 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
394 Align.getQuantity());
395}
396
Anders Carlsson27da15b2010-01-01 20:29:01 +0000397void
John McCall7a626f62010-09-15 10:14:12 +0000398CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
399 AggValueSlot Dest) {
400 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000401 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000402
403 // If we require zero initialization before (or instead of) calling the
404 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000405 // constructor, emit the zero initialization now, unless destination is
406 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000407 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
408 switch (E->getConstructionKind()) {
409 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000410 case CXXConstructExpr::CK_Complete:
411 EmitNullInitialization(Dest.getAddr(), E->getType());
412 break;
413 case CXXConstructExpr::CK_VirtualBase:
414 case CXXConstructExpr::CK_NonVirtualBase:
415 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
416 break;
417 }
418 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000419
420 // If this is a call to a trivial default constructor, do nothing.
421 if (CD->isTrivial() && CD->isDefaultConstructor())
422 return;
423
John McCall8ea46b62010-09-18 00:58:34 +0000424 // Elide the constructor if we're constructing from a temporary.
425 // The temporary check is required because Sema sets this on NRVO
426 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000427 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000428 assert(getContext().hasSameUnqualifiedType(E->getType(),
429 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000430 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
431 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000432 return;
433 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000434 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000435
John McCallf677a8e2011-07-13 06:10:41 +0000436 if (const ConstantArrayType *arrayType
437 = getContext().getAsConstantArrayType(E->getType())) {
438 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000439 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000440 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000441 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000442 bool ForVirtualBase = false;
443
444 switch (E->getConstructionKind()) {
445 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000446 // We should be emitting a constructor; GlobalDecl will assert this
447 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000448 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000449
Alexis Hunt271c3682011-05-03 20:19:28 +0000450 case CXXConstructExpr::CK_Complete:
451 Type = Ctor_Complete;
452 break;
453
454 case CXXConstructExpr::CK_VirtualBase:
455 ForVirtualBase = true;
456 // fall-through
457
458 case CXXConstructExpr::CK_NonVirtualBase:
459 Type = Ctor_Base;
460 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000461
Anders Carlsson27da15b2010-01-01 20:29:01 +0000462 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000463 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000464 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000465 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000466}
467
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000468void
469CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
470 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000471 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000472 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000473 Exp = E->getSubExpr();
474 assert(isa<CXXConstructExpr>(Exp) &&
475 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
476 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
477 const CXXConstructorDecl *CD = E->getConstructor();
478 RunCleanupsScope Scope(*this);
479
480 // If we require zero initialization before (or instead of) calling the
481 // constructor, as can be the case with a non-user-provided default
482 // constructor, emit the zero initialization now.
483 // FIXME. Do I still need this for a copy ctor synthesis?
484 if (E->requiresZeroInitialization())
485 EmitNullInitialization(Dest, E->getType());
486
Chandler Carruth99da11c2010-11-15 13:54:43 +0000487 assert(!getContext().getAsConstantArrayType(E->getType())
488 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000489 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
490 E->arg_begin(), E->arg_end());
491}
492
John McCall8ed55a52010-09-02 09:58:18 +0000493static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
494 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000495 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000496 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000497
John McCall7ec4b432011-05-16 01:05:12 +0000498 // No cookie is required if the operator new[] being used is the
499 // reserved placement operator new[].
500 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000501 return CharUnits::Zero();
502
John McCall284c48f2011-01-27 09:37:56 +0000503 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000504}
505
John McCall036f2f62011-05-15 07:14:44 +0000506static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
507 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000508 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000509 llvm::Value *&numElements,
510 llvm::Value *&sizeWithoutCookie) {
511 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000512
John McCall036f2f62011-05-15 07:14:44 +0000513 if (!e->isArray()) {
514 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
515 sizeWithoutCookie
516 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
517 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000518 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000519
John McCall036f2f62011-05-15 07:14:44 +0000520 // The width of size_t.
521 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
522
John McCall8ed55a52010-09-02 09:58:18 +0000523 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000524 llvm::APInt cookieSize(sizeWidth,
525 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000526
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000527 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000528 // We multiply the size of all dimensions for NumElements.
529 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000530 numElements = CGF.EmitScalarExpr(e->getArraySize());
531 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000532
John McCall036f2f62011-05-15 07:14:44 +0000533 // The number of elements can be have an arbitrary integer type;
534 // essentially, we need to multiply it by a constant factor, add a
535 // cookie size, and verify that the result is representable as a
536 // size_t. That's just a gloss, though, and it's wrong in one
537 // important way: if the count is negative, it's an error even if
538 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000539 bool isSigned
540 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000541 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000542 = cast<llvm::IntegerType>(numElements->getType());
543 unsigned numElementsWidth = numElementsType->getBitWidth();
544
545 // Compute the constant factor.
546 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000547 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000548 = CGF.getContext().getAsConstantArrayType(type)) {
549 type = CAT->getElementType();
550 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000551 }
552
John McCall036f2f62011-05-15 07:14:44 +0000553 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
554 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
555 typeSizeMultiplier *= arraySizeMultiplier;
556
557 // This will be a size_t.
558 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000559
Chris Lattner32ac5832010-07-20 21:55:52 +0000560 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
561 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000562 if (llvm::ConstantInt *numElementsC =
563 dyn_cast<llvm::ConstantInt>(numElements)) {
564 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000565
John McCall036f2f62011-05-15 07:14:44 +0000566 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000567
John McCall036f2f62011-05-15 07:14:44 +0000568 // If 'count' was a negative number, it's an overflow.
569 if (isSigned && count.isNegative())
570 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000571
John McCall036f2f62011-05-15 07:14:44 +0000572 // We want to do all this arithmetic in size_t. If numElements is
573 // wider than that, check whether it's already too big, and if so,
574 // overflow.
575 else if (numElementsWidth > sizeWidth &&
576 numElementsWidth - sizeWidth > count.countLeadingZeros())
577 hasAnyOverflow = true;
578
579 // Okay, compute a count at the right width.
580 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
581
Sebastian Redlf862eb62012-02-22 17:37:52 +0000582 // If there is a brace-initializer, we cannot allocate fewer elements than
583 // there are initializers. If we do, that's treated like an overflow.
584 if (adjustedCount.ult(minElements))
585 hasAnyOverflow = true;
586
John McCall036f2f62011-05-15 07:14:44 +0000587 // Scale numElements by that. This might overflow, but we don't
588 // care because it only overflows if allocationSize does, too, and
589 // if that overflows then we shouldn't use this.
590 numElements = llvm::ConstantInt::get(CGF.SizeTy,
591 adjustedCount * arraySizeMultiplier);
592
593 // Compute the size before cookie, and track whether it overflowed.
594 bool overflow;
595 llvm::APInt allocationSize
596 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
597 hasAnyOverflow |= overflow;
598
599 // Add in the cookie, and check whether it's overflowed.
600 if (cookieSize != 0) {
601 // Save the current size without a cookie. This shouldn't be
602 // used if there was overflow.
603 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
604
605 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
606 hasAnyOverflow |= overflow;
607 }
608
609 // On overflow, produce a -1 so operator new will fail.
610 if (hasAnyOverflow) {
611 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
612 } else {
613 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
614 }
615
616 // Otherwise, we might need to use the overflow intrinsics.
617 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000618 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000619 // 1) if isSigned, we need to check whether numElements is negative;
620 // 2) if numElementsWidth > sizeWidth, we need to check whether
621 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000622 // 3) if minElements > 0, we need to check whether numElements is smaller
623 // than that.
624 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000625 // sizeWithoutCookie := numElements * typeSizeMultiplier
626 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000627 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000628 // size := sizeWithoutCookie + cookieSize
629 // and check whether it overflows.
630
631 llvm::Value *hasOverflow = 0;
632
633 // If numElementsWidth > sizeWidth, then one way or another, we're
634 // going to have to do a comparison for (2), and this happens to
635 // take care of (1), too.
636 if (numElementsWidth > sizeWidth) {
637 llvm::APInt threshold(numElementsWidth, 1);
638 threshold <<= sizeWidth;
639
640 llvm::Value *thresholdV
641 = llvm::ConstantInt::get(numElementsType, threshold);
642
643 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
644 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
645
646 // Otherwise, if we're signed, we want to sext up to size_t.
647 } else if (isSigned) {
648 if (numElementsWidth < sizeWidth)
649 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
650
651 // If there's a non-1 type size multiplier, then we can do the
652 // signedness check at the same time as we do the multiply
653 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000654 // unsigned overflow. Otherwise, we have to do it here. But at least
655 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000656 if (typeSizeMultiplier == 1)
657 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000658 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000659
660 // Otherwise, zext up to size_t if necessary.
661 } else if (numElementsWidth < sizeWidth) {
662 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
663 }
664
665 assert(numElements->getType() == CGF.SizeTy);
666
Sebastian Redlf862eb62012-02-22 17:37:52 +0000667 if (minElements) {
668 // Don't allow allocation of fewer elements than we have initializers.
669 if (!hasOverflow) {
670 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
671 llvm::ConstantInt::get(CGF.SizeTy, minElements));
672 } else if (numElementsWidth > sizeWidth) {
673 // The other existing overflow subsumes this check.
674 // We do an unsigned comparison, since any signed value < -1 is
675 // taken care of either above or below.
676 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
677 CGF.Builder.CreateICmpULT(numElements,
678 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
679 }
680 }
681
John McCall036f2f62011-05-15 07:14:44 +0000682 size = numElements;
683
684 // Multiply by the type size if necessary. This multiplier
685 // includes all the factors for nested arrays.
686 //
687 // This step also causes numElements to be scaled up by the
688 // nested-array factor if necessary. Overflow on this computation
689 // can be ignored because the result shouldn't be used if
690 // allocation fails.
691 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000692 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000693 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000694
695 llvm::Value *tsmV =
696 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
697 llvm::Value *result =
698 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
699
700 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
701 if (hasOverflow)
702 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
703 else
704 hasOverflow = overflowed;
705
706 size = CGF.Builder.CreateExtractValue(result, 0);
707
708 // Also scale up numElements by the array size multiplier.
709 if (arraySizeMultiplier != 1) {
710 // If the base element type size is 1, then we can re-use the
711 // multiply we just did.
712 if (typeSize.isOne()) {
713 assert(arraySizeMultiplier == typeSizeMultiplier);
714 numElements = size;
715
716 // Otherwise we need a separate multiply.
717 } else {
718 llvm::Value *asmV =
719 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
720 numElements = CGF.Builder.CreateMul(numElements, asmV);
721 }
722 }
723 } else {
724 // numElements doesn't need to be scaled.
725 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000726 }
727
John McCall036f2f62011-05-15 07:14:44 +0000728 // Add in the cookie size if necessary.
729 if (cookieSize != 0) {
730 sizeWithoutCookie = size;
731
John McCall036f2f62011-05-15 07:14:44 +0000732 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000733 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000734
735 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
736 llvm::Value *result =
737 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
738
739 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
740 if (hasOverflow)
741 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
742 else
743 hasOverflow = overflowed;
744
745 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000746 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000747
John McCall036f2f62011-05-15 07:14:44 +0000748 // If we had any possibility of dynamic overflow, make a select to
749 // overwrite 'size' with an all-ones value, which should cause
750 // operator new to throw.
751 if (hasOverflow)
752 size = CGF.Builder.CreateSelect(hasOverflow,
753 llvm::Constant::getAllOnesValue(CGF.SizeTy),
754 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000755 }
John McCall8ed55a52010-09-02 09:58:18 +0000756
John McCall036f2f62011-05-15 07:14:44 +0000757 if (cookieSize == 0)
758 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000759 else
John McCall036f2f62011-05-15 07:14:44 +0000760 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000761
John McCall036f2f62011-05-15 07:14:44 +0000762 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000763}
764
Sebastian Redlf862eb62012-02-22 17:37:52 +0000765static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
766 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000767
Eli Friedman38cd36d2011-12-03 02:13:40 +0000768 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000769 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000770 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000771 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000772 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000773 else if (AllocType->isAnyComplexType())
774 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
775 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000776 else {
777 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000778 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000779 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000780 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000781 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000782 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000783
784 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000785 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000786}
787
788void
789CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000790 QualType elementType,
791 llvm::Value *beginPtr,
792 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000793 if (!E->hasInitializer())
794 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000795
Sebastian Redlf862eb62012-02-22 17:37:52 +0000796 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000797 // Find the end of the array, hoisted out of the loop.
798 llvm::Value *endPtr =
799 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
800
Sebastian Redlf862eb62012-02-22 17:37:52 +0000801 unsigned initializerElements = 0;
802
803 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000804 llvm::AllocaInst *endOfInit = 0;
805 QualType::DestructionKind dtorKind = elementType.isDestructedType();
806 EHScopeStack::stable_iterator cleanup;
807 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000808 // If the initializer is an initializer list, first do the explicit elements.
809 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
810 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000811
812 // Enter a partial-destruction cleanup if necessary.
813 if (needsEHCleanup(dtorKind)) {
814 // In principle we could tell the cleanup where we are more
815 // directly, but the control flow can get so varied here that it
816 // would actually be quite complex. Therefore we go through an
817 // alloca.
818 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
819 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
820 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
821 getDestroyer(dtorKind));
822 cleanup = EHStack.stable_begin();
823 }
824
Sebastian Redlf862eb62012-02-22 17:37:52 +0000825 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000826 // Tell the cleanup that it needs to destroy up to this
827 // element. TODO: some of these stores can be trivially
828 // observed to be unnecessary.
829 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000830 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
831 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
832 }
833
834 // The remaining elements are filled with the array filler expression.
835 Init = ILE->getArrayFiller();
836 }
837
John McCall99210dc2011-09-15 06:49:18 +0000838 // Create the continuation block.
839 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
840
Sebastian Redlf862eb62012-02-22 17:37:52 +0000841 // If the number of elements isn't constant, we have to now check if there is
842 // anything left to initialize.
843 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
844 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000845 if (constNum->getZExtValue() <= initializerElements) {
846 // If there was a cleanup, deactivate it.
847 if (cleanupDominator)
848 DeactivateCleanupBlock(cleanup, cleanupDominator);;
849 return;
850 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000851 } else {
John McCall99210dc2011-09-15 06:49:18 +0000852 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000853 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000854 "array.isempty");
855 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
856 EmitBlock(nonEmptyBB);
857 }
858
859 // Enter the loop.
860 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
861 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
862
863 EmitBlock(loopBB);
864
865 // Set up the current-element phi.
866 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000867 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
868 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000869
Chad Rosierf62290a2012-02-24 00:13:55 +0000870 // Store the new cleanup position for irregular cleanups.
871 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
872
John McCall99210dc2011-09-15 06:49:18 +0000873 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000874 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000875 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
876 getDestroyer(dtorKind));
877 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000878 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000879 }
880
881 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000882 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000883
884 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000885 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000886 DeactivateCleanupBlock(cleanup, cleanupDominator);
887 cleanupDominator->eraseFromParent();
888 }
John McCall99210dc2011-09-15 06:49:18 +0000889
890 // Advance to the next element.
891 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
892
893 // Check whether we've gotten to the end of the array and, if so,
894 // exit the loop.
895 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
896 Builder.CreateCondBr(isEnd, contBB, loopBB);
897 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
898
899 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000900}
901
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000902static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
903 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000904 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000905 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000906 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000907 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000908}
909
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000910static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000911 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000912 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000913 llvm::Value *NumElements,
914 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000915 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000916 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000917 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
918 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000919 bool RequiresZeroInitialization = false;
Douglas Gregord1531032012-02-23 17:07:43 +0000920 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000921 // If new expression did not specify value-initialization, then there
922 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000923 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000924 return;
925
John McCall99210dc2011-09-15 06:49:18 +0000926 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000927 // Optimization: since zero initialization will just set the memory
928 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000929 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000930 return;
931 }
932
933 RequiresZeroInitialization = true;
934 }
John McCallf677a8e2011-07-13 06:10:41 +0000935
Sebastian Redl6047f072012-02-16 12:22:20 +0000936 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
937 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000938 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000939 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000940 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000941 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000942 // Optimization: since zero initialization will just set the memory
943 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000944 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
945 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000946 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000947 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
948 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000949 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000950
Sebastian Redl6047f072012-02-16 12:22:20 +0000951 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000952 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000953
Sebastian Redlf862eb62012-02-22 17:37:52 +0000954 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000955}
956
John McCall824c2f52010-09-14 07:57:04 +0000957namespace {
958 /// A cleanup to call the given 'operator delete' function upon
959 /// abnormal exit from a new expression.
960 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
961 size_t NumPlacementArgs;
962 const FunctionDecl *OperatorDelete;
963 llvm::Value *Ptr;
964 llvm::Value *AllocSize;
965
966 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
967
968 public:
969 static size_t getExtraSize(size_t NumPlacementArgs) {
970 return NumPlacementArgs * sizeof(RValue);
971 }
972
973 CallDeleteDuringNew(size_t NumPlacementArgs,
974 const FunctionDecl *OperatorDelete,
975 llvm::Value *Ptr,
976 llvm::Value *AllocSize)
977 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
978 Ptr(Ptr), AllocSize(AllocSize) {}
979
980 void setPlacementArg(unsigned I, RValue Arg) {
981 assert(I < NumPlacementArgs && "index out of range");
982 getPlacementArgs()[I] = Arg;
983 }
984
John McCall30317fd2011-07-12 20:27:29 +0000985 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +0000986 const FunctionProtoType *FPT
987 = OperatorDelete->getType()->getAs<FunctionProtoType>();
988 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000989 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000990
991 CallArgList DeleteArgs;
992
993 // The first argument is always a void*.
994 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000995 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000996
997 // A member 'operator delete' can take an extra 'size_t' argument.
998 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000999 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001000
1001 // Pass the rest of the arguments, which must match exactly.
1002 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001003 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001004
1005 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001006 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +00001007 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1008 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1009 }
1010 };
John McCall7f9c92a2010-09-17 00:50:28 +00001011
1012 /// A cleanup to call the given 'operator delete' function upon
1013 /// abnormal exit from a new expression when the new expression is
1014 /// conditional.
1015 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1016 size_t NumPlacementArgs;
1017 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001018 DominatingValue<RValue>::saved_type Ptr;
1019 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001020
John McCallcb5f77f2011-01-28 10:53:53 +00001021 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1022 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001023 }
1024
1025 public:
1026 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001027 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001028 }
1029
1030 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1031 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001032 DominatingValue<RValue>::saved_type Ptr,
1033 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001034 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1035 Ptr(Ptr), AllocSize(AllocSize) {}
1036
John McCallcb5f77f2011-01-28 10:53:53 +00001037 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001038 assert(I < NumPlacementArgs && "index out of range");
1039 getPlacementArgs()[I] = Arg;
1040 }
1041
John McCall30317fd2011-07-12 20:27:29 +00001042 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001043 const FunctionProtoType *FPT
1044 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1045 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1046 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1047
1048 CallArgList DeleteArgs;
1049
1050 // The first argument is always a void*.
1051 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001052 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001053
1054 // A member 'operator delete' can take an extra 'size_t' argument.
1055 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001056 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001057 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001058 }
1059
1060 // Pass the rest of the arguments, which must match exactly.
1061 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001062 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001063 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001064 }
1065
1066 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001067 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001068 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1069 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1070 }
1071 };
1072}
1073
1074/// Enter a cleanup to call 'operator delete' if the initializer in a
1075/// new-expression throws.
1076static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1077 const CXXNewExpr *E,
1078 llvm::Value *NewPtr,
1079 llvm::Value *AllocSize,
1080 const CallArgList &NewArgs) {
1081 // If we're not inside a conditional branch, then the cleanup will
1082 // dominate and we can do the easier (and more efficient) thing.
1083 if (!CGF.isInConditionalBranch()) {
1084 CallDeleteDuringNew *Cleanup = CGF.EHStack
1085 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1086 E->getNumPlacementArgs(),
1087 E->getOperatorDelete(),
1088 NewPtr, AllocSize);
1089 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001090 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001091
1092 return;
1093 }
1094
1095 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001096 DominatingValue<RValue>::saved_type SavedNewPtr =
1097 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1098 DominatingValue<RValue>::saved_type SavedAllocSize =
1099 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001100
1101 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001102 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001103 E->getNumPlacementArgs(),
1104 E->getOperatorDelete(),
1105 SavedNewPtr,
1106 SavedAllocSize);
1107 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001108 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001109 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001110
John McCallf4beacd2011-11-10 10:43:54 +00001111 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001112}
1113
Anders Carlssoncc52f652009-09-22 22:53:17 +00001114llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001115 // The element type being allocated.
1116 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001117
John McCall75f94982011-03-07 03:12:35 +00001118 // 1. Build a call to the allocation function.
1119 FunctionDecl *allocator = E->getOperatorNew();
1120 const FunctionProtoType *allocatorType =
1121 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001122
John McCall75f94982011-03-07 03:12:35 +00001123 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001124
1125 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001126 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001127
Sebastian Redlf862eb62012-02-22 17:37:52 +00001128 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1129 unsigned minElements = 0;
1130 if (E->isArray() && E->hasInitializer()) {
1131 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1132 minElements = ILE->getNumInits();
1133 }
1134
John McCall75f94982011-03-07 03:12:35 +00001135 llvm::Value *numElements = 0;
1136 llvm::Value *allocSizeWithoutCookie = 0;
1137 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001138 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1139 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001140
Eli Friedman43dca6a2011-05-02 17:57:46 +00001141 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001142
1143 // Emit the rest of the arguments.
1144 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001145 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001146
1147 // First, use the types from the function type.
1148 // We start at 1 here because the first argument (the allocation size)
1149 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001150 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1151 ++i, ++placementArg) {
1152 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001153
John McCall75f94982011-03-07 03:12:35 +00001154 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1155 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001156 "type mismatch in call argument!");
1157
John McCall32ea9692011-03-11 20:59:21 +00001158 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001159 }
1160
1161 // Either we've emitted all the call args, or we have a call to a
1162 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001163 assert((placementArg == E->placement_arg_end() ||
1164 allocatorType->isVariadic()) &&
1165 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001166
1167 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001168 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1169 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001170 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001171 }
1172
John McCall7ec4b432011-05-16 01:05:12 +00001173 // Emit the allocation call. If the allocator is a global placement
1174 // operator, just "inline" it directly.
1175 RValue RV;
1176 if (allocator->isReservedGlobalPlacementOperator()) {
1177 assert(allocatorArgs.size() == 2);
1178 RV = allocatorArgs[1].RV;
1179 // TODO: kill any unnecessary computations done for the size
1180 // argument.
1181 } else {
John McCalla729c622012-02-17 03:33:10 +00001182 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1183 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001184 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1185 allocatorArgs, allocator);
1186 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001187
John McCall75f94982011-03-07 03:12:35 +00001188 // Emit a null check on the allocation result if the allocation
1189 // function is allowed to return null (because it has a non-throwing
1190 // exception spec; for this part, we inline
1191 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1192 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001193 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001194 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001195
John McCall75f94982011-03-07 03:12:35 +00001196 llvm::BasicBlock *nullCheckBB = 0;
1197 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001198
John McCall75f94982011-03-07 03:12:35 +00001199 llvm::Value *allocation = RV.getScalarVal();
1200 unsigned AS =
1201 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001202
John McCallf7dcf322011-03-07 01:52:56 +00001203 // The null-check means that the initializer is conditionally
1204 // evaluated.
1205 ConditionalEvaluation conditional(*this);
1206
John McCall75f94982011-03-07 03:12:35 +00001207 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001208 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001209
1210 nullCheckBB = Builder.GetInsertBlock();
1211 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1212 contBB = createBasicBlock("new.cont");
1213
1214 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1215 Builder.CreateCondBr(isNull, contBB, notNullBB);
1216 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001217 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001218
John McCall824c2f52010-09-14 07:57:04 +00001219 // If there's an operator delete, enter a cleanup to call it if an
1220 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001221 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001222 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001223 if (E->getOperatorDelete() &&
1224 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001225 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1226 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001227 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001228 }
1229
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001230 assert((allocSize == allocSizeWithoutCookie) ==
1231 CalculateCookiePadding(*this, E).isZero());
1232 if (allocSize != allocSizeWithoutCookie) {
1233 assert(E->isArray());
1234 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1235 numElements,
1236 E, allocType);
1237 }
1238
Chris Lattner2192fe52011-07-18 04:24:23 +00001239 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001240 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1241 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001242
John McCall99210dc2011-09-15 06:49:18 +00001243 EmitNewInitializer(*this, E, allocType, result, numElements,
1244 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001245 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001246 // NewPtr is a pointer to the base element type. If we're
1247 // allocating an array of arrays, we'll need to cast back to the
1248 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001249 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001250 if (result->getType() != resultType)
1251 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001252 }
John McCall824c2f52010-09-14 07:57:04 +00001253
1254 // Deactivate the 'operator delete' cleanup if we finished
1255 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001256 if (operatorDeleteCleanup.isValid()) {
1257 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1258 cleanupDominator->eraseFromParent();
1259 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001260
John McCall75f94982011-03-07 03:12:35 +00001261 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001262 conditional.end(*this);
1263
John McCall75f94982011-03-07 03:12:35 +00001264 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1265 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001266
Jay Foad20c0f022011-03-30 11:28:58 +00001267 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001268 PHI->addIncoming(result, notNullBB);
1269 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1270 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001271
John McCall75f94982011-03-07 03:12:35 +00001272 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001273 }
John McCall8ed55a52010-09-02 09:58:18 +00001274
John McCall75f94982011-03-07 03:12:35 +00001275 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001276}
1277
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001278void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1279 llvm::Value *Ptr,
1280 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001281 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1282
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001283 const FunctionProtoType *DeleteFTy =
1284 DeleteFD->getType()->getAs<FunctionProtoType>();
1285
1286 CallArgList DeleteArgs;
1287
Anders Carlsson21122cf2009-12-13 20:04:38 +00001288 // Check if we need to pass the size to the delete operator.
1289 llvm::Value *Size = 0;
1290 QualType SizeTy;
1291 if (DeleteFTy->getNumArgs() == 2) {
1292 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001293 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1294 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1295 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001296 }
1297
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001298 QualType ArgTy = DeleteFTy->getArgType(0);
1299 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001300 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001301
Anders Carlsson21122cf2009-12-13 20:04:38 +00001302 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001303 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001304
1305 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001306 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001307 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001308 DeleteArgs, DeleteFD);
1309}
1310
John McCall8ed55a52010-09-02 09:58:18 +00001311namespace {
1312 /// Calls the given 'operator delete' on a single object.
1313 struct CallObjectDelete : EHScopeStack::Cleanup {
1314 llvm::Value *Ptr;
1315 const FunctionDecl *OperatorDelete;
1316 QualType ElementType;
1317
1318 CallObjectDelete(llvm::Value *Ptr,
1319 const FunctionDecl *OperatorDelete,
1320 QualType ElementType)
1321 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1322
John McCall30317fd2011-07-12 20:27:29 +00001323 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001324 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1325 }
1326 };
1327}
1328
1329/// Emit the code for deleting a single object.
1330static void EmitObjectDelete(CodeGenFunction &CGF,
1331 const FunctionDecl *OperatorDelete,
1332 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001333 QualType ElementType,
1334 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001335 // Find the destructor for the type, if applicable. If the
1336 // destructor is virtual, we'll just emit the vcall and return.
1337 const CXXDestructorDecl *Dtor = 0;
1338 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1339 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001340 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001341 Dtor = RD->getDestructor();
1342
1343 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001344 if (UseGlobalDelete) {
1345 // If we're supposed to call the global delete, make sure we do so
1346 // even if the destructor throws.
1347 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1348 Ptr, OperatorDelete,
1349 ElementType);
1350 }
1351
Chris Lattner2192fe52011-07-18 04:24:23 +00001352 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001353 CGF.getTypes().GetFunctionType(
1354 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001355
1356 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001357 = CGF.BuildVirtualCall(Dtor,
1358 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1359 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001360 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1361 0, 0);
1362
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001363 if (UseGlobalDelete) {
1364 CGF.PopCleanupBlock();
1365 }
1366
John McCall8ed55a52010-09-02 09:58:18 +00001367 return;
1368 }
1369 }
1370 }
1371
1372 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001373 // This doesn't have to a conditional cleanup because we're going
1374 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001375 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1376 Ptr, OperatorDelete, ElementType);
1377
1378 if (Dtor)
1379 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1380 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001381 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001382 ElementType->isObjCLifetimeType()) {
1383 switch (ElementType.getObjCLifetime()) {
1384 case Qualifiers::OCL_None:
1385 case Qualifiers::OCL_ExplicitNone:
1386 case Qualifiers::OCL_Autoreleasing:
1387 break;
John McCall8ed55a52010-09-02 09:58:18 +00001388
John McCall31168b02011-06-15 23:02:42 +00001389 case Qualifiers::OCL_Strong: {
1390 // Load the pointer value.
1391 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1392 ElementType.isVolatileQualified());
1393
1394 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1395 break;
1396 }
1397
1398 case Qualifiers::OCL_Weak:
1399 CGF.EmitARCDestroyWeak(Ptr);
1400 break;
1401 }
1402 }
1403
John McCall8ed55a52010-09-02 09:58:18 +00001404 CGF.PopCleanupBlock();
1405}
1406
1407namespace {
1408 /// Calls the given 'operator delete' on an array of objects.
1409 struct CallArrayDelete : EHScopeStack::Cleanup {
1410 llvm::Value *Ptr;
1411 const FunctionDecl *OperatorDelete;
1412 llvm::Value *NumElements;
1413 QualType ElementType;
1414 CharUnits CookieSize;
1415
1416 CallArrayDelete(llvm::Value *Ptr,
1417 const FunctionDecl *OperatorDelete,
1418 llvm::Value *NumElements,
1419 QualType ElementType,
1420 CharUnits CookieSize)
1421 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1422 ElementType(ElementType), CookieSize(CookieSize) {}
1423
John McCall30317fd2011-07-12 20:27:29 +00001424 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001425 const FunctionProtoType *DeleteFTy =
1426 OperatorDelete->getType()->getAs<FunctionProtoType>();
1427 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1428
1429 CallArgList Args;
1430
1431 // Pass the pointer as the first argument.
1432 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1433 llvm::Value *DeletePtr
1434 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001435 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001436
1437 // Pass the original requested size as the second argument.
1438 if (DeleteFTy->getNumArgs() == 2) {
1439 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001440 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001441 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1442
1443 CharUnits ElementTypeSize =
1444 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1445
1446 // The size of an element, multiplied by the number of elements.
1447 llvm::Value *Size
1448 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1449 Size = CGF.Builder.CreateMul(Size, NumElements);
1450
1451 // Plus the size of the cookie if applicable.
1452 if (!CookieSize.isZero()) {
1453 llvm::Value *CookieSizeV
1454 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1455 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1456 }
1457
Eli Friedman43dca6a2011-05-02 17:57:46 +00001458 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001459 }
1460
1461 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001462 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001463 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1464 ReturnValueSlot(), Args, OperatorDelete);
1465 }
1466 };
1467}
1468
1469/// Emit the code for deleting an array of objects.
1470static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001471 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001472 llvm::Value *deletedPtr,
1473 QualType elementType) {
1474 llvm::Value *numElements = 0;
1475 llvm::Value *allocatedPtr = 0;
1476 CharUnits cookieSize;
1477 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1478 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001479
John McCallca2c56f2011-07-13 01:41:37 +00001480 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001481
1482 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001483 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001484 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001485 allocatedPtr, operatorDelete,
1486 numElements, elementType,
1487 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001488
John McCallca2c56f2011-07-13 01:41:37 +00001489 // Destroy the elements.
1490 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1491 assert(numElements && "no element count for a type with a destructor!");
1492
John McCallca2c56f2011-07-13 01:41:37 +00001493 llvm::Value *arrayEnd =
1494 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001495
1496 // Note that it is legal to allocate a zero-length array, and we
1497 // can never fold the check away because the length should always
1498 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001499 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1500 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001501 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001502 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001503 }
1504
John McCallca2c56f2011-07-13 01:41:37 +00001505 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001506 CGF.PopCleanupBlock();
1507}
1508
Anders Carlssoncc52f652009-09-22 22:53:17 +00001509void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001510
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001511 // Get at the argument before we performed the implicit conversion
1512 // to void*.
1513 const Expr *Arg = E->getArgument();
1514 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001515 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001516 ICE->getType()->isVoidPointerType())
1517 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001518 else
1519 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001520 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001521
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001522 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001523
1524 // Null check the pointer.
1525 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1526 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1527
Anders Carlsson98981b12011-04-11 00:30:07 +00001528 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001529
1530 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1531 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001532
John McCall8ed55a52010-09-02 09:58:18 +00001533 // We might be deleting a pointer to array. If so, GEP down to the
1534 // first non-array element.
1535 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1536 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1537 if (DeleteTy->isConstantArrayType()) {
1538 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001539 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001540
1541 GEP.push_back(Zero); // point at the outermost array
1542
1543 // For each layer of array type we're pointing at:
1544 while (const ConstantArrayType *Arr
1545 = getContext().getAsConstantArrayType(DeleteTy)) {
1546 // 1. Unpeel the array type.
1547 DeleteTy = Arr->getElementType();
1548
1549 // 2. GEP to the first element of the array.
1550 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001551 }
John McCall8ed55a52010-09-02 09:58:18 +00001552
Jay Foad040dd822011-07-22 08:16:57 +00001553 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001554 }
1555
Douglas Gregor04f36212010-09-02 17:38:50 +00001556 assert(ConvertTypeForMem(DeleteTy) ==
1557 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001558
1559 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001560 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001561 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001562 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1563 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001564 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001565
Anders Carlssoncc52f652009-09-22 22:53:17 +00001566 EmitBlock(DeleteEnd);
1567}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001568
Anders Carlsson0c633502011-04-11 14:13:40 +00001569static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1570 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001571 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001572
1573 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1574}
1575
1576static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001577 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001578 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001579 CGF.Builder.CreateUnreachable();
1580}
1581
Anders Carlsson940f02d2011-04-18 00:57:03 +00001582static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1583 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001584 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001585 // Get the vtable pointer.
1586 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1587
1588 // C++ [expr.typeid]p2:
1589 // If the glvalue expression is obtained by applying the unary * operator to
1590 // a pointer and the pointer is a null pointer value, the typeid expression
1591 // throws the std::bad_typeid exception.
1592 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1593 if (UO->getOpcode() == UO_Deref) {
1594 llvm::BasicBlock *BadTypeidBlock =
1595 CGF.createBasicBlock("typeid.bad_typeid");
1596 llvm::BasicBlock *EndBlock =
1597 CGF.createBasicBlock("typeid.end");
1598
1599 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1600 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1601
1602 CGF.EmitBlock(BadTypeidBlock);
1603 EmitBadTypeidCall(CGF);
1604 CGF.EmitBlock(EndBlock);
1605 }
1606 }
1607
1608 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1609 StdTypeInfoPtrTy->getPointerTo());
1610
1611 // Load the type info.
1612 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1613 return CGF.Builder.CreateLoad(Value);
1614}
1615
John McCalle4df6c82011-01-28 08:37:24 +00001616llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001617 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001618 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001619
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001620 if (E->isTypeOperand()) {
1621 llvm::Constant *TypeInfo =
1622 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001623 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001624 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001625
Anders Carlsson940f02d2011-04-18 00:57:03 +00001626 // C++ [expr.typeid]p2:
1627 // When typeid is applied to a glvalue expression whose type is a
1628 // polymorphic class type, the result refers to a std::type_info object
1629 // representing the type of the most derived object (that is, the dynamic
1630 // type) to which the glvalue refers.
1631 if (E->getExprOperand()->isGLValue()) {
1632 if (const RecordType *RT =
1633 E->getExprOperand()->getType()->getAs<RecordType>()) {
1634 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1635 if (RD->isPolymorphic())
1636 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1637 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001638 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001639 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001640
1641 QualType OperandTy = E->getExprOperand()->getType();
1642 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1643 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001644}
Mike Stump65511702009-11-16 06:50:58 +00001645
Anders Carlsson882d7902011-04-11 00:46:40 +00001646static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1647 // void *__dynamic_cast(const void *sub,
1648 // const abi::__class_type_info *src,
1649 // const abi::__class_type_info *dst,
1650 // std::ptrdiff_t src2dst_offset);
1651
Chris Lattnerece04092012-02-07 00:39:47 +00001652 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001653 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001654 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1655
Chris Lattnera5f58b02011-07-09 17:41:47 +00001656 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001657
Chris Lattner2192fe52011-07-18 04:24:23 +00001658 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001659 llvm::FunctionType::get(Int8PtrTy, Args, false);
1660
1661 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1662}
1663
1664static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1665 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001666 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001667 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1668}
1669
Anders Carlssonc1c99712011-04-11 01:45:29 +00001670static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001671 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001672 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001673 CGF.Builder.CreateUnreachable();
1674}
1675
Anders Carlsson882d7902011-04-11 00:46:40 +00001676static llvm::Value *
1677EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1678 QualType SrcTy, QualType DestTy,
1679 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001680 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001681 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001682 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001683
1684 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1685 if (PTy->getPointeeType()->isVoidType()) {
1686 // C++ [expr.dynamic.cast]p7:
1687 // If T is "pointer to cv void," then the result is a pointer to the
1688 // most derived object pointed to by v.
1689
1690 // Get the vtable pointer.
1691 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1692
1693 // Get the offset-to-top from the vtable.
1694 llvm::Value *OffsetToTop =
1695 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1696 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1697
1698 // Finally, add the offset to the pointer.
1699 Value = CGF.EmitCastToVoidPtr(Value);
1700 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1701
1702 return CGF.Builder.CreateBitCast(Value, DestLTy);
1703 }
1704 }
1705
1706 QualType SrcRecordTy;
1707 QualType DestRecordTy;
1708
1709 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1710 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1711 DestRecordTy = DestPTy->getPointeeType();
1712 } else {
1713 SrcRecordTy = SrcTy;
1714 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1715 }
1716
1717 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1718 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1719
1720 llvm::Value *SrcRTTI =
1721 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1722 llvm::Value *DestRTTI =
1723 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1724
1725 // FIXME: Actually compute a hint here.
1726 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1727
1728 // Emit the call to __dynamic_cast.
1729 Value = CGF.EmitCastToVoidPtr(Value);
1730 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1731 SrcRTTI, DestRTTI, OffsetHint);
1732 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1733
1734 /// C++ [expr.dynamic.cast]p9:
1735 /// A failed cast to reference type throws std::bad_cast
1736 if (DestTy->isReferenceType()) {
1737 llvm::BasicBlock *BadCastBlock =
1738 CGF.createBasicBlock("dynamic_cast.bad_cast");
1739
1740 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1741 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1742
1743 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001744 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001745 }
1746
1747 return Value;
1748}
1749
Anders Carlssonc1c99712011-04-11 01:45:29 +00001750static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1751 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001752 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001753 if (DestTy->isPointerType())
1754 return llvm::Constant::getNullValue(DestLTy);
1755
1756 /// C++ [expr.dynamic.cast]p9:
1757 /// A failed cast to reference type throws std::bad_cast
1758 EmitBadCastCall(CGF);
1759
1760 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1761 return llvm::UndefValue::get(DestLTy);
1762}
1763
Anders Carlsson882d7902011-04-11 00:46:40 +00001764llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001765 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001766 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001767
Anders Carlssonc1c99712011-04-11 01:45:29 +00001768 if (DCE->isAlwaysNull())
1769 return EmitDynamicCastToNull(*this, DestTy);
1770
1771 QualType SrcTy = DCE->getSubExpr()->getType();
1772
Anders Carlsson882d7902011-04-11 00:46:40 +00001773 // C++ [expr.dynamic.cast]p4:
1774 // If the value of v is a null pointer value in the pointer case, the result
1775 // is the null pointer value of type T.
1776 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001777
Anders Carlsson882d7902011-04-11 00:46:40 +00001778 llvm::BasicBlock *CastNull = 0;
1779 llvm::BasicBlock *CastNotNull = 0;
1780 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001781
Anders Carlsson882d7902011-04-11 00:46:40 +00001782 if (ShouldNullCheckSrcValue) {
1783 CastNull = createBasicBlock("dynamic_cast.null");
1784 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1785
1786 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1787 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1788 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001789 }
1790
Anders Carlsson882d7902011-04-11 00:46:40 +00001791 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1792
1793 if (ShouldNullCheckSrcValue) {
1794 EmitBranch(CastEnd);
1795
1796 EmitBlock(CastNull);
1797 EmitBranch(CastEnd);
1798 }
1799
1800 EmitBlock(CastEnd);
1801
1802 if (ShouldNullCheckSrcValue) {
1803 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1804 PHI->addIncoming(Value, CastNotNull);
1805 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1806
1807 Value = PHI;
1808 }
1809
1810 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001811}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001812
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001813void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001814 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001815 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1816 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001817
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001818 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1819 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1820 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001821 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001822 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001823
David Blaikie40ed2972012-06-06 20:45:41 +00001824 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001825 ArrayRef<VarDecl *> ArrayIndexes;
1826 if (CurField->getType()->isArrayType())
1827 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001828 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001829 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001830}