blob: 4b0bff0ad0db7f30298533195131672a3d673451 [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
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000145static CXXRecordDecl *getCXXRecord(const Expr *E) {
146 QualType T = E->getType();
147 if (const PointerType *PTy = T->getAs<PointerType>())
148 T = PTy->getPointeeType();
149 const RecordType *Ty = T->castAs<RecordType>();
150 return cast<CXXRecordDecl>(Ty->getDecl());
151}
152
Francois Pichet64225792011-01-18 05:04:39 +0000153// Note: This function also emit constructor calls to support a MSVC
154// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000155RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
156 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000157 const Expr *callee = CE->getCallee()->IgnoreParens();
158
159 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000160 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000161
162 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000163 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
164
Devang Patel91bbb552010-09-30 19:05:55 +0000165 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000166 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel401c9162010-10-22 18:56:27 +0000167 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000168 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
169 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
170 DI->getOrCreateRecordType(PTy->getPointeeType(),
171 MD->getParent()->getLocation());
172 }
173 }
174
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 if (MD->isStatic()) {
176 // The method is static, emit it as we would a regular call.
177 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
178 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
179 ReturnValue, CE->arg_begin(), CE->arg_end());
180 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000181
John McCall0d635f52010-09-03 01:26:39 +0000182 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000183 const Expr *Base = ME->getBase();
184 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000185
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000186 const CXXMethodDecl *DevirtualizedMethod = NULL;
187 if (CanUseVirtualCall &&
188 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
189 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
190 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
191 assert(DevirtualizedMethod);
192 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
193 const Expr *Inner = Base->ignoreParenBaseCasts();
194 if (getCXXRecord(Inner) == DevirtualizedClass)
195 // If the class of the Inner expression is where the dynamic method
196 // is defined, build the this pointer from it.
197 Base = Inner;
198 else if (getCXXRecord(Base) != DevirtualizedClass) {
199 // If the method is defined in a class that is not the best dynamic
200 // one or the one of the full expression, we would have to build
201 // a derived-to-base cast to compute the correct this pointer, but
202 // we don't have support for that yet, so do a virtual call.
203 DevirtualizedMethod = NULL;
204 }
Rafael Espindoladebc71c2012-06-28 15:11:39 +0000205 if (DevirtualizedMethod && DevirtualizedMethod->getResultType() !=
206 MD->getResultType())
207 DevirtualizedMethod = NULL;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000208 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000209
Anders Carlsson27da15b2010-01-01 20:29:01 +0000210 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000211 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000212 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000213 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000214 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000215
Anders Carlsson27da15b2010-01-01 20:29:01 +0000216
John McCall0d635f52010-09-03 01:26:39 +0000217 if (MD->isTrivial()) {
218 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000219 if (isa<CXXConstructorDecl>(MD) &&
220 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
221 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000222
Sebastian Redl22653ba2011-08-30 19:58:05 +0000223 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
224 // We don't like to generate the trivial copy/move assignment operator
225 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000226 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
227 EmitAggregateCopy(This, RHS, CE->getType());
228 return RValue::get(This);
229 }
230
231 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000232 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
233 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000234 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
235 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
236 CE->arg_begin(), CE->arg_end());
237 return RValue::get(This);
238 }
239 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000240 }
241
John McCall0d635f52010-09-03 01:26:39 +0000242 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000243 const CGFunctionInfo *FInfo = 0;
244 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000245 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
246 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000247 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000248 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
249 cast<CXXConstructorDecl>(MD),
250 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000251 else
John McCalla729c622012-02-17 03:33:10 +0000252 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000253
John McCalla729c622012-02-17 03:33:10 +0000254 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000255
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 // C++ [class.virtual]p12:
257 // Explicit qualification with the scope operator (5.1) suppresses the
258 // virtual call mechanism.
259 //
260 // We also don't emit a virtual call if the base expression has a record type
261 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000262 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola49e860b2012-06-26 17:45:31 +0000263
Anders Carlsson27da15b2010-01-01 20:29:01 +0000264 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000265 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
266 if (UseVirtualCall) {
267 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000268 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000269 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000270 MD->isVirtual() &&
271 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000272 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000273 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000274 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000275 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000276 const CXXDestructorDecl *DDtor =
277 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000278 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
279 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000280 }
Francois Pichet64225792011-01-18 05:04:39 +0000281 } else if (const CXXConstructorDecl *Ctor =
282 dyn_cast<CXXConstructorDecl>(MD)) {
283 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000284 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000285 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000286 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000288 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000289 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000290 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000291 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000292 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000293 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000294 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000295 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 }
297
Anders Carlssone36a6b32010-01-02 01:01:18 +0000298 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000299 CE->arg_begin(), CE->arg_end());
300}
301
302RValue
303CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
304 ReturnValueSlot ReturnValue) {
305 const BinaryOperator *BO =
306 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
307 const Expr *BaseExpr = BO->getLHS();
308 const Expr *MemFnExpr = BO->getRHS();
309
310 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000311 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000312
Anders Carlsson27da15b2010-01-01 20:29:01 +0000313 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000314 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000315 const CXXRecordDecl *RD =
316 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
317
Anders Carlsson27da15b2010-01-01 20:29:01 +0000318 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000319 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000320
321 // Emit the 'this' pointer.
322 llvm::Value *This;
323
John McCalle3027922010-08-25 11:45:40 +0000324 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000325 This = EmitScalarExpr(BaseExpr);
326 else
327 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000328
John McCall475999d2010-08-22 00:05:51 +0000329 // Ask the ABI to load the callee. Note that This is modified.
330 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000331 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000332
Anders Carlsson27da15b2010-01-01 20:29:01 +0000333 CallArgList Args;
334
335 QualType ThisType =
336 getContext().getPointerType(getContext().getTagDeclType(RD));
337
338 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000339 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000340
341 // And the rest of the call args
342 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCalla729c622012-02-17 03:33:10 +0000343 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000344 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000345}
346
347RValue
348CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
349 const CXXMethodDecl *MD,
350 ReturnValueSlot ReturnValue) {
351 assert(MD->isInstance() &&
352 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000353 LValue LV = EmitLValue(E->getArg(0));
354 llvm::Value *This = LV.getAddress();
355
Douglas Gregor146b8e92011-09-06 16:26:56 +0000356 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
357 MD->isTrivial()) {
358 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
359 QualType Ty = E->getType();
360 EmitAggregateCopy(This, Src, Ty);
361 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000362 }
363
Anders Carlssonc36783e2011-05-08 20:32:23 +0000364 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000365 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000366 E->arg_begin() + 1, E->arg_end());
367}
368
Peter Collingbournefe883422011-10-06 18:29:37 +0000369RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
370 ReturnValueSlot ReturnValue) {
371 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
372}
373
Eli Friedmanfde961d2011-10-14 02:27:24 +0000374static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
375 llvm::Value *DestPtr,
376 const CXXRecordDecl *Base) {
377 if (Base->isEmpty())
378 return;
379
380 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
381
382 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
383 CharUnits Size = Layout.getNonVirtualSize();
384 CharUnits Align = Layout.getNonVirtualAlign();
385
386 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
387
388 // If the type contains a pointer to data member we can't memset it to zero.
389 // Instead, create a null constant and copy it to the destination.
390 // TODO: there are other patterns besides zero that we can usefully memset,
391 // like -1, which happens to be the pattern used by member-pointers.
392 // TODO: isZeroInitializable can be over-conservative in the case where a
393 // virtual base contains a member pointer.
394 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
395 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
396
397 llvm::GlobalVariable *NullVariable =
398 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
399 /*isConstant=*/true,
400 llvm::GlobalVariable::PrivateLinkage,
401 NullConstant, Twine());
402 NullVariable->setAlignment(Align.getQuantity());
403 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
404
405 // Get and call the appropriate llvm.memcpy overload.
406 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
407 return;
408 }
409
410 // Otherwise, just memset the whole thing to zero. This is legal
411 // because in LLVM, all default initializers (other than the ones we just
412 // handled above) are guaranteed to have a bit pattern of all zeros.
413 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
414 Align.getQuantity());
415}
416
Anders Carlsson27da15b2010-01-01 20:29:01 +0000417void
John McCall7a626f62010-09-15 10:14:12 +0000418CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
419 AggValueSlot Dest) {
420 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000421 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000422
423 // If we require zero initialization before (or instead of) calling the
424 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000425 // constructor, emit the zero initialization now, unless destination is
426 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000427 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
428 switch (E->getConstructionKind()) {
429 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000430 case CXXConstructExpr::CK_Complete:
431 EmitNullInitialization(Dest.getAddr(), E->getType());
432 break;
433 case CXXConstructExpr::CK_VirtualBase:
434 case CXXConstructExpr::CK_NonVirtualBase:
435 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
436 break;
437 }
438 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000439
440 // If this is a call to a trivial default constructor, do nothing.
441 if (CD->isTrivial() && CD->isDefaultConstructor())
442 return;
443
John McCall8ea46b62010-09-18 00:58:34 +0000444 // Elide the constructor if we're constructing from a temporary.
445 // The temporary check is required because Sema sets this on NRVO
446 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000447 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000448 assert(getContext().hasSameUnqualifiedType(E->getType(),
449 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000450 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
451 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000452 return;
453 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000454 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000455
John McCallf677a8e2011-07-13 06:10:41 +0000456 if (const ConstantArrayType *arrayType
457 = getContext().getAsConstantArrayType(E->getType())) {
458 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000459 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000460 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000461 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000462 bool ForVirtualBase = false;
463
464 switch (E->getConstructionKind()) {
465 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000466 // We should be emitting a constructor; GlobalDecl will assert this
467 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000468 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000469
Alexis Hunt271c3682011-05-03 20:19:28 +0000470 case CXXConstructExpr::CK_Complete:
471 Type = Ctor_Complete;
472 break;
473
474 case CXXConstructExpr::CK_VirtualBase:
475 ForVirtualBase = true;
476 // fall-through
477
478 case CXXConstructExpr::CK_NonVirtualBase:
479 Type = Ctor_Base;
480 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000481
Anders Carlsson27da15b2010-01-01 20:29:01 +0000482 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000483 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000484 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000485 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000486}
487
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000488void
489CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
490 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000491 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000492 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000493 Exp = E->getSubExpr();
494 assert(isa<CXXConstructExpr>(Exp) &&
495 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
496 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
497 const CXXConstructorDecl *CD = E->getConstructor();
498 RunCleanupsScope Scope(*this);
499
500 // If we require zero initialization before (or instead of) calling the
501 // constructor, as can be the case with a non-user-provided default
502 // constructor, emit the zero initialization now.
503 // FIXME. Do I still need this for a copy ctor synthesis?
504 if (E->requiresZeroInitialization())
505 EmitNullInitialization(Dest, E->getType());
506
Chandler Carruth99da11c2010-11-15 13:54:43 +0000507 assert(!getContext().getAsConstantArrayType(E->getType())
508 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000509 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
510 E->arg_begin(), E->arg_end());
511}
512
John McCall8ed55a52010-09-02 09:58:18 +0000513static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
514 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000515 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000516 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000517
John McCall7ec4b432011-05-16 01:05:12 +0000518 // No cookie is required if the operator new[] being used is the
519 // reserved placement operator new[].
520 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000521 return CharUnits::Zero();
522
John McCall284c48f2011-01-27 09:37:56 +0000523 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000524}
525
John McCall036f2f62011-05-15 07:14:44 +0000526static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
527 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000528 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000529 llvm::Value *&numElements,
530 llvm::Value *&sizeWithoutCookie) {
531 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000532
John McCall036f2f62011-05-15 07:14:44 +0000533 if (!e->isArray()) {
534 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
535 sizeWithoutCookie
536 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
537 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000538 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000539
John McCall036f2f62011-05-15 07:14:44 +0000540 // The width of size_t.
541 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
542
John McCall8ed55a52010-09-02 09:58:18 +0000543 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000544 llvm::APInt cookieSize(sizeWidth,
545 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000546
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000547 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000548 // We multiply the size of all dimensions for NumElements.
549 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000550 numElements = CGF.EmitScalarExpr(e->getArraySize());
551 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000552
John McCall036f2f62011-05-15 07:14:44 +0000553 // The number of elements can be have an arbitrary integer type;
554 // essentially, we need to multiply it by a constant factor, add a
555 // cookie size, and verify that the result is representable as a
556 // size_t. That's just a gloss, though, and it's wrong in one
557 // important way: if the count is negative, it's an error even if
558 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000559 bool isSigned
560 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000561 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000562 = cast<llvm::IntegerType>(numElements->getType());
563 unsigned numElementsWidth = numElementsType->getBitWidth();
564
565 // Compute the constant factor.
566 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000567 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000568 = CGF.getContext().getAsConstantArrayType(type)) {
569 type = CAT->getElementType();
570 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000571 }
572
John McCall036f2f62011-05-15 07:14:44 +0000573 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
574 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
575 typeSizeMultiplier *= arraySizeMultiplier;
576
577 // This will be a size_t.
578 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000579
Chris Lattner32ac5832010-07-20 21:55:52 +0000580 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
581 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000582 if (llvm::ConstantInt *numElementsC =
583 dyn_cast<llvm::ConstantInt>(numElements)) {
584 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000585
John McCall036f2f62011-05-15 07:14:44 +0000586 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000587
John McCall036f2f62011-05-15 07:14:44 +0000588 // If 'count' was a negative number, it's an overflow.
589 if (isSigned && count.isNegative())
590 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000591
John McCall036f2f62011-05-15 07:14:44 +0000592 // We want to do all this arithmetic in size_t. If numElements is
593 // wider than that, check whether it's already too big, and if so,
594 // overflow.
595 else if (numElementsWidth > sizeWidth &&
596 numElementsWidth - sizeWidth > count.countLeadingZeros())
597 hasAnyOverflow = true;
598
599 // Okay, compute a count at the right width.
600 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
601
Sebastian Redlf862eb62012-02-22 17:37:52 +0000602 // If there is a brace-initializer, we cannot allocate fewer elements than
603 // there are initializers. If we do, that's treated like an overflow.
604 if (adjustedCount.ult(minElements))
605 hasAnyOverflow = true;
606
John McCall036f2f62011-05-15 07:14:44 +0000607 // Scale numElements by that. This might overflow, but we don't
608 // care because it only overflows if allocationSize does, too, and
609 // if that overflows then we shouldn't use this.
610 numElements = llvm::ConstantInt::get(CGF.SizeTy,
611 adjustedCount * arraySizeMultiplier);
612
613 // Compute the size before cookie, and track whether it overflowed.
614 bool overflow;
615 llvm::APInt allocationSize
616 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
617 hasAnyOverflow |= overflow;
618
619 // Add in the cookie, and check whether it's overflowed.
620 if (cookieSize != 0) {
621 // Save the current size without a cookie. This shouldn't be
622 // used if there was overflow.
623 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
624
625 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
626 hasAnyOverflow |= overflow;
627 }
628
629 // On overflow, produce a -1 so operator new will fail.
630 if (hasAnyOverflow) {
631 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
632 } else {
633 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
634 }
635
636 // Otherwise, we might need to use the overflow intrinsics.
637 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000638 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000639 // 1) if isSigned, we need to check whether numElements is negative;
640 // 2) if numElementsWidth > sizeWidth, we need to check whether
641 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000642 // 3) if minElements > 0, we need to check whether numElements is smaller
643 // than that.
644 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000645 // sizeWithoutCookie := numElements * typeSizeMultiplier
646 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000647 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000648 // size := sizeWithoutCookie + cookieSize
649 // and check whether it overflows.
650
651 llvm::Value *hasOverflow = 0;
652
653 // If numElementsWidth > sizeWidth, then one way or another, we're
654 // going to have to do a comparison for (2), and this happens to
655 // take care of (1), too.
656 if (numElementsWidth > sizeWidth) {
657 llvm::APInt threshold(numElementsWidth, 1);
658 threshold <<= sizeWidth;
659
660 llvm::Value *thresholdV
661 = llvm::ConstantInt::get(numElementsType, threshold);
662
663 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
664 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
665
666 // Otherwise, if we're signed, we want to sext up to size_t.
667 } else if (isSigned) {
668 if (numElementsWidth < sizeWidth)
669 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
670
671 // If there's a non-1 type size multiplier, then we can do the
672 // signedness check at the same time as we do the multiply
673 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000674 // unsigned overflow. Otherwise, we have to do it here. But at least
675 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000676 if (typeSizeMultiplier == 1)
677 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000678 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000679
680 // Otherwise, zext up to size_t if necessary.
681 } else if (numElementsWidth < sizeWidth) {
682 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
683 }
684
685 assert(numElements->getType() == CGF.SizeTy);
686
Sebastian Redlf862eb62012-02-22 17:37:52 +0000687 if (minElements) {
688 // Don't allow allocation of fewer elements than we have initializers.
689 if (!hasOverflow) {
690 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
691 llvm::ConstantInt::get(CGF.SizeTy, minElements));
692 } else if (numElementsWidth > sizeWidth) {
693 // The other existing overflow subsumes this check.
694 // We do an unsigned comparison, since any signed value < -1 is
695 // taken care of either above or below.
696 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
697 CGF.Builder.CreateICmpULT(numElements,
698 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
699 }
700 }
701
John McCall036f2f62011-05-15 07:14:44 +0000702 size = numElements;
703
704 // Multiply by the type size if necessary. This multiplier
705 // includes all the factors for nested arrays.
706 //
707 // This step also causes numElements to be scaled up by the
708 // nested-array factor if necessary. Overflow on this computation
709 // can be ignored because the result shouldn't be used if
710 // allocation fails.
711 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000712 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000713 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000714
715 llvm::Value *tsmV =
716 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
717 llvm::Value *result =
718 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
719
720 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
721 if (hasOverflow)
722 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
723 else
724 hasOverflow = overflowed;
725
726 size = CGF.Builder.CreateExtractValue(result, 0);
727
728 // Also scale up numElements by the array size multiplier.
729 if (arraySizeMultiplier != 1) {
730 // If the base element type size is 1, then we can re-use the
731 // multiply we just did.
732 if (typeSize.isOne()) {
733 assert(arraySizeMultiplier == typeSizeMultiplier);
734 numElements = size;
735
736 // Otherwise we need a separate multiply.
737 } else {
738 llvm::Value *asmV =
739 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
740 numElements = CGF.Builder.CreateMul(numElements, asmV);
741 }
742 }
743 } else {
744 // numElements doesn't need to be scaled.
745 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000746 }
747
John McCall036f2f62011-05-15 07:14:44 +0000748 // Add in the cookie size if necessary.
749 if (cookieSize != 0) {
750 sizeWithoutCookie = size;
751
John McCall036f2f62011-05-15 07:14:44 +0000752 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000753 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000754
755 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
756 llvm::Value *result =
757 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
758
759 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
760 if (hasOverflow)
761 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
762 else
763 hasOverflow = overflowed;
764
765 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000766 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000767
John McCall036f2f62011-05-15 07:14:44 +0000768 // If we had any possibility of dynamic overflow, make a select to
769 // overwrite 'size' with an all-ones value, which should cause
770 // operator new to throw.
771 if (hasOverflow)
772 size = CGF.Builder.CreateSelect(hasOverflow,
773 llvm::Constant::getAllOnesValue(CGF.SizeTy),
774 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000775 }
John McCall8ed55a52010-09-02 09:58:18 +0000776
John McCall036f2f62011-05-15 07:14:44 +0000777 if (cookieSize == 0)
778 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000779 else
John McCall036f2f62011-05-15 07:14:44 +0000780 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000781
John McCall036f2f62011-05-15 07:14:44 +0000782 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000783}
784
Sebastian Redlf862eb62012-02-22 17:37:52 +0000785static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
786 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000787
Eli Friedman38cd36d2011-12-03 02:13:40 +0000788 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000789 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000790 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000791 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000792 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000793 else if (AllocType->isAnyComplexType())
794 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
795 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000796 else {
797 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000798 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000799 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000800 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000801 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000802 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000803
804 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000805 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000806}
807
808void
809CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000810 QualType elementType,
811 llvm::Value *beginPtr,
812 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000813 if (!E->hasInitializer())
814 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000815
Sebastian Redlf862eb62012-02-22 17:37:52 +0000816 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000817 // Find the end of the array, hoisted out of the loop.
818 llvm::Value *endPtr =
819 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
820
Sebastian Redlf862eb62012-02-22 17:37:52 +0000821 unsigned initializerElements = 0;
822
823 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000824 llvm::AllocaInst *endOfInit = 0;
825 QualType::DestructionKind dtorKind = elementType.isDestructedType();
826 EHScopeStack::stable_iterator cleanup;
827 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000828 // If the initializer is an initializer list, first do the explicit elements.
829 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
830 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000831
832 // Enter a partial-destruction cleanup if necessary.
833 if (needsEHCleanup(dtorKind)) {
834 // In principle we could tell the cleanup where we are more
835 // directly, but the control flow can get so varied here that it
836 // would actually be quite complex. Therefore we go through an
837 // alloca.
838 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
839 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
840 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
841 getDestroyer(dtorKind));
842 cleanup = EHStack.stable_begin();
843 }
844
Sebastian Redlf862eb62012-02-22 17:37:52 +0000845 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000846 // Tell the cleanup that it needs to destroy up to this
847 // element. TODO: some of these stores can be trivially
848 // observed to be unnecessary.
849 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000850 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
851 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
852 }
853
854 // The remaining elements are filled with the array filler expression.
855 Init = ILE->getArrayFiller();
856 }
857
John McCall99210dc2011-09-15 06:49:18 +0000858 // Create the continuation block.
859 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
860
Sebastian Redlf862eb62012-02-22 17:37:52 +0000861 // If the number of elements isn't constant, we have to now check if there is
862 // anything left to initialize.
863 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
864 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000865 if (constNum->getZExtValue() <= initializerElements) {
866 // If there was a cleanup, deactivate it.
867 if (cleanupDominator)
868 DeactivateCleanupBlock(cleanup, cleanupDominator);;
869 return;
870 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000871 } else {
John McCall99210dc2011-09-15 06:49:18 +0000872 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000873 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000874 "array.isempty");
875 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
876 EmitBlock(nonEmptyBB);
877 }
878
879 // Enter the loop.
880 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
881 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
882
883 EmitBlock(loopBB);
884
885 // Set up the current-element phi.
886 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000887 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
888 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000889
Chad Rosierf62290a2012-02-24 00:13:55 +0000890 // Store the new cleanup position for irregular cleanups.
891 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
892
John McCall99210dc2011-09-15 06:49:18 +0000893 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000894 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000895 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
896 getDestroyer(dtorKind));
897 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000898 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000899 }
900
901 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000902 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000903
904 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000905 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000906 DeactivateCleanupBlock(cleanup, cleanupDominator);
907 cleanupDominator->eraseFromParent();
908 }
John McCall99210dc2011-09-15 06:49:18 +0000909
910 // Advance to the next element.
911 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
912
913 // Check whether we've gotten to the end of the array and, if so,
914 // exit the loop.
915 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
916 Builder.CreateCondBr(isEnd, contBB, loopBB);
917 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
918
919 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000920}
921
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000922static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
923 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000924 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000925 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000926 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000927 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000928}
929
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000930static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000931 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000932 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000933 llvm::Value *NumElements,
934 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000935 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000936 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000937 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
938 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000939 bool RequiresZeroInitialization = false;
Douglas Gregord1531032012-02-23 17:07:43 +0000940 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000941 // If new expression did not specify value-initialization, then there
942 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000943 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000944 return;
945
John McCall99210dc2011-09-15 06:49:18 +0000946 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000947 // Optimization: since zero initialization will just set the memory
948 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000949 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000950 return;
951 }
952
953 RequiresZeroInitialization = true;
954 }
John McCallf677a8e2011-07-13 06:10:41 +0000955
Sebastian Redl6047f072012-02-16 12:22:20 +0000956 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
957 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000958 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000959 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000960 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000961 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000962 // Optimization: since zero initialization will just set the memory
963 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000964 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
965 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000966 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000967 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
968 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000969 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000970
Sebastian Redl6047f072012-02-16 12:22:20 +0000971 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000972 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000973
Sebastian Redlf862eb62012-02-22 17:37:52 +0000974 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000975}
976
John McCall824c2f52010-09-14 07:57:04 +0000977namespace {
978 /// A cleanup to call the given 'operator delete' function upon
979 /// abnormal exit from a new expression.
980 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
981 size_t NumPlacementArgs;
982 const FunctionDecl *OperatorDelete;
983 llvm::Value *Ptr;
984 llvm::Value *AllocSize;
985
986 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
987
988 public:
989 static size_t getExtraSize(size_t NumPlacementArgs) {
990 return NumPlacementArgs * sizeof(RValue);
991 }
992
993 CallDeleteDuringNew(size_t NumPlacementArgs,
994 const FunctionDecl *OperatorDelete,
995 llvm::Value *Ptr,
996 llvm::Value *AllocSize)
997 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
998 Ptr(Ptr), AllocSize(AllocSize) {}
999
1000 void setPlacementArg(unsigned I, RValue Arg) {
1001 assert(I < NumPlacementArgs && "index out of range");
1002 getPlacementArgs()[I] = Arg;
1003 }
1004
John McCall30317fd2011-07-12 20:27:29 +00001005 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +00001006 const FunctionProtoType *FPT
1007 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1008 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +00001009 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001010
1011 CallArgList DeleteArgs;
1012
1013 // The first argument is always a void*.
1014 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001015 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001016
1017 // A member 'operator delete' can take an extra 'size_t' argument.
1018 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001019 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001020
1021 // Pass the rest of the arguments, which must match exactly.
1022 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001023 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001024
1025 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001026 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +00001027 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1028 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1029 }
1030 };
John McCall7f9c92a2010-09-17 00:50:28 +00001031
1032 /// A cleanup to call the given 'operator delete' function upon
1033 /// abnormal exit from a new expression when the new expression is
1034 /// conditional.
1035 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1036 size_t NumPlacementArgs;
1037 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001038 DominatingValue<RValue>::saved_type Ptr;
1039 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001040
John McCallcb5f77f2011-01-28 10:53:53 +00001041 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1042 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001043 }
1044
1045 public:
1046 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001047 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001048 }
1049
1050 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1051 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001052 DominatingValue<RValue>::saved_type Ptr,
1053 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001054 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1055 Ptr(Ptr), AllocSize(AllocSize) {}
1056
John McCallcb5f77f2011-01-28 10:53:53 +00001057 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001058 assert(I < NumPlacementArgs && "index out of range");
1059 getPlacementArgs()[I] = Arg;
1060 }
1061
John McCall30317fd2011-07-12 20:27:29 +00001062 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001063 const FunctionProtoType *FPT
1064 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1065 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1066 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1067
1068 CallArgList DeleteArgs;
1069
1070 // The first argument is always a void*.
1071 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001072 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001073
1074 // A member 'operator delete' can take an extra 'size_t' argument.
1075 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001076 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001077 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001078 }
1079
1080 // Pass the rest of the arguments, which must match exactly.
1081 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001082 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001083 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001084 }
1085
1086 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001087 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001088 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1089 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1090 }
1091 };
1092}
1093
1094/// Enter a cleanup to call 'operator delete' if the initializer in a
1095/// new-expression throws.
1096static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1097 const CXXNewExpr *E,
1098 llvm::Value *NewPtr,
1099 llvm::Value *AllocSize,
1100 const CallArgList &NewArgs) {
1101 // If we're not inside a conditional branch, then the cleanup will
1102 // dominate and we can do the easier (and more efficient) thing.
1103 if (!CGF.isInConditionalBranch()) {
1104 CallDeleteDuringNew *Cleanup = CGF.EHStack
1105 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1106 E->getNumPlacementArgs(),
1107 E->getOperatorDelete(),
1108 NewPtr, AllocSize);
1109 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001110 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001111
1112 return;
1113 }
1114
1115 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001116 DominatingValue<RValue>::saved_type SavedNewPtr =
1117 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1118 DominatingValue<RValue>::saved_type SavedAllocSize =
1119 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001120
1121 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001122 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001123 E->getNumPlacementArgs(),
1124 E->getOperatorDelete(),
1125 SavedNewPtr,
1126 SavedAllocSize);
1127 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001128 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001129 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001130
John McCallf4beacd2011-11-10 10:43:54 +00001131 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001132}
1133
Anders Carlssoncc52f652009-09-22 22:53:17 +00001134llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001135 // The element type being allocated.
1136 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001137
John McCall75f94982011-03-07 03:12:35 +00001138 // 1. Build a call to the allocation function.
1139 FunctionDecl *allocator = E->getOperatorNew();
1140 const FunctionProtoType *allocatorType =
1141 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001142
John McCall75f94982011-03-07 03:12:35 +00001143 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001144
1145 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001146 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001147
Sebastian Redlf862eb62012-02-22 17:37:52 +00001148 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1149 unsigned minElements = 0;
1150 if (E->isArray() && E->hasInitializer()) {
1151 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1152 minElements = ILE->getNumInits();
1153 }
1154
John McCall75f94982011-03-07 03:12:35 +00001155 llvm::Value *numElements = 0;
1156 llvm::Value *allocSizeWithoutCookie = 0;
1157 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001158 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1159 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001160
Eli Friedman43dca6a2011-05-02 17:57:46 +00001161 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001162
1163 // Emit the rest of the arguments.
1164 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001165 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001166
1167 // First, use the types from the function type.
1168 // We start at 1 here because the first argument (the allocation size)
1169 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001170 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1171 ++i, ++placementArg) {
1172 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001173
John McCall75f94982011-03-07 03:12:35 +00001174 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1175 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001176 "type mismatch in call argument!");
1177
John McCall32ea9692011-03-11 20:59:21 +00001178 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001179 }
1180
1181 // Either we've emitted all the call args, or we have a call to a
1182 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001183 assert((placementArg == E->placement_arg_end() ||
1184 allocatorType->isVariadic()) &&
1185 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001186
1187 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001188 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1189 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001190 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001191 }
1192
John McCall7ec4b432011-05-16 01:05:12 +00001193 // Emit the allocation call. If the allocator is a global placement
1194 // operator, just "inline" it directly.
1195 RValue RV;
1196 if (allocator->isReservedGlobalPlacementOperator()) {
1197 assert(allocatorArgs.size() == 2);
1198 RV = allocatorArgs[1].RV;
1199 // TODO: kill any unnecessary computations done for the size
1200 // argument.
1201 } else {
John McCalla729c622012-02-17 03:33:10 +00001202 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1203 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001204 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1205 allocatorArgs, allocator);
1206 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001207
John McCall75f94982011-03-07 03:12:35 +00001208 // Emit a null check on the allocation result if the allocation
1209 // function is allowed to return null (because it has a non-throwing
1210 // exception spec; for this part, we inline
1211 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1212 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001213 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001214 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001215
John McCall75f94982011-03-07 03:12:35 +00001216 llvm::BasicBlock *nullCheckBB = 0;
1217 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001218
John McCall75f94982011-03-07 03:12:35 +00001219 llvm::Value *allocation = RV.getScalarVal();
1220 unsigned AS =
1221 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001222
John McCallf7dcf322011-03-07 01:52:56 +00001223 // The null-check means that the initializer is conditionally
1224 // evaluated.
1225 ConditionalEvaluation conditional(*this);
1226
John McCall75f94982011-03-07 03:12:35 +00001227 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001228 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001229
1230 nullCheckBB = Builder.GetInsertBlock();
1231 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1232 contBB = createBasicBlock("new.cont");
1233
1234 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1235 Builder.CreateCondBr(isNull, contBB, notNullBB);
1236 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001237 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001238
John McCall824c2f52010-09-14 07:57:04 +00001239 // If there's an operator delete, enter a cleanup to call it if an
1240 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001241 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001242 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001243 if (E->getOperatorDelete() &&
1244 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001245 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1246 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001247 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001248 }
1249
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001250 assert((allocSize == allocSizeWithoutCookie) ==
1251 CalculateCookiePadding(*this, E).isZero());
1252 if (allocSize != allocSizeWithoutCookie) {
1253 assert(E->isArray());
1254 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1255 numElements,
1256 E, allocType);
1257 }
1258
Chris Lattner2192fe52011-07-18 04:24:23 +00001259 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001260 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1261 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001262
John McCall99210dc2011-09-15 06:49:18 +00001263 EmitNewInitializer(*this, E, allocType, result, numElements,
1264 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001265 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001266 // NewPtr is a pointer to the base element type. If we're
1267 // allocating an array of arrays, we'll need to cast back to the
1268 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001269 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001270 if (result->getType() != resultType)
1271 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001272 }
John McCall824c2f52010-09-14 07:57:04 +00001273
1274 // Deactivate the 'operator delete' cleanup if we finished
1275 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001276 if (operatorDeleteCleanup.isValid()) {
1277 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1278 cleanupDominator->eraseFromParent();
1279 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001280
John McCall75f94982011-03-07 03:12:35 +00001281 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001282 conditional.end(*this);
1283
John McCall75f94982011-03-07 03:12:35 +00001284 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1285 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001286
Jay Foad20c0f022011-03-30 11:28:58 +00001287 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001288 PHI->addIncoming(result, notNullBB);
1289 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1290 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001291
John McCall75f94982011-03-07 03:12:35 +00001292 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001293 }
John McCall8ed55a52010-09-02 09:58:18 +00001294
John McCall75f94982011-03-07 03:12:35 +00001295 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001296}
1297
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001298void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1299 llvm::Value *Ptr,
1300 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001301 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1302
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001303 const FunctionProtoType *DeleteFTy =
1304 DeleteFD->getType()->getAs<FunctionProtoType>();
1305
1306 CallArgList DeleteArgs;
1307
Anders Carlsson21122cf2009-12-13 20:04:38 +00001308 // Check if we need to pass the size to the delete operator.
1309 llvm::Value *Size = 0;
1310 QualType SizeTy;
1311 if (DeleteFTy->getNumArgs() == 2) {
1312 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001313 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1314 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1315 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001316 }
1317
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001318 QualType ArgTy = DeleteFTy->getArgType(0);
1319 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001320 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001321
Anders Carlsson21122cf2009-12-13 20:04:38 +00001322 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001323 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001324
1325 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001326 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001327 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001328 DeleteArgs, DeleteFD);
1329}
1330
John McCall8ed55a52010-09-02 09:58:18 +00001331namespace {
1332 /// Calls the given 'operator delete' on a single object.
1333 struct CallObjectDelete : EHScopeStack::Cleanup {
1334 llvm::Value *Ptr;
1335 const FunctionDecl *OperatorDelete;
1336 QualType ElementType;
1337
1338 CallObjectDelete(llvm::Value *Ptr,
1339 const FunctionDecl *OperatorDelete,
1340 QualType ElementType)
1341 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1342
John McCall30317fd2011-07-12 20:27:29 +00001343 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001344 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1345 }
1346 };
1347}
1348
1349/// Emit the code for deleting a single object.
1350static void EmitObjectDelete(CodeGenFunction &CGF,
1351 const FunctionDecl *OperatorDelete,
1352 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001353 QualType ElementType,
1354 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001355 // Find the destructor for the type, if applicable. If the
1356 // destructor is virtual, we'll just emit the vcall and return.
1357 const CXXDestructorDecl *Dtor = 0;
1358 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1359 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001360 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001361 Dtor = RD->getDestructor();
1362
1363 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001364 if (UseGlobalDelete) {
1365 // If we're supposed to call the global delete, make sure we do so
1366 // even if the destructor throws.
1367 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1368 Ptr, OperatorDelete,
1369 ElementType);
1370 }
1371
Chris Lattner2192fe52011-07-18 04:24:23 +00001372 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001373 CGF.getTypes().GetFunctionType(
1374 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001375
1376 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001377 = CGF.BuildVirtualCall(Dtor,
1378 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1379 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001380 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1381 0, 0);
1382
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001383 if (UseGlobalDelete) {
1384 CGF.PopCleanupBlock();
1385 }
1386
John McCall8ed55a52010-09-02 09:58:18 +00001387 return;
1388 }
1389 }
1390 }
1391
1392 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001393 // This doesn't have to a conditional cleanup because we're going
1394 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001395 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1396 Ptr, OperatorDelete, ElementType);
1397
1398 if (Dtor)
1399 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1400 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001401 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001402 ElementType->isObjCLifetimeType()) {
1403 switch (ElementType.getObjCLifetime()) {
1404 case Qualifiers::OCL_None:
1405 case Qualifiers::OCL_ExplicitNone:
1406 case Qualifiers::OCL_Autoreleasing:
1407 break;
John McCall8ed55a52010-09-02 09:58:18 +00001408
John McCall31168b02011-06-15 23:02:42 +00001409 case Qualifiers::OCL_Strong: {
1410 // Load the pointer value.
1411 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1412 ElementType.isVolatileQualified());
1413
1414 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1415 break;
1416 }
1417
1418 case Qualifiers::OCL_Weak:
1419 CGF.EmitARCDestroyWeak(Ptr);
1420 break;
1421 }
1422 }
1423
John McCall8ed55a52010-09-02 09:58:18 +00001424 CGF.PopCleanupBlock();
1425}
1426
1427namespace {
1428 /// Calls the given 'operator delete' on an array of objects.
1429 struct CallArrayDelete : EHScopeStack::Cleanup {
1430 llvm::Value *Ptr;
1431 const FunctionDecl *OperatorDelete;
1432 llvm::Value *NumElements;
1433 QualType ElementType;
1434 CharUnits CookieSize;
1435
1436 CallArrayDelete(llvm::Value *Ptr,
1437 const FunctionDecl *OperatorDelete,
1438 llvm::Value *NumElements,
1439 QualType ElementType,
1440 CharUnits CookieSize)
1441 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1442 ElementType(ElementType), CookieSize(CookieSize) {}
1443
John McCall30317fd2011-07-12 20:27:29 +00001444 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001445 const FunctionProtoType *DeleteFTy =
1446 OperatorDelete->getType()->getAs<FunctionProtoType>();
1447 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1448
1449 CallArgList Args;
1450
1451 // Pass the pointer as the first argument.
1452 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1453 llvm::Value *DeletePtr
1454 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001455 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001456
1457 // Pass the original requested size as the second argument.
1458 if (DeleteFTy->getNumArgs() == 2) {
1459 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001460 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001461 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1462
1463 CharUnits ElementTypeSize =
1464 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1465
1466 // The size of an element, multiplied by the number of elements.
1467 llvm::Value *Size
1468 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1469 Size = CGF.Builder.CreateMul(Size, NumElements);
1470
1471 // Plus the size of the cookie if applicable.
1472 if (!CookieSize.isZero()) {
1473 llvm::Value *CookieSizeV
1474 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1475 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1476 }
1477
Eli Friedman43dca6a2011-05-02 17:57:46 +00001478 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001479 }
1480
1481 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001482 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001483 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1484 ReturnValueSlot(), Args, OperatorDelete);
1485 }
1486 };
1487}
1488
1489/// Emit the code for deleting an array of objects.
1490static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001491 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001492 llvm::Value *deletedPtr,
1493 QualType elementType) {
1494 llvm::Value *numElements = 0;
1495 llvm::Value *allocatedPtr = 0;
1496 CharUnits cookieSize;
1497 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1498 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001499
John McCallca2c56f2011-07-13 01:41:37 +00001500 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001501
1502 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001503 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001504 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001505 allocatedPtr, operatorDelete,
1506 numElements, elementType,
1507 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001508
John McCallca2c56f2011-07-13 01:41:37 +00001509 // Destroy the elements.
1510 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1511 assert(numElements && "no element count for a type with a destructor!");
1512
John McCallca2c56f2011-07-13 01:41:37 +00001513 llvm::Value *arrayEnd =
1514 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001515
1516 // Note that it is legal to allocate a zero-length array, and we
1517 // can never fold the check away because the length should always
1518 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001519 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1520 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001521 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001522 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001523 }
1524
John McCallca2c56f2011-07-13 01:41:37 +00001525 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001526 CGF.PopCleanupBlock();
1527}
1528
Anders Carlssoncc52f652009-09-22 22:53:17 +00001529void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001530
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001531 // Get at the argument before we performed the implicit conversion
1532 // to void*.
1533 const Expr *Arg = E->getArgument();
1534 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001535 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001536 ICE->getType()->isVoidPointerType())
1537 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001538 else
1539 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001540 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001541
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001542 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001543
1544 // Null check the pointer.
1545 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1546 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1547
Anders Carlsson98981b12011-04-11 00:30:07 +00001548 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001549
1550 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1551 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001552
John McCall8ed55a52010-09-02 09:58:18 +00001553 // We might be deleting a pointer to array. If so, GEP down to the
1554 // first non-array element.
1555 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1556 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1557 if (DeleteTy->isConstantArrayType()) {
1558 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001559 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001560
1561 GEP.push_back(Zero); // point at the outermost array
1562
1563 // For each layer of array type we're pointing at:
1564 while (const ConstantArrayType *Arr
1565 = getContext().getAsConstantArrayType(DeleteTy)) {
1566 // 1. Unpeel the array type.
1567 DeleteTy = Arr->getElementType();
1568
1569 // 2. GEP to the first element of the array.
1570 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001571 }
John McCall8ed55a52010-09-02 09:58:18 +00001572
Jay Foad040dd822011-07-22 08:16:57 +00001573 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001574 }
1575
Douglas Gregor04f36212010-09-02 17:38:50 +00001576 assert(ConvertTypeForMem(DeleteTy) ==
1577 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001578
1579 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001580 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001581 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001582 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1583 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001584 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001585
Anders Carlssoncc52f652009-09-22 22:53:17 +00001586 EmitBlock(DeleteEnd);
1587}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001588
Anders Carlsson0c633502011-04-11 14:13:40 +00001589static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1590 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001591 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001592
1593 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1594}
1595
1596static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001597 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001598 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001599 CGF.Builder.CreateUnreachable();
1600}
1601
Anders Carlsson940f02d2011-04-18 00:57:03 +00001602static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1603 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001604 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001605 // Get the vtable pointer.
1606 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1607
1608 // C++ [expr.typeid]p2:
1609 // If the glvalue expression is obtained by applying the unary * operator to
1610 // a pointer and the pointer is a null pointer value, the typeid expression
1611 // throws the std::bad_typeid exception.
1612 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1613 if (UO->getOpcode() == UO_Deref) {
1614 llvm::BasicBlock *BadTypeidBlock =
1615 CGF.createBasicBlock("typeid.bad_typeid");
1616 llvm::BasicBlock *EndBlock =
1617 CGF.createBasicBlock("typeid.end");
1618
1619 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1620 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1621
1622 CGF.EmitBlock(BadTypeidBlock);
1623 EmitBadTypeidCall(CGF);
1624 CGF.EmitBlock(EndBlock);
1625 }
1626 }
1627
1628 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1629 StdTypeInfoPtrTy->getPointerTo());
1630
1631 // Load the type info.
1632 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1633 return CGF.Builder.CreateLoad(Value);
1634}
1635
John McCalle4df6c82011-01-28 08:37:24 +00001636llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001637 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001638 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001639
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001640 if (E->isTypeOperand()) {
1641 llvm::Constant *TypeInfo =
1642 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001643 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001644 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001645
Anders Carlsson940f02d2011-04-18 00:57:03 +00001646 // C++ [expr.typeid]p2:
1647 // When typeid is applied to a glvalue expression whose type is a
1648 // polymorphic class type, the result refers to a std::type_info object
1649 // representing the type of the most derived object (that is, the dynamic
1650 // type) to which the glvalue refers.
1651 if (E->getExprOperand()->isGLValue()) {
1652 if (const RecordType *RT =
1653 E->getExprOperand()->getType()->getAs<RecordType>()) {
1654 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1655 if (RD->isPolymorphic())
1656 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1657 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001658 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001659 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001660
1661 QualType OperandTy = E->getExprOperand()->getType();
1662 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1663 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001664}
Mike Stump65511702009-11-16 06:50:58 +00001665
Anders Carlsson882d7902011-04-11 00:46:40 +00001666static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1667 // void *__dynamic_cast(const void *sub,
1668 // const abi::__class_type_info *src,
1669 // const abi::__class_type_info *dst,
1670 // std::ptrdiff_t src2dst_offset);
1671
Chris Lattnerece04092012-02-07 00:39:47 +00001672 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001673 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001674 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1675
Chris Lattnera5f58b02011-07-09 17:41:47 +00001676 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001677
Chris Lattner2192fe52011-07-18 04:24:23 +00001678 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001679 llvm::FunctionType::get(Int8PtrTy, Args, false);
1680
1681 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1682}
1683
1684static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1685 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001686 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001687 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1688}
1689
Anders Carlssonc1c99712011-04-11 01:45:29 +00001690static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001691 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001692 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001693 CGF.Builder.CreateUnreachable();
1694}
1695
Anders Carlsson882d7902011-04-11 00:46:40 +00001696static llvm::Value *
1697EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1698 QualType SrcTy, QualType DestTy,
1699 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001700 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001701 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001702 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001703
1704 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1705 if (PTy->getPointeeType()->isVoidType()) {
1706 // C++ [expr.dynamic.cast]p7:
1707 // If T is "pointer to cv void," then the result is a pointer to the
1708 // most derived object pointed to by v.
1709
1710 // Get the vtable pointer.
1711 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1712
1713 // Get the offset-to-top from the vtable.
1714 llvm::Value *OffsetToTop =
1715 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1716 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1717
1718 // Finally, add the offset to the pointer.
1719 Value = CGF.EmitCastToVoidPtr(Value);
1720 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1721
1722 return CGF.Builder.CreateBitCast(Value, DestLTy);
1723 }
1724 }
1725
1726 QualType SrcRecordTy;
1727 QualType DestRecordTy;
1728
1729 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1730 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1731 DestRecordTy = DestPTy->getPointeeType();
1732 } else {
1733 SrcRecordTy = SrcTy;
1734 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1735 }
1736
1737 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1738 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1739
1740 llvm::Value *SrcRTTI =
1741 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1742 llvm::Value *DestRTTI =
1743 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1744
1745 // FIXME: Actually compute a hint here.
1746 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1747
1748 // Emit the call to __dynamic_cast.
1749 Value = CGF.EmitCastToVoidPtr(Value);
1750 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1751 SrcRTTI, DestRTTI, OffsetHint);
1752 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1753
1754 /// C++ [expr.dynamic.cast]p9:
1755 /// A failed cast to reference type throws std::bad_cast
1756 if (DestTy->isReferenceType()) {
1757 llvm::BasicBlock *BadCastBlock =
1758 CGF.createBasicBlock("dynamic_cast.bad_cast");
1759
1760 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1761 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1762
1763 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001764 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001765 }
1766
1767 return Value;
1768}
1769
Anders Carlssonc1c99712011-04-11 01:45:29 +00001770static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1771 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001772 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001773 if (DestTy->isPointerType())
1774 return llvm::Constant::getNullValue(DestLTy);
1775
1776 /// C++ [expr.dynamic.cast]p9:
1777 /// A failed cast to reference type throws std::bad_cast
1778 EmitBadCastCall(CGF);
1779
1780 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1781 return llvm::UndefValue::get(DestLTy);
1782}
1783
Anders Carlsson882d7902011-04-11 00:46:40 +00001784llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001785 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001786 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001787
Anders Carlssonc1c99712011-04-11 01:45:29 +00001788 if (DCE->isAlwaysNull())
1789 return EmitDynamicCastToNull(*this, DestTy);
1790
1791 QualType SrcTy = DCE->getSubExpr()->getType();
1792
Anders Carlsson882d7902011-04-11 00:46:40 +00001793 // C++ [expr.dynamic.cast]p4:
1794 // If the value of v is a null pointer value in the pointer case, the result
1795 // is the null pointer value of type T.
1796 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001797
Anders Carlsson882d7902011-04-11 00:46:40 +00001798 llvm::BasicBlock *CastNull = 0;
1799 llvm::BasicBlock *CastNotNull = 0;
1800 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001801
Anders Carlsson882d7902011-04-11 00:46:40 +00001802 if (ShouldNullCheckSrcValue) {
1803 CastNull = createBasicBlock("dynamic_cast.null");
1804 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1805
1806 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1807 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1808 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001809 }
1810
Anders Carlsson882d7902011-04-11 00:46:40 +00001811 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1812
1813 if (ShouldNullCheckSrcValue) {
1814 EmitBranch(CastEnd);
1815
1816 EmitBlock(CastNull);
1817 EmitBranch(CastEnd);
1818 }
1819
1820 EmitBlock(CastEnd);
1821
1822 if (ShouldNullCheckSrcValue) {
1823 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1824 PHI->addIncoming(Value, CastNotNull);
1825 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1826
1827 Value = PHI;
1828 }
1829
1830 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001831}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001832
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001833void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001834 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001835 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1836 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001837
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001838 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1839 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1840 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001841 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001842 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001843
David Blaikie40ed2972012-06-06 20:45:41 +00001844 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001845 ArrayRef<VarDecl *> ArrayIndexes;
1846 if (CurField->getType()->isArrayType())
1847 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001848 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001849 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001850}