blob: 30324b97ef16723dcd0f5b76810a6f2278e2146d [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.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000176 if (ME->isArrow())
177 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000178 else
179 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000180
John McCall0d635f52010-09-03 01:26:39 +0000181 if (MD->isTrivial()) {
182 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000183 if (isa<CXXConstructorDecl>(MD) &&
184 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
185 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000186
Sebastian Redl22653ba2011-08-30 19:58:05 +0000187 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
188 // We don't like to generate the trivial copy/move assignment operator
189 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000190 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
191 EmitAggregateCopy(This, RHS, CE->getType());
192 return RValue::get(This);
193 }
194
195 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000196 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
197 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000198 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
199 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
200 CE->arg_begin(), CE->arg_end());
201 return RValue::get(This);
202 }
203 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000204 }
205
John McCall0d635f52010-09-03 01:26:39 +0000206 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000207 const CGFunctionInfo *FInfo = 0;
208 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000209 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
210 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000211 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000212 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
213 cast<CXXConstructorDecl>(MD),
214 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000215 else
John McCalla729c622012-02-17 03:33:10 +0000216 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000217
John McCalla729c622012-02-17 03:33:10 +0000218 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000219
Anders Carlsson27da15b2010-01-01 20:29:01 +0000220 // C++ [class.virtual]p12:
221 // Explicit qualification with the scope operator (5.1) suppresses the
222 // virtual call mechanism.
223 //
224 // We also don't emit a virtual call if the base expression has a record type
225 // because then we know what the type is.
Rafael Espindola49e860b2012-06-26 17:45:31 +0000226 const Expr *Base = ME->getBase();
227 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
228 && !canDevirtualizeMemberFunctionCalls(getContext(),
229 Base, MD);
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +0000230 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Rafael Espindola49e860b2012-06-26 17:45:31 +0000231
Anders Carlsson27da15b2010-01-01 20:29:01 +0000232 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000233 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
234 if (UseVirtualCall) {
235 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000236 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000237 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000238 MD->isVirtual() &&
239 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000240 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola727a7712012-06-26 19:18:25 +0000241 else if (ME->hasQualifier())
242 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000243 else {
244 const CXXMethodDecl *DM =
245 Dtor->getCorrespondingMethodInClass(MostDerivedClassDecl);
246 assert(DM);
247 const CXXDestructorDecl *DDtor = cast<CXXDestructorDecl>(DM);
248 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
249 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000250 }
Francois Pichet64225792011-01-18 05:04:39 +0000251 } else if (const CXXConstructorDecl *Ctor =
252 dyn_cast<CXXConstructorDecl>(MD)) {
253 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000254 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000255 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000257 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000258 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000259 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000260 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola727a7712012-06-26 19:18:25 +0000261 else if (ME->hasQualifier())
262 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000263 else {
264 const CXXMethodDecl *DerivedMethod =
265 MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
266 assert(DerivedMethod);
267 Callee = CGM.GetAddrOfFunction(DerivedMethod, Ty);
268 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000269 }
270
Anders Carlssone36a6b32010-01-02 01:01:18 +0000271 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000272 CE->arg_begin(), CE->arg_end());
273}
274
275RValue
276CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
277 ReturnValueSlot ReturnValue) {
278 const BinaryOperator *BO =
279 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
280 const Expr *BaseExpr = BO->getLHS();
281 const Expr *MemFnExpr = BO->getRHS();
282
283 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000284 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000285
Anders Carlsson27da15b2010-01-01 20:29:01 +0000286 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000287 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000288 const CXXRecordDecl *RD =
289 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
290
Anders Carlsson27da15b2010-01-01 20:29:01 +0000291 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000292 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293
294 // Emit the 'this' pointer.
295 llvm::Value *This;
296
John McCalle3027922010-08-25 11:45:40 +0000297 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 This = EmitScalarExpr(BaseExpr);
299 else
300 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000301
John McCall475999d2010-08-22 00:05:51 +0000302 // Ask the ABI to load the callee. Note that This is modified.
303 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000304 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305
Anders Carlsson27da15b2010-01-01 20:29:01 +0000306 CallArgList Args;
307
308 QualType ThisType =
309 getContext().getPointerType(getContext().getTagDeclType(RD));
310
311 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000312 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000313
314 // And the rest of the call args
315 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCalla729c622012-02-17 03:33:10 +0000316 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000317 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000318}
319
320RValue
321CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
322 const CXXMethodDecl *MD,
323 ReturnValueSlot ReturnValue) {
324 assert(MD->isInstance() &&
325 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000326 LValue LV = EmitLValue(E->getArg(0));
327 llvm::Value *This = LV.getAddress();
328
Douglas Gregor146b8e92011-09-06 16:26:56 +0000329 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
330 MD->isTrivial()) {
331 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
332 QualType Ty = E->getType();
333 EmitAggregateCopy(This, Src, Ty);
334 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000335 }
336
Anders Carlssonc36783e2011-05-08 20:32:23 +0000337 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000338 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000339 E->arg_begin() + 1, E->arg_end());
340}
341
Peter Collingbournefe883422011-10-06 18:29:37 +0000342RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
343 ReturnValueSlot ReturnValue) {
344 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
345}
346
Eli Friedmanfde961d2011-10-14 02:27:24 +0000347static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
348 llvm::Value *DestPtr,
349 const CXXRecordDecl *Base) {
350 if (Base->isEmpty())
351 return;
352
353 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
354
355 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
356 CharUnits Size = Layout.getNonVirtualSize();
357 CharUnits Align = Layout.getNonVirtualAlign();
358
359 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
360
361 // If the type contains a pointer to data member we can't memset it to zero.
362 // Instead, create a null constant and copy it to the destination.
363 // TODO: there are other patterns besides zero that we can usefully memset,
364 // like -1, which happens to be the pattern used by member-pointers.
365 // TODO: isZeroInitializable can be over-conservative in the case where a
366 // virtual base contains a member pointer.
367 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
368 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
369
370 llvm::GlobalVariable *NullVariable =
371 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
372 /*isConstant=*/true,
373 llvm::GlobalVariable::PrivateLinkage,
374 NullConstant, Twine());
375 NullVariable->setAlignment(Align.getQuantity());
376 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
377
378 // Get and call the appropriate llvm.memcpy overload.
379 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
380 return;
381 }
382
383 // Otherwise, just memset the whole thing to zero. This is legal
384 // because in LLVM, all default initializers (other than the ones we just
385 // handled above) are guaranteed to have a bit pattern of all zeros.
386 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
387 Align.getQuantity());
388}
389
Anders Carlsson27da15b2010-01-01 20:29:01 +0000390void
John McCall7a626f62010-09-15 10:14:12 +0000391CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
392 AggValueSlot Dest) {
393 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000394 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000395
396 // If we require zero initialization before (or instead of) calling the
397 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000398 // constructor, emit the zero initialization now, unless destination is
399 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000400 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
401 switch (E->getConstructionKind()) {
402 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000403 case CXXConstructExpr::CK_Complete:
404 EmitNullInitialization(Dest.getAddr(), E->getType());
405 break;
406 case CXXConstructExpr::CK_VirtualBase:
407 case CXXConstructExpr::CK_NonVirtualBase:
408 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
409 break;
410 }
411 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000412
413 // If this is a call to a trivial default constructor, do nothing.
414 if (CD->isTrivial() && CD->isDefaultConstructor())
415 return;
416
John McCall8ea46b62010-09-18 00:58:34 +0000417 // Elide the constructor if we're constructing from a temporary.
418 // The temporary check is required because Sema sets this on NRVO
419 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000421 assert(getContext().hasSameUnqualifiedType(E->getType(),
422 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000423 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
424 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000425 return;
426 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000427 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000428
John McCallf677a8e2011-07-13 06:10:41 +0000429 if (const ConstantArrayType *arrayType
430 = getContext().getAsConstantArrayType(E->getType())) {
431 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000432 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000433 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000434 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000435 bool ForVirtualBase = false;
436
437 switch (E->getConstructionKind()) {
438 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000439 // We should be emitting a constructor; GlobalDecl will assert this
440 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000441 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000442
Alexis Hunt271c3682011-05-03 20:19:28 +0000443 case CXXConstructExpr::CK_Complete:
444 Type = Ctor_Complete;
445 break;
446
447 case CXXConstructExpr::CK_VirtualBase:
448 ForVirtualBase = true;
449 // fall-through
450
451 case CXXConstructExpr::CK_NonVirtualBase:
452 Type = Ctor_Base;
453 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000454
Anders Carlsson27da15b2010-01-01 20:29:01 +0000455 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000456 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000457 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000458 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000459}
460
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000461void
462CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
463 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000464 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000465 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000466 Exp = E->getSubExpr();
467 assert(isa<CXXConstructExpr>(Exp) &&
468 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
469 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
470 const CXXConstructorDecl *CD = E->getConstructor();
471 RunCleanupsScope Scope(*this);
472
473 // If we require zero initialization before (or instead of) calling the
474 // constructor, as can be the case with a non-user-provided default
475 // constructor, emit the zero initialization now.
476 // FIXME. Do I still need this for a copy ctor synthesis?
477 if (E->requiresZeroInitialization())
478 EmitNullInitialization(Dest, E->getType());
479
Chandler Carruth99da11c2010-11-15 13:54:43 +0000480 assert(!getContext().getAsConstantArrayType(E->getType())
481 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000482 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
483 E->arg_begin(), E->arg_end());
484}
485
John McCall8ed55a52010-09-02 09:58:18 +0000486static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
487 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000488 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000489 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000490
John McCall7ec4b432011-05-16 01:05:12 +0000491 // No cookie is required if the operator new[] being used is the
492 // reserved placement operator new[].
493 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000494 return CharUnits::Zero();
495
John McCall284c48f2011-01-27 09:37:56 +0000496 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000497}
498
John McCall036f2f62011-05-15 07:14:44 +0000499static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
500 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000501 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000502 llvm::Value *&numElements,
503 llvm::Value *&sizeWithoutCookie) {
504 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000505
John McCall036f2f62011-05-15 07:14:44 +0000506 if (!e->isArray()) {
507 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
508 sizeWithoutCookie
509 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
510 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000511 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000512
John McCall036f2f62011-05-15 07:14:44 +0000513 // The width of size_t.
514 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
515
John McCall8ed55a52010-09-02 09:58:18 +0000516 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000517 llvm::APInt cookieSize(sizeWidth,
518 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000519
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000520 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000521 // We multiply the size of all dimensions for NumElements.
522 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000523 numElements = CGF.EmitScalarExpr(e->getArraySize());
524 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000525
John McCall036f2f62011-05-15 07:14:44 +0000526 // The number of elements can be have an arbitrary integer type;
527 // essentially, we need to multiply it by a constant factor, add a
528 // cookie size, and verify that the result is representable as a
529 // size_t. That's just a gloss, though, and it's wrong in one
530 // important way: if the count is negative, it's an error even if
531 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000532 bool isSigned
533 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000534 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000535 = cast<llvm::IntegerType>(numElements->getType());
536 unsigned numElementsWidth = numElementsType->getBitWidth();
537
538 // Compute the constant factor.
539 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000540 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000541 = CGF.getContext().getAsConstantArrayType(type)) {
542 type = CAT->getElementType();
543 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000544 }
545
John McCall036f2f62011-05-15 07:14:44 +0000546 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
547 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
548 typeSizeMultiplier *= arraySizeMultiplier;
549
550 // This will be a size_t.
551 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000552
Chris Lattner32ac5832010-07-20 21:55:52 +0000553 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
554 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000555 if (llvm::ConstantInt *numElementsC =
556 dyn_cast<llvm::ConstantInt>(numElements)) {
557 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000558
John McCall036f2f62011-05-15 07:14:44 +0000559 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000560
John McCall036f2f62011-05-15 07:14:44 +0000561 // If 'count' was a negative number, it's an overflow.
562 if (isSigned && count.isNegative())
563 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000564
John McCall036f2f62011-05-15 07:14:44 +0000565 // We want to do all this arithmetic in size_t. If numElements is
566 // wider than that, check whether it's already too big, and if so,
567 // overflow.
568 else if (numElementsWidth > sizeWidth &&
569 numElementsWidth - sizeWidth > count.countLeadingZeros())
570 hasAnyOverflow = true;
571
572 // Okay, compute a count at the right width.
573 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
574
Sebastian Redlf862eb62012-02-22 17:37:52 +0000575 // If there is a brace-initializer, we cannot allocate fewer elements than
576 // there are initializers. If we do, that's treated like an overflow.
577 if (adjustedCount.ult(minElements))
578 hasAnyOverflow = true;
579
John McCall036f2f62011-05-15 07:14:44 +0000580 // Scale numElements by that. This might overflow, but we don't
581 // care because it only overflows if allocationSize does, too, and
582 // if that overflows then we shouldn't use this.
583 numElements = llvm::ConstantInt::get(CGF.SizeTy,
584 adjustedCount * arraySizeMultiplier);
585
586 // Compute the size before cookie, and track whether it overflowed.
587 bool overflow;
588 llvm::APInt allocationSize
589 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
590 hasAnyOverflow |= overflow;
591
592 // Add in the cookie, and check whether it's overflowed.
593 if (cookieSize != 0) {
594 // Save the current size without a cookie. This shouldn't be
595 // used if there was overflow.
596 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
597
598 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
599 hasAnyOverflow |= overflow;
600 }
601
602 // On overflow, produce a -1 so operator new will fail.
603 if (hasAnyOverflow) {
604 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
605 } else {
606 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
607 }
608
609 // Otherwise, we might need to use the overflow intrinsics.
610 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000611 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000612 // 1) if isSigned, we need to check whether numElements is negative;
613 // 2) if numElementsWidth > sizeWidth, we need to check whether
614 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000615 // 3) if minElements > 0, we need to check whether numElements is smaller
616 // than that.
617 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000618 // sizeWithoutCookie := numElements * typeSizeMultiplier
619 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000620 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000621 // size := sizeWithoutCookie + cookieSize
622 // and check whether it overflows.
623
624 llvm::Value *hasOverflow = 0;
625
626 // If numElementsWidth > sizeWidth, then one way or another, we're
627 // going to have to do a comparison for (2), and this happens to
628 // take care of (1), too.
629 if (numElementsWidth > sizeWidth) {
630 llvm::APInt threshold(numElementsWidth, 1);
631 threshold <<= sizeWidth;
632
633 llvm::Value *thresholdV
634 = llvm::ConstantInt::get(numElementsType, threshold);
635
636 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
637 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
638
639 // Otherwise, if we're signed, we want to sext up to size_t.
640 } else if (isSigned) {
641 if (numElementsWidth < sizeWidth)
642 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
643
644 // If there's a non-1 type size multiplier, then we can do the
645 // signedness check at the same time as we do the multiply
646 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000647 // unsigned overflow. Otherwise, we have to do it here. But at least
648 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000649 if (typeSizeMultiplier == 1)
650 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000651 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000652
653 // Otherwise, zext up to size_t if necessary.
654 } else if (numElementsWidth < sizeWidth) {
655 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
656 }
657
658 assert(numElements->getType() == CGF.SizeTy);
659
Sebastian Redlf862eb62012-02-22 17:37:52 +0000660 if (minElements) {
661 // Don't allow allocation of fewer elements than we have initializers.
662 if (!hasOverflow) {
663 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
664 llvm::ConstantInt::get(CGF.SizeTy, minElements));
665 } else if (numElementsWidth > sizeWidth) {
666 // The other existing overflow subsumes this check.
667 // We do an unsigned comparison, since any signed value < -1 is
668 // taken care of either above or below.
669 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
670 CGF.Builder.CreateICmpULT(numElements,
671 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
672 }
673 }
674
John McCall036f2f62011-05-15 07:14:44 +0000675 size = numElements;
676
677 // Multiply by the type size if necessary. This multiplier
678 // includes all the factors for nested arrays.
679 //
680 // This step also causes numElements to be scaled up by the
681 // nested-array factor if necessary. Overflow on this computation
682 // can be ignored because the result shouldn't be used if
683 // allocation fails.
684 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000685 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000686 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000687
688 llvm::Value *tsmV =
689 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
690 llvm::Value *result =
691 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
692
693 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
694 if (hasOverflow)
695 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
696 else
697 hasOverflow = overflowed;
698
699 size = CGF.Builder.CreateExtractValue(result, 0);
700
701 // Also scale up numElements by the array size multiplier.
702 if (arraySizeMultiplier != 1) {
703 // If the base element type size is 1, then we can re-use the
704 // multiply we just did.
705 if (typeSize.isOne()) {
706 assert(arraySizeMultiplier == typeSizeMultiplier);
707 numElements = size;
708
709 // Otherwise we need a separate multiply.
710 } else {
711 llvm::Value *asmV =
712 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
713 numElements = CGF.Builder.CreateMul(numElements, asmV);
714 }
715 }
716 } else {
717 // numElements doesn't need to be scaled.
718 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000719 }
720
John McCall036f2f62011-05-15 07:14:44 +0000721 // Add in the cookie size if necessary.
722 if (cookieSize != 0) {
723 sizeWithoutCookie = size;
724
John McCall036f2f62011-05-15 07:14:44 +0000725 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000726 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000727
728 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
729 llvm::Value *result =
730 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
731
732 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
733 if (hasOverflow)
734 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
735 else
736 hasOverflow = overflowed;
737
738 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000739 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000740
John McCall036f2f62011-05-15 07:14:44 +0000741 // If we had any possibility of dynamic overflow, make a select to
742 // overwrite 'size' with an all-ones value, which should cause
743 // operator new to throw.
744 if (hasOverflow)
745 size = CGF.Builder.CreateSelect(hasOverflow,
746 llvm::Constant::getAllOnesValue(CGF.SizeTy),
747 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000748 }
John McCall8ed55a52010-09-02 09:58:18 +0000749
John McCall036f2f62011-05-15 07:14:44 +0000750 if (cookieSize == 0)
751 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000752 else
John McCall036f2f62011-05-15 07:14:44 +0000753 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000754
John McCall036f2f62011-05-15 07:14:44 +0000755 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000756}
757
Sebastian Redlf862eb62012-02-22 17:37:52 +0000758static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
759 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000760
Eli Friedman38cd36d2011-12-03 02:13:40 +0000761 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000762 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000763 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000764 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000765 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000766 else if (AllocType->isAnyComplexType())
767 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
768 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000769 else {
770 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000771 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000772 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000773 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000774 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000775 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000776
777 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000778 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000779}
780
781void
782CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000783 QualType elementType,
784 llvm::Value *beginPtr,
785 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000786 if (!E->hasInitializer())
787 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000788
Sebastian Redlf862eb62012-02-22 17:37:52 +0000789 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000790 // Find the end of the array, hoisted out of the loop.
791 llvm::Value *endPtr =
792 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
793
Sebastian Redlf862eb62012-02-22 17:37:52 +0000794 unsigned initializerElements = 0;
795
796 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000797 llvm::AllocaInst *endOfInit = 0;
798 QualType::DestructionKind dtorKind = elementType.isDestructedType();
799 EHScopeStack::stable_iterator cleanup;
800 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000801 // If the initializer is an initializer list, first do the explicit elements.
802 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
803 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000804
805 // Enter a partial-destruction cleanup if necessary.
806 if (needsEHCleanup(dtorKind)) {
807 // In principle we could tell the cleanup where we are more
808 // directly, but the control flow can get so varied here that it
809 // would actually be quite complex. Therefore we go through an
810 // alloca.
811 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
812 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
813 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
814 getDestroyer(dtorKind));
815 cleanup = EHStack.stable_begin();
816 }
817
Sebastian Redlf862eb62012-02-22 17:37:52 +0000818 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000819 // Tell the cleanup that it needs to destroy up to this
820 // element. TODO: some of these stores can be trivially
821 // observed to be unnecessary.
822 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000823 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
824 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
825 }
826
827 // The remaining elements are filled with the array filler expression.
828 Init = ILE->getArrayFiller();
829 }
830
John McCall99210dc2011-09-15 06:49:18 +0000831 // Create the continuation block.
832 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
833
Sebastian Redlf862eb62012-02-22 17:37:52 +0000834 // If the number of elements isn't constant, we have to now check if there is
835 // anything left to initialize.
836 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
837 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000838 if (constNum->getZExtValue() <= initializerElements) {
839 // If there was a cleanup, deactivate it.
840 if (cleanupDominator)
841 DeactivateCleanupBlock(cleanup, cleanupDominator);;
842 return;
843 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000844 } else {
John McCall99210dc2011-09-15 06:49:18 +0000845 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000846 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000847 "array.isempty");
848 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
849 EmitBlock(nonEmptyBB);
850 }
851
852 // Enter the loop.
853 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
854 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
855
856 EmitBlock(loopBB);
857
858 // Set up the current-element phi.
859 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000860 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
861 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000862
Chad Rosierf62290a2012-02-24 00:13:55 +0000863 // Store the new cleanup position for irregular cleanups.
864 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
865
John McCall99210dc2011-09-15 06:49:18 +0000866 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000867 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000868 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
869 getDestroyer(dtorKind));
870 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000871 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000872 }
873
874 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000875 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000876
877 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000878 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000879 DeactivateCleanupBlock(cleanup, cleanupDominator);
880 cleanupDominator->eraseFromParent();
881 }
John McCall99210dc2011-09-15 06:49:18 +0000882
883 // Advance to the next element.
884 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
885
886 // Check whether we've gotten to the end of the array and, if so,
887 // exit the loop.
888 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
889 Builder.CreateCondBr(isEnd, contBB, loopBB);
890 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
891
892 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000893}
894
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000895static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
896 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000897 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000898 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000899 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000900 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000901}
902
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000903static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000904 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000905 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000906 llvm::Value *NumElements,
907 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000908 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000909 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000910 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
911 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000912 bool RequiresZeroInitialization = false;
Douglas Gregord1531032012-02-23 17:07:43 +0000913 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000914 // If new expression did not specify value-initialization, then there
915 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000916 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000917 return;
918
John McCall99210dc2011-09-15 06:49:18 +0000919 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000920 // Optimization: since zero initialization will just set the memory
921 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000922 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000923 return;
924 }
925
926 RequiresZeroInitialization = true;
927 }
John McCallf677a8e2011-07-13 06:10:41 +0000928
Sebastian Redl6047f072012-02-16 12:22:20 +0000929 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
930 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000931 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000932 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000933 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000934 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000935 // Optimization: since zero initialization will just set the memory
936 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000937 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
938 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000939 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000940 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
941 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000942 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000943
Sebastian Redl6047f072012-02-16 12:22:20 +0000944 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000945 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000946
Sebastian Redlf862eb62012-02-22 17:37:52 +0000947 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000948}
949
John McCall824c2f52010-09-14 07:57:04 +0000950namespace {
951 /// A cleanup to call the given 'operator delete' function upon
952 /// abnormal exit from a new expression.
953 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
954 size_t NumPlacementArgs;
955 const FunctionDecl *OperatorDelete;
956 llvm::Value *Ptr;
957 llvm::Value *AllocSize;
958
959 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
960
961 public:
962 static size_t getExtraSize(size_t NumPlacementArgs) {
963 return NumPlacementArgs * sizeof(RValue);
964 }
965
966 CallDeleteDuringNew(size_t NumPlacementArgs,
967 const FunctionDecl *OperatorDelete,
968 llvm::Value *Ptr,
969 llvm::Value *AllocSize)
970 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
971 Ptr(Ptr), AllocSize(AllocSize) {}
972
973 void setPlacementArg(unsigned I, RValue Arg) {
974 assert(I < NumPlacementArgs && "index out of range");
975 getPlacementArgs()[I] = Arg;
976 }
977
John McCall30317fd2011-07-12 20:27:29 +0000978 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +0000979 const FunctionProtoType *FPT
980 = OperatorDelete->getType()->getAs<FunctionProtoType>();
981 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000982 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000983
984 CallArgList DeleteArgs;
985
986 // The first argument is always a void*.
987 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000988 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000989
990 // A member 'operator delete' can take an extra 'size_t' argument.
991 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000992 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000993
994 // Pass the rest of the arguments, which must match exactly.
995 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000996 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000997
998 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +0000999 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +00001000 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1001 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1002 }
1003 };
John McCall7f9c92a2010-09-17 00:50:28 +00001004
1005 /// A cleanup to call the given 'operator delete' function upon
1006 /// abnormal exit from a new expression when the new expression is
1007 /// conditional.
1008 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1009 size_t NumPlacementArgs;
1010 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001011 DominatingValue<RValue>::saved_type Ptr;
1012 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001013
John McCallcb5f77f2011-01-28 10:53:53 +00001014 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1015 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001016 }
1017
1018 public:
1019 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001020 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001021 }
1022
1023 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1024 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001025 DominatingValue<RValue>::saved_type Ptr,
1026 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001027 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1028 Ptr(Ptr), AllocSize(AllocSize) {}
1029
John McCallcb5f77f2011-01-28 10:53:53 +00001030 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001031 assert(I < NumPlacementArgs && "index out of range");
1032 getPlacementArgs()[I] = Arg;
1033 }
1034
John McCall30317fd2011-07-12 20:27:29 +00001035 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001036 const FunctionProtoType *FPT
1037 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1038 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1039 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1040
1041 CallArgList DeleteArgs;
1042
1043 // The first argument is always a void*.
1044 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001045 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001046
1047 // A member 'operator delete' can take an extra 'size_t' argument.
1048 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001049 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001050 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001051 }
1052
1053 // Pass the rest of the arguments, which must match exactly.
1054 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001055 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001056 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001057 }
1058
1059 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001060 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001061 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1062 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1063 }
1064 };
1065}
1066
1067/// Enter a cleanup to call 'operator delete' if the initializer in a
1068/// new-expression throws.
1069static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1070 const CXXNewExpr *E,
1071 llvm::Value *NewPtr,
1072 llvm::Value *AllocSize,
1073 const CallArgList &NewArgs) {
1074 // If we're not inside a conditional branch, then the cleanup will
1075 // dominate and we can do the easier (and more efficient) thing.
1076 if (!CGF.isInConditionalBranch()) {
1077 CallDeleteDuringNew *Cleanup = CGF.EHStack
1078 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1079 E->getNumPlacementArgs(),
1080 E->getOperatorDelete(),
1081 NewPtr, AllocSize);
1082 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001083 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001084
1085 return;
1086 }
1087
1088 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001089 DominatingValue<RValue>::saved_type SavedNewPtr =
1090 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1091 DominatingValue<RValue>::saved_type SavedAllocSize =
1092 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001093
1094 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001095 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001096 E->getNumPlacementArgs(),
1097 E->getOperatorDelete(),
1098 SavedNewPtr,
1099 SavedAllocSize);
1100 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001101 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001102 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001103
John McCallf4beacd2011-11-10 10:43:54 +00001104 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001105}
1106
Anders Carlssoncc52f652009-09-22 22:53:17 +00001107llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001108 // The element type being allocated.
1109 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001110
John McCall75f94982011-03-07 03:12:35 +00001111 // 1. Build a call to the allocation function.
1112 FunctionDecl *allocator = E->getOperatorNew();
1113 const FunctionProtoType *allocatorType =
1114 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001115
John McCall75f94982011-03-07 03:12:35 +00001116 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001117
1118 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001119 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001120
Sebastian Redlf862eb62012-02-22 17:37:52 +00001121 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1122 unsigned minElements = 0;
1123 if (E->isArray() && E->hasInitializer()) {
1124 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1125 minElements = ILE->getNumInits();
1126 }
1127
John McCall75f94982011-03-07 03:12:35 +00001128 llvm::Value *numElements = 0;
1129 llvm::Value *allocSizeWithoutCookie = 0;
1130 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001131 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1132 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001133
Eli Friedman43dca6a2011-05-02 17:57:46 +00001134 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001135
1136 // Emit the rest of the arguments.
1137 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001138 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001139
1140 // First, use the types from the function type.
1141 // We start at 1 here because the first argument (the allocation size)
1142 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001143 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1144 ++i, ++placementArg) {
1145 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001146
John McCall75f94982011-03-07 03:12:35 +00001147 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1148 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001149 "type mismatch in call argument!");
1150
John McCall32ea9692011-03-11 20:59:21 +00001151 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001152 }
1153
1154 // Either we've emitted all the call args, or we have a call to a
1155 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001156 assert((placementArg == E->placement_arg_end() ||
1157 allocatorType->isVariadic()) &&
1158 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001159
1160 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001161 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1162 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001163 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001164 }
1165
John McCall7ec4b432011-05-16 01:05:12 +00001166 // Emit the allocation call. If the allocator is a global placement
1167 // operator, just "inline" it directly.
1168 RValue RV;
1169 if (allocator->isReservedGlobalPlacementOperator()) {
1170 assert(allocatorArgs.size() == 2);
1171 RV = allocatorArgs[1].RV;
1172 // TODO: kill any unnecessary computations done for the size
1173 // argument.
1174 } else {
John McCalla729c622012-02-17 03:33:10 +00001175 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1176 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001177 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1178 allocatorArgs, allocator);
1179 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001180
John McCall75f94982011-03-07 03:12:35 +00001181 // Emit a null check on the allocation result if the allocation
1182 // function is allowed to return null (because it has a non-throwing
1183 // exception spec; for this part, we inline
1184 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1185 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001186 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001187 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001188
John McCall75f94982011-03-07 03:12:35 +00001189 llvm::BasicBlock *nullCheckBB = 0;
1190 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001191
John McCall75f94982011-03-07 03:12:35 +00001192 llvm::Value *allocation = RV.getScalarVal();
1193 unsigned AS =
1194 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001195
John McCallf7dcf322011-03-07 01:52:56 +00001196 // The null-check means that the initializer is conditionally
1197 // evaluated.
1198 ConditionalEvaluation conditional(*this);
1199
John McCall75f94982011-03-07 03:12:35 +00001200 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001201 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001202
1203 nullCheckBB = Builder.GetInsertBlock();
1204 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1205 contBB = createBasicBlock("new.cont");
1206
1207 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1208 Builder.CreateCondBr(isNull, contBB, notNullBB);
1209 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001210 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001211
John McCall824c2f52010-09-14 07:57:04 +00001212 // If there's an operator delete, enter a cleanup to call it if an
1213 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001214 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001215 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001216 if (E->getOperatorDelete() &&
1217 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001218 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1219 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001220 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001221 }
1222
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001223 assert((allocSize == allocSizeWithoutCookie) ==
1224 CalculateCookiePadding(*this, E).isZero());
1225 if (allocSize != allocSizeWithoutCookie) {
1226 assert(E->isArray());
1227 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1228 numElements,
1229 E, allocType);
1230 }
1231
Chris Lattner2192fe52011-07-18 04:24:23 +00001232 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001233 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1234 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001235
John McCall99210dc2011-09-15 06:49:18 +00001236 EmitNewInitializer(*this, E, allocType, result, numElements,
1237 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001238 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001239 // NewPtr is a pointer to the base element type. If we're
1240 // allocating an array of arrays, we'll need to cast back to the
1241 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001242 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001243 if (result->getType() != resultType)
1244 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001245 }
John McCall824c2f52010-09-14 07:57:04 +00001246
1247 // Deactivate the 'operator delete' cleanup if we finished
1248 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001249 if (operatorDeleteCleanup.isValid()) {
1250 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1251 cleanupDominator->eraseFromParent();
1252 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001253
John McCall75f94982011-03-07 03:12:35 +00001254 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001255 conditional.end(*this);
1256
John McCall75f94982011-03-07 03:12:35 +00001257 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1258 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001259
Jay Foad20c0f022011-03-30 11:28:58 +00001260 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001261 PHI->addIncoming(result, notNullBB);
1262 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1263 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001264
John McCall75f94982011-03-07 03:12:35 +00001265 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001266 }
John McCall8ed55a52010-09-02 09:58:18 +00001267
John McCall75f94982011-03-07 03:12:35 +00001268 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001269}
1270
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001271void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1272 llvm::Value *Ptr,
1273 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001274 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1275
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001276 const FunctionProtoType *DeleteFTy =
1277 DeleteFD->getType()->getAs<FunctionProtoType>();
1278
1279 CallArgList DeleteArgs;
1280
Anders Carlsson21122cf2009-12-13 20:04:38 +00001281 // Check if we need to pass the size to the delete operator.
1282 llvm::Value *Size = 0;
1283 QualType SizeTy;
1284 if (DeleteFTy->getNumArgs() == 2) {
1285 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001286 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1287 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1288 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001289 }
1290
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001291 QualType ArgTy = DeleteFTy->getArgType(0);
1292 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001293 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001294
Anders Carlsson21122cf2009-12-13 20:04:38 +00001295 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001296 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001297
1298 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001299 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001300 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001301 DeleteArgs, DeleteFD);
1302}
1303
John McCall8ed55a52010-09-02 09:58:18 +00001304namespace {
1305 /// Calls the given 'operator delete' on a single object.
1306 struct CallObjectDelete : EHScopeStack::Cleanup {
1307 llvm::Value *Ptr;
1308 const FunctionDecl *OperatorDelete;
1309 QualType ElementType;
1310
1311 CallObjectDelete(llvm::Value *Ptr,
1312 const FunctionDecl *OperatorDelete,
1313 QualType ElementType)
1314 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1315
John McCall30317fd2011-07-12 20:27:29 +00001316 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001317 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1318 }
1319 };
1320}
1321
1322/// Emit the code for deleting a single object.
1323static void EmitObjectDelete(CodeGenFunction &CGF,
1324 const FunctionDecl *OperatorDelete,
1325 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001326 QualType ElementType,
1327 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001328 // Find the destructor for the type, if applicable. If the
1329 // destructor is virtual, we'll just emit the vcall and return.
1330 const CXXDestructorDecl *Dtor = 0;
1331 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1332 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001333 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001334 Dtor = RD->getDestructor();
1335
1336 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001337 if (UseGlobalDelete) {
1338 // If we're supposed to call the global delete, make sure we do so
1339 // even if the destructor throws.
1340 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1341 Ptr, OperatorDelete,
1342 ElementType);
1343 }
1344
Chris Lattner2192fe52011-07-18 04:24:23 +00001345 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001346 CGF.getTypes().GetFunctionType(
1347 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001348
1349 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001350 = CGF.BuildVirtualCall(Dtor,
1351 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1352 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001353 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1354 0, 0);
1355
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001356 if (UseGlobalDelete) {
1357 CGF.PopCleanupBlock();
1358 }
1359
John McCall8ed55a52010-09-02 09:58:18 +00001360 return;
1361 }
1362 }
1363 }
1364
1365 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001366 // This doesn't have to a conditional cleanup because we're going
1367 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001368 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1369 Ptr, OperatorDelete, ElementType);
1370
1371 if (Dtor)
1372 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1373 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001374 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001375 ElementType->isObjCLifetimeType()) {
1376 switch (ElementType.getObjCLifetime()) {
1377 case Qualifiers::OCL_None:
1378 case Qualifiers::OCL_ExplicitNone:
1379 case Qualifiers::OCL_Autoreleasing:
1380 break;
John McCall8ed55a52010-09-02 09:58:18 +00001381
John McCall31168b02011-06-15 23:02:42 +00001382 case Qualifiers::OCL_Strong: {
1383 // Load the pointer value.
1384 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1385 ElementType.isVolatileQualified());
1386
1387 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1388 break;
1389 }
1390
1391 case Qualifiers::OCL_Weak:
1392 CGF.EmitARCDestroyWeak(Ptr);
1393 break;
1394 }
1395 }
1396
John McCall8ed55a52010-09-02 09:58:18 +00001397 CGF.PopCleanupBlock();
1398}
1399
1400namespace {
1401 /// Calls the given 'operator delete' on an array of objects.
1402 struct CallArrayDelete : EHScopeStack::Cleanup {
1403 llvm::Value *Ptr;
1404 const FunctionDecl *OperatorDelete;
1405 llvm::Value *NumElements;
1406 QualType ElementType;
1407 CharUnits CookieSize;
1408
1409 CallArrayDelete(llvm::Value *Ptr,
1410 const FunctionDecl *OperatorDelete,
1411 llvm::Value *NumElements,
1412 QualType ElementType,
1413 CharUnits CookieSize)
1414 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1415 ElementType(ElementType), CookieSize(CookieSize) {}
1416
John McCall30317fd2011-07-12 20:27:29 +00001417 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001418 const FunctionProtoType *DeleteFTy =
1419 OperatorDelete->getType()->getAs<FunctionProtoType>();
1420 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1421
1422 CallArgList Args;
1423
1424 // Pass the pointer as the first argument.
1425 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1426 llvm::Value *DeletePtr
1427 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001428 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001429
1430 // Pass the original requested size as the second argument.
1431 if (DeleteFTy->getNumArgs() == 2) {
1432 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001433 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001434 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1435
1436 CharUnits ElementTypeSize =
1437 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1438
1439 // The size of an element, multiplied by the number of elements.
1440 llvm::Value *Size
1441 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1442 Size = CGF.Builder.CreateMul(Size, NumElements);
1443
1444 // Plus the size of the cookie if applicable.
1445 if (!CookieSize.isZero()) {
1446 llvm::Value *CookieSizeV
1447 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1448 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1449 }
1450
Eli Friedman43dca6a2011-05-02 17:57:46 +00001451 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001452 }
1453
1454 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001455 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001456 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1457 ReturnValueSlot(), Args, OperatorDelete);
1458 }
1459 };
1460}
1461
1462/// Emit the code for deleting an array of objects.
1463static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001464 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001465 llvm::Value *deletedPtr,
1466 QualType elementType) {
1467 llvm::Value *numElements = 0;
1468 llvm::Value *allocatedPtr = 0;
1469 CharUnits cookieSize;
1470 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1471 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001472
John McCallca2c56f2011-07-13 01:41:37 +00001473 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001474
1475 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001476 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001477 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001478 allocatedPtr, operatorDelete,
1479 numElements, elementType,
1480 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001481
John McCallca2c56f2011-07-13 01:41:37 +00001482 // Destroy the elements.
1483 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1484 assert(numElements && "no element count for a type with a destructor!");
1485
John McCallca2c56f2011-07-13 01:41:37 +00001486 llvm::Value *arrayEnd =
1487 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001488
1489 // Note that it is legal to allocate a zero-length array, and we
1490 // can never fold the check away because the length should always
1491 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001492 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1493 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001494 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001495 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001496 }
1497
John McCallca2c56f2011-07-13 01:41:37 +00001498 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001499 CGF.PopCleanupBlock();
1500}
1501
Anders Carlssoncc52f652009-09-22 22:53:17 +00001502void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001503
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001504 // Get at the argument before we performed the implicit conversion
1505 // to void*.
1506 const Expr *Arg = E->getArgument();
1507 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001508 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001509 ICE->getType()->isVoidPointerType())
1510 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001511 else
1512 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001513 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001514
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001515 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001516
1517 // Null check the pointer.
1518 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1519 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1520
Anders Carlsson98981b12011-04-11 00:30:07 +00001521 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001522
1523 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1524 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001525
John McCall8ed55a52010-09-02 09:58:18 +00001526 // We might be deleting a pointer to array. If so, GEP down to the
1527 // first non-array element.
1528 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1529 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1530 if (DeleteTy->isConstantArrayType()) {
1531 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001532 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001533
1534 GEP.push_back(Zero); // point at the outermost array
1535
1536 // For each layer of array type we're pointing at:
1537 while (const ConstantArrayType *Arr
1538 = getContext().getAsConstantArrayType(DeleteTy)) {
1539 // 1. Unpeel the array type.
1540 DeleteTy = Arr->getElementType();
1541
1542 // 2. GEP to the first element of the array.
1543 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001544 }
John McCall8ed55a52010-09-02 09:58:18 +00001545
Jay Foad040dd822011-07-22 08:16:57 +00001546 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001547 }
1548
Douglas Gregor04f36212010-09-02 17:38:50 +00001549 assert(ConvertTypeForMem(DeleteTy) ==
1550 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001551
1552 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001553 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001554 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001555 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1556 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001557 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001558
Anders Carlssoncc52f652009-09-22 22:53:17 +00001559 EmitBlock(DeleteEnd);
1560}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001561
Anders Carlsson0c633502011-04-11 14:13:40 +00001562static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1563 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001564 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001565
1566 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1567}
1568
1569static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001570 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001571 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001572 CGF.Builder.CreateUnreachable();
1573}
1574
Anders Carlsson940f02d2011-04-18 00:57:03 +00001575static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1576 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001577 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001578 // Get the vtable pointer.
1579 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1580
1581 // C++ [expr.typeid]p2:
1582 // If the glvalue expression is obtained by applying the unary * operator to
1583 // a pointer and the pointer is a null pointer value, the typeid expression
1584 // throws the std::bad_typeid exception.
1585 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1586 if (UO->getOpcode() == UO_Deref) {
1587 llvm::BasicBlock *BadTypeidBlock =
1588 CGF.createBasicBlock("typeid.bad_typeid");
1589 llvm::BasicBlock *EndBlock =
1590 CGF.createBasicBlock("typeid.end");
1591
1592 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1593 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1594
1595 CGF.EmitBlock(BadTypeidBlock);
1596 EmitBadTypeidCall(CGF);
1597 CGF.EmitBlock(EndBlock);
1598 }
1599 }
1600
1601 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1602 StdTypeInfoPtrTy->getPointerTo());
1603
1604 // Load the type info.
1605 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1606 return CGF.Builder.CreateLoad(Value);
1607}
1608
John McCalle4df6c82011-01-28 08:37:24 +00001609llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001610 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001611 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001612
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001613 if (E->isTypeOperand()) {
1614 llvm::Constant *TypeInfo =
1615 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001616 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001617 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001618
Anders Carlsson940f02d2011-04-18 00:57:03 +00001619 // C++ [expr.typeid]p2:
1620 // When typeid is applied to a glvalue expression whose type is a
1621 // polymorphic class type, the result refers to a std::type_info object
1622 // representing the type of the most derived object (that is, the dynamic
1623 // type) to which the glvalue refers.
1624 if (E->getExprOperand()->isGLValue()) {
1625 if (const RecordType *RT =
1626 E->getExprOperand()->getType()->getAs<RecordType>()) {
1627 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1628 if (RD->isPolymorphic())
1629 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1630 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001631 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001632 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001633
1634 QualType OperandTy = E->getExprOperand()->getType();
1635 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1636 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001637}
Mike Stump65511702009-11-16 06:50:58 +00001638
Anders Carlsson882d7902011-04-11 00:46:40 +00001639static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1640 // void *__dynamic_cast(const void *sub,
1641 // const abi::__class_type_info *src,
1642 // const abi::__class_type_info *dst,
1643 // std::ptrdiff_t src2dst_offset);
1644
Chris Lattnerece04092012-02-07 00:39:47 +00001645 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001646 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001647 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1648
Chris Lattnera5f58b02011-07-09 17:41:47 +00001649 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001650
Chris Lattner2192fe52011-07-18 04:24:23 +00001651 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001652 llvm::FunctionType::get(Int8PtrTy, Args, false);
1653
1654 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1655}
1656
1657static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1658 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001659 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001660 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1661}
1662
Anders Carlssonc1c99712011-04-11 01:45:29 +00001663static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001664 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001665 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001666 CGF.Builder.CreateUnreachable();
1667}
1668
Anders Carlsson882d7902011-04-11 00:46:40 +00001669static llvm::Value *
1670EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1671 QualType SrcTy, QualType DestTy,
1672 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001673 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001674 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001675 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001676
1677 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1678 if (PTy->getPointeeType()->isVoidType()) {
1679 // C++ [expr.dynamic.cast]p7:
1680 // If T is "pointer to cv void," then the result is a pointer to the
1681 // most derived object pointed to by v.
1682
1683 // Get the vtable pointer.
1684 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1685
1686 // Get the offset-to-top from the vtable.
1687 llvm::Value *OffsetToTop =
1688 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1689 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1690
1691 // Finally, add the offset to the pointer.
1692 Value = CGF.EmitCastToVoidPtr(Value);
1693 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1694
1695 return CGF.Builder.CreateBitCast(Value, DestLTy);
1696 }
1697 }
1698
1699 QualType SrcRecordTy;
1700 QualType DestRecordTy;
1701
1702 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1703 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1704 DestRecordTy = DestPTy->getPointeeType();
1705 } else {
1706 SrcRecordTy = SrcTy;
1707 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1708 }
1709
1710 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1711 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1712
1713 llvm::Value *SrcRTTI =
1714 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1715 llvm::Value *DestRTTI =
1716 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1717
1718 // FIXME: Actually compute a hint here.
1719 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1720
1721 // Emit the call to __dynamic_cast.
1722 Value = CGF.EmitCastToVoidPtr(Value);
1723 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1724 SrcRTTI, DestRTTI, OffsetHint);
1725 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1726
1727 /// C++ [expr.dynamic.cast]p9:
1728 /// A failed cast to reference type throws std::bad_cast
1729 if (DestTy->isReferenceType()) {
1730 llvm::BasicBlock *BadCastBlock =
1731 CGF.createBasicBlock("dynamic_cast.bad_cast");
1732
1733 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1734 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1735
1736 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001737 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001738 }
1739
1740 return Value;
1741}
1742
Anders Carlssonc1c99712011-04-11 01:45:29 +00001743static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1744 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001745 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001746 if (DestTy->isPointerType())
1747 return llvm::Constant::getNullValue(DestLTy);
1748
1749 /// C++ [expr.dynamic.cast]p9:
1750 /// A failed cast to reference type throws std::bad_cast
1751 EmitBadCastCall(CGF);
1752
1753 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1754 return llvm::UndefValue::get(DestLTy);
1755}
1756
Anders Carlsson882d7902011-04-11 00:46:40 +00001757llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001758 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001759 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001760
Anders Carlssonc1c99712011-04-11 01:45:29 +00001761 if (DCE->isAlwaysNull())
1762 return EmitDynamicCastToNull(*this, DestTy);
1763
1764 QualType SrcTy = DCE->getSubExpr()->getType();
1765
Anders Carlsson882d7902011-04-11 00:46:40 +00001766 // C++ [expr.dynamic.cast]p4:
1767 // If the value of v is a null pointer value in the pointer case, the result
1768 // is the null pointer value of type T.
1769 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001770
Anders Carlsson882d7902011-04-11 00:46:40 +00001771 llvm::BasicBlock *CastNull = 0;
1772 llvm::BasicBlock *CastNotNull = 0;
1773 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001774
Anders Carlsson882d7902011-04-11 00:46:40 +00001775 if (ShouldNullCheckSrcValue) {
1776 CastNull = createBasicBlock("dynamic_cast.null");
1777 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1778
1779 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1780 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1781 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001782 }
1783
Anders Carlsson882d7902011-04-11 00:46:40 +00001784 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1785
1786 if (ShouldNullCheckSrcValue) {
1787 EmitBranch(CastEnd);
1788
1789 EmitBlock(CastNull);
1790 EmitBranch(CastEnd);
1791 }
1792
1793 EmitBlock(CastEnd);
1794
1795 if (ShouldNullCheckSrcValue) {
1796 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1797 PHI->addIncoming(Value, CastNotNull);
1798 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1799
1800 Value = PHI;
1801 }
1802
1803 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001804}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001805
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001806void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001807 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001808 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1809 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001810
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001811 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1812 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1813 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001814 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001815 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001816
David Blaikie40ed2972012-06-06 20:45:41 +00001817 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001818 ArrayRef<VarDecl *> ArrayIndexes;
1819 if (CurField->getType()->isArrayType())
1820 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001821 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001822 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001823}