blob: 17e2bc18744c0729be1b2caa910e5a27a12c2d63 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-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 Patelc69e1cf2010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlsson16d81b82009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson3b5ad222010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson3b5ad222010-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
Richard Smith2c9f87c2012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
39 EmitCheck(CT_MemberCall, This, getContext().getRecordType(MD->getParent()));
40
Anders Carlsson3b5ad222010-01-01 20:29:01 +000041 CallArgList Args;
42
43 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000044 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000045
Anders Carlssonc997d422010-01-02 01:01:18 +000046 // If there is a VTT parameter, emit it.
47 if (VTT) {
48 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000049 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000050 }
John McCallde5d3c72012-02-17 03:33:10 +000051
52 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
53 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssonc997d422010-01-02 01:01:18 +000054
John McCallde5d3c72012-02-17 03:33:10 +000055 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000056 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
57
John McCall0f3d0972012-07-07 06:41:13 +000058 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000059 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000060}
61
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000062// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
63// quite what we want.
64static const Expr *skipNoOpCastsAndParens(const Expr *E) {
65 while (true) {
66 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
67 E = PE->getSubExpr();
68 continue;
69 }
70
71 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
72 if (CE->getCastKind() == CK_NoOp) {
73 E = CE->getSubExpr();
74 continue;
75 }
76 }
77 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
78 if (UO->getOpcode() == UO_Extension) {
79 E = UO->getSubExpr();
80 continue;
81 }
82 }
83 return E;
84 }
85}
86
Anders Carlsson3b5ad222010-01-01 20:29:01 +000087/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
88/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000089static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
90 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000091 const CXXMethodDecl *MD) {
92
Anders Carlsson1679f5a2011-01-29 03:52:01 +000093 // When building with -fapple-kext, all calls must go through the vtable since
94 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +000095 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000096 return false;
97
Anders Carlsson1679f5a2011-01-29 03:52:01 +000098 // If the most derived class is marked final, we know that no subclass can
99 // override this member function and so we can devirtualize it. For example:
100 //
101 // struct A { virtual void f(); }
102 // struct B final : A { };
103 //
104 // void f(B *b) {
105 // b->f();
106 // }
107 //
Rafael Espindola8d852e32012-06-27 18:18:05 +0000108 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000109 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
110 return true;
111
Anders Carlssonf89e0422011-01-23 21:07:30 +0000112 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000113 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000114 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000115 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000116
Anders Carlssonf89e0422011-01-23 21:07:30 +0000117 // Similarly, if the class itself is marked 'final' it can't be overridden
118 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000119 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000120 return true;
121
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000122 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000123 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
124 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
125 // This is a record decl. We know the type and can devirtualize it.
126 return VD->getType()->isRecordType();
127 }
128
129 return false;
130 }
Richard Smithac452932012-08-15 22:59:28 +0000131
132 // We can devirtualize calls on an object accessed by a class member access
133 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
134 // a derived class object constructed in the same location.
135 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
136 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
137 return VD->getType()->isRecordType();
138
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000139 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000140 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000141 return true;
142
143 // And calls on bound temporaries.
144 if (isa<CXXBindTemporaryExpr>(Base))
145 return true;
146
147 // Check if this is a call expr that returns a record type.
148 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
149 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000150
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000151 // We can't devirtualize the call.
152 return false;
153}
154
Rafael Espindolaea01d762012-06-28 14:28:57 +0000155static CXXRecordDecl *getCXXRecord(const Expr *E) {
156 QualType T = E->getType();
157 if (const PointerType *PTy = T->getAs<PointerType>())
158 T = PTy->getPointeeType();
159 const RecordType *Ty = T->castAs<RecordType>();
160 return cast<CXXRecordDecl>(Ty->getDecl());
161}
162
Francois Pichetdbee3412011-01-18 05:04:39 +0000163// Note: This function also emit constructor calls to support a MSVC
164// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000165RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
166 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000167 const Expr *callee = CE->getCallee()->IgnoreParens();
168
169 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000170 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000171
172 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
174
Devang Patelc69e1cf2010-09-30 19:05:55 +0000175 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000176 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel68020272010-10-22 18:56:27 +0000177 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000178 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
179 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
180 DI->getOrCreateRecordType(PTy->getPointeeType(),
181 MD->getParent()->getLocation());
182 }
183 }
184
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000185 if (MD->isStatic()) {
186 // The method is static, emit it as we would a regular call.
187 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
188 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
189 ReturnValue, CE->arg_begin(), CE->arg_end());
190 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000191
John McCallfc400282010-09-03 01:26:39 +0000192 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000193 const Expr *Base = ME->getBase();
194 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000195
Rafael Espindolaea01d762012-06-28 14:28:57 +0000196 const CXXMethodDecl *DevirtualizedMethod = NULL;
197 if (CanUseVirtualCall &&
198 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
199 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
200 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
201 assert(DevirtualizedMethod);
202 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
203 const Expr *Inner = Base->ignoreParenBaseCasts();
204 if (getCXXRecord(Inner) == DevirtualizedClass)
205 // If the class of the Inner expression is where the dynamic method
206 // is defined, build the this pointer from it.
207 Base = Inner;
208 else if (getCXXRecord(Base) != DevirtualizedClass) {
209 // If the method is defined in a class that is not the best dynamic
210 // one or the one of the full expression, we would have to build
211 // a derived-to-base cast to compute the correct this pointer, but
212 // we don't have support for that yet, so do a virtual call.
213 DevirtualizedMethod = NULL;
214 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000215 // If the return types are not the same, this might be a case where more
216 // code needs to run to compensate for it. For example, the derived
217 // method might return a type that inherits form from the return
218 // type of MD and has a prefix.
219 // For now we just avoid devirtualizing these covariant cases.
220 if (DevirtualizedMethod &&
221 DevirtualizedMethod->getResultType().getCanonicalType() !=
222 MD->getResultType().getCanonicalType())
Rafael Espindola4a889e42012-06-28 15:11:39 +0000223 DevirtualizedMethod = NULL;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000224 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000225
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000226 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000227 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000228 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000229 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000230 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000231
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000232
John McCallfc400282010-09-03 01:26:39 +0000233 if (MD->isTrivial()) {
234 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000235 if (isa<CXXConstructorDecl>(MD) &&
236 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
237 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000238
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000239 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
240 // We don't like to generate the trivial copy/move assignment operator
241 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000242 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
243 EmitAggregateCopy(This, RHS, CE->getType());
244 return RValue::get(This);
245 }
246
247 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000248 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
249 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000250 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
251 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
252 CE->arg_begin(), CE->arg_end());
253 return RValue::get(This);
254 }
255 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000256 }
257
John McCallfc400282010-09-03 01:26:39 +0000258 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000259 const CGFunctionInfo *FInfo = 0;
260 if (isa<CXXDestructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000261 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
262 Dtor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000263 else if (isa<CXXConstructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000264 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
265 cast<CXXConstructorDecl>(MD),
266 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000267 else
John McCallde5d3c72012-02-17 03:33:10 +0000268 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCallfc400282010-09-03 01:26:39 +0000269
John McCallde5d3c72012-02-17 03:33:10 +0000270 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000271
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000272 // C++ [class.virtual]p12:
273 // Explicit qualification with the scope operator (5.1) suppresses the
274 // virtual call mechanism.
275 //
276 // We also don't emit a virtual call if the base expression has a record type
277 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000278 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000279
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000280 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000281 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
282 if (UseVirtualCall) {
283 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +0000285 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000286 MD->isVirtual() &&
287 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000288 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000289 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000290 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000291 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000292 const CXXDestructorDecl *DDtor =
293 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000294 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
295 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000297 } else if (const CXXConstructorDecl *Ctor =
298 dyn_cast<CXXConstructorDecl>(MD)) {
299 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000300 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000301 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000302 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +0000303 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000304 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000305 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000306 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000307 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000308 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000309 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000310 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000311 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000312 }
313
Anders Carlssonc997d422010-01-02 01:01:18 +0000314 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000315 CE->arg_begin(), CE->arg_end());
316}
317
318RValue
319CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
320 ReturnValueSlot ReturnValue) {
321 const BinaryOperator *BO =
322 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
323 const Expr *BaseExpr = BO->getLHS();
324 const Expr *MemFnExpr = BO->getRHS();
325
326 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000327 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000328
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000329 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000330 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000331 const CXXRecordDecl *RD =
332 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
333
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000334 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000335 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000336
337 // Emit the 'this' pointer.
338 llvm::Value *This;
339
John McCall2de56d12010-08-25 11:45:40 +0000340 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000341 This = EmitScalarExpr(BaseExpr);
342 else
343 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344
Richard Smith2c9f87c2012-08-24 00:54:33 +0000345 EmitCheck(CT_MemberCall, This, QualType(MPT->getClass(), 0));
346
John McCall93d557b2010-08-22 00:05:51 +0000347 // Ask the ABI to load the callee. Note that This is modified.
348 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000349 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000350
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000351 CallArgList Args;
352
353 QualType ThisType =
354 getContext().getPointerType(getContext().getTagDeclType(RD));
355
356 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000357 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000358
359 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000360
361 // And the rest of the call args
362 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0f3d0972012-07-07 06:41:13 +0000363 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000364 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000365}
366
367RValue
368CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
369 const CXXMethodDecl *MD,
370 ReturnValueSlot ReturnValue) {
371 assert(MD->isInstance() &&
372 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000373 LValue LV = EmitLValue(E->getArg(0));
374 llvm::Value *This = LV.getAddress();
375
Douglas Gregorb2b56582011-09-06 16:26:56 +0000376 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
377 MD->isTrivial()) {
378 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
379 QualType Ty = E->getType();
380 EmitAggregateCopy(This, Src, Ty);
381 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000382 }
383
Anders Carlssona2447e02011-05-08 20:32:23 +0000384 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000385 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000386 E->arg_begin() + 1, E->arg_end());
387}
388
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000389RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
390 ReturnValueSlot ReturnValue) {
391 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
392}
393
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000394static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
395 llvm::Value *DestPtr,
396 const CXXRecordDecl *Base) {
397 if (Base->isEmpty())
398 return;
399
400 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
401
402 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
403 CharUnits Size = Layout.getNonVirtualSize();
404 CharUnits Align = Layout.getNonVirtualAlign();
405
406 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
407
408 // If the type contains a pointer to data member we can't memset it to zero.
409 // Instead, create a null constant and copy it to the destination.
410 // TODO: there are other patterns besides zero that we can usefully memset,
411 // like -1, which happens to be the pattern used by member-pointers.
412 // TODO: isZeroInitializable can be over-conservative in the case where a
413 // virtual base contains a member pointer.
414 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
415 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
416
417 llvm::GlobalVariable *NullVariable =
418 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
419 /*isConstant=*/true,
420 llvm::GlobalVariable::PrivateLinkage,
421 NullConstant, Twine());
422 NullVariable->setAlignment(Align.getQuantity());
423 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
424
425 // Get and call the appropriate llvm.memcpy overload.
426 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
427 return;
428 }
429
430 // Otherwise, just memset the whole thing to zero. This is legal
431 // because in LLVM, all default initializers (other than the ones we just
432 // handled above) are guaranteed to have a bit pattern of all zeros.
433 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
434 Align.getQuantity());
435}
436
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000437void
John McCall558d2ab2010-09-15 10:14:12 +0000438CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
439 AggValueSlot Dest) {
440 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000441 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000442
443 // If we require zero initialization before (or instead of) calling the
444 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000445 // constructor, emit the zero initialization now, unless destination is
446 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000447 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
448 switch (E->getConstructionKind()) {
449 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000450 case CXXConstructExpr::CK_Complete:
451 EmitNullInitialization(Dest.getAddr(), E->getType());
452 break;
453 case CXXConstructExpr::CK_VirtualBase:
454 case CXXConstructExpr::CK_NonVirtualBase:
455 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
456 break;
457 }
458 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000459
460 // If this is a call to a trivial default constructor, do nothing.
461 if (CD->isTrivial() && CD->isDefaultConstructor())
462 return;
463
John McCallfc1e6c72010-09-18 00:58:34 +0000464 // Elide the constructor if we're constructing from a temporary.
465 // The temporary check is required because Sema sets this on NRVO
466 // returns.
David Blaikie4e4d0842012-03-11 07:00:24 +0000467 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000468 assert(getContext().hasSameUnqualifiedType(E->getType(),
469 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000470 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
471 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000472 return;
473 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000474 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000475
John McCallc3c07662011-07-13 06:10:41 +0000476 if (const ConstantArrayType *arrayType
477 = getContext().getAsConstantArrayType(E->getType())) {
478 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000479 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000480 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000481 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000482 bool ForVirtualBase = false;
483
484 switch (E->getConstructionKind()) {
485 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000486 // We should be emitting a constructor; GlobalDecl will assert this
487 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000488 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000489
Sean Huntd49bd552011-05-03 20:19:28 +0000490 case CXXConstructExpr::CK_Complete:
491 Type = Ctor_Complete;
492 break;
493
494 case CXXConstructExpr::CK_VirtualBase:
495 ForVirtualBase = true;
496 // fall-through
497
498 case CXXConstructExpr::CK_NonVirtualBase:
499 Type = Ctor_Base;
500 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000501
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000502 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000503 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000504 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000505 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000506}
507
Fariborz Jahanian34999872010-11-13 21:53:34 +0000508void
509CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
510 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000511 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000512 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000513 Exp = E->getSubExpr();
514 assert(isa<CXXConstructExpr>(Exp) &&
515 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
516 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
517 const CXXConstructorDecl *CD = E->getConstructor();
518 RunCleanupsScope Scope(*this);
519
520 // If we require zero initialization before (or instead of) calling the
521 // constructor, as can be the case with a non-user-provided default
522 // constructor, emit the zero initialization now.
523 // FIXME. Do I still need this for a copy ctor synthesis?
524 if (E->requiresZeroInitialization())
525 EmitNullInitialization(Dest, E->getType());
526
Chandler Carruth858a5462010-11-15 13:54:43 +0000527 assert(!getContext().getAsConstantArrayType(E->getType())
528 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000529 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
530 E->arg_begin(), E->arg_end());
531}
532
John McCall1e7fe752010-09-02 09:58:18 +0000533static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
534 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000535 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000536 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000537
John McCallb1c98a32011-05-16 01:05:12 +0000538 // No cookie is required if the operator new[] being used is the
539 // reserved placement operator new[].
540 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000541 return CharUnits::Zero();
542
John McCall6ec278d2011-01-27 09:37:56 +0000543 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000544}
545
John McCall7d166272011-05-15 07:14:44 +0000546static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
547 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000548 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000549 llvm::Value *&numElements,
550 llvm::Value *&sizeWithoutCookie) {
551 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000552
John McCall7d166272011-05-15 07:14:44 +0000553 if (!e->isArray()) {
554 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
555 sizeWithoutCookie
556 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
557 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000558 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000559
John McCall7d166272011-05-15 07:14:44 +0000560 // The width of size_t.
561 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
562
John McCall1e7fe752010-09-02 09:58:18 +0000563 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000564 llvm::APInt cookieSize(sizeWidth,
565 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000566
Anders Carlssona4d4c012009-09-23 16:07:23 +0000567 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000568 // We multiply the size of all dimensions for NumElements.
569 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000570 numElements = CGF.EmitScalarExpr(e->getArraySize());
571 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000572
John McCall7d166272011-05-15 07:14:44 +0000573 // The number of elements can be have an arbitrary integer type;
574 // essentially, we need to multiply it by a constant factor, add a
575 // cookie size, and verify that the result is representable as a
576 // size_t. That's just a gloss, though, and it's wrong in one
577 // important way: if the count is negative, it's an error even if
578 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000579 bool isSigned
580 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000581 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000582 = cast<llvm::IntegerType>(numElements->getType());
583 unsigned numElementsWidth = numElementsType->getBitWidth();
584
585 // Compute the constant factor.
586 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000587 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000588 = CGF.getContext().getAsConstantArrayType(type)) {
589 type = CAT->getElementType();
590 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000591 }
592
John McCall7d166272011-05-15 07:14:44 +0000593 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
594 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
595 typeSizeMultiplier *= arraySizeMultiplier;
596
597 // This will be a size_t.
598 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000599
Chris Lattner806941e2010-07-20 21:55:52 +0000600 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
601 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000602 if (llvm::ConstantInt *numElementsC =
603 dyn_cast<llvm::ConstantInt>(numElements)) {
604 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000605
John McCall7d166272011-05-15 07:14:44 +0000606 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000607
John McCall7d166272011-05-15 07:14:44 +0000608 // If 'count' was a negative number, it's an overflow.
609 if (isSigned && count.isNegative())
610 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000611
John McCall7d166272011-05-15 07:14:44 +0000612 // We want to do all this arithmetic in size_t. If numElements is
613 // wider than that, check whether it's already too big, and if so,
614 // overflow.
615 else if (numElementsWidth > sizeWidth &&
616 numElementsWidth - sizeWidth > count.countLeadingZeros())
617 hasAnyOverflow = true;
618
619 // Okay, compute a count at the right width.
620 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
621
Sebastian Redl92036472012-02-22 17:37:52 +0000622 // If there is a brace-initializer, we cannot allocate fewer elements than
623 // there are initializers. If we do, that's treated like an overflow.
624 if (adjustedCount.ult(minElements))
625 hasAnyOverflow = true;
626
John McCall7d166272011-05-15 07:14:44 +0000627 // Scale numElements by that. This might overflow, but we don't
628 // care because it only overflows if allocationSize does, too, and
629 // if that overflows then we shouldn't use this.
630 numElements = llvm::ConstantInt::get(CGF.SizeTy,
631 adjustedCount * arraySizeMultiplier);
632
633 // Compute the size before cookie, and track whether it overflowed.
634 bool overflow;
635 llvm::APInt allocationSize
636 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
637 hasAnyOverflow |= overflow;
638
639 // Add in the cookie, and check whether it's overflowed.
640 if (cookieSize != 0) {
641 // Save the current size without a cookie. This shouldn't be
642 // used if there was overflow.
643 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
644
645 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
646 hasAnyOverflow |= overflow;
647 }
648
649 // On overflow, produce a -1 so operator new will fail.
650 if (hasAnyOverflow) {
651 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
652 } else {
653 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
654 }
655
656 // Otherwise, we might need to use the overflow intrinsics.
657 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000658 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000659 // 1) if isSigned, we need to check whether numElements is negative;
660 // 2) if numElementsWidth > sizeWidth, we need to check whether
661 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000662 // 3) if minElements > 0, we need to check whether numElements is smaller
663 // than that.
664 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000665 // sizeWithoutCookie := numElements * typeSizeMultiplier
666 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000667 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000668 // size := sizeWithoutCookie + cookieSize
669 // and check whether it overflows.
670
671 llvm::Value *hasOverflow = 0;
672
673 // If numElementsWidth > sizeWidth, then one way or another, we're
674 // going to have to do a comparison for (2), and this happens to
675 // take care of (1), too.
676 if (numElementsWidth > sizeWidth) {
677 llvm::APInt threshold(numElementsWidth, 1);
678 threshold <<= sizeWidth;
679
680 llvm::Value *thresholdV
681 = llvm::ConstantInt::get(numElementsType, threshold);
682
683 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
684 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
685
686 // Otherwise, if we're signed, we want to sext up to size_t.
687 } else if (isSigned) {
688 if (numElementsWidth < sizeWidth)
689 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
690
691 // If there's a non-1 type size multiplier, then we can do the
692 // signedness check at the same time as we do the multiply
693 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000694 // unsigned overflow. Otherwise, we have to do it here. But at least
695 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000696 if (typeSizeMultiplier == 1)
697 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000698 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000699
700 // Otherwise, zext up to size_t if necessary.
701 } else if (numElementsWidth < sizeWidth) {
702 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
703 }
704
705 assert(numElements->getType() == CGF.SizeTy);
706
Sebastian Redl92036472012-02-22 17:37:52 +0000707 if (minElements) {
708 // Don't allow allocation of fewer elements than we have initializers.
709 if (!hasOverflow) {
710 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
711 llvm::ConstantInt::get(CGF.SizeTy, minElements));
712 } else if (numElementsWidth > sizeWidth) {
713 // The other existing overflow subsumes this check.
714 // We do an unsigned comparison, since any signed value < -1 is
715 // taken care of either above or below.
716 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
717 CGF.Builder.CreateICmpULT(numElements,
718 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
719 }
720 }
721
John McCall7d166272011-05-15 07:14:44 +0000722 size = numElements;
723
724 // Multiply by the type size if necessary. This multiplier
725 // includes all the factors for nested arrays.
726 //
727 // This step also causes numElements to be scaled up by the
728 // nested-array factor if necessary. Overflow on this computation
729 // can be ignored because the result shouldn't be used if
730 // allocation fails.
731 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000732 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000733 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000734
735 llvm::Value *tsmV =
736 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
737 llvm::Value *result =
738 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
739
740 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
741 if (hasOverflow)
742 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
743 else
744 hasOverflow = overflowed;
745
746 size = CGF.Builder.CreateExtractValue(result, 0);
747
748 // Also scale up numElements by the array size multiplier.
749 if (arraySizeMultiplier != 1) {
750 // If the base element type size is 1, then we can re-use the
751 // multiply we just did.
752 if (typeSize.isOne()) {
753 assert(arraySizeMultiplier == typeSizeMultiplier);
754 numElements = size;
755
756 // Otherwise we need a separate multiply.
757 } else {
758 llvm::Value *asmV =
759 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
760 numElements = CGF.Builder.CreateMul(numElements, asmV);
761 }
762 }
763 } else {
764 // numElements doesn't need to be scaled.
765 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000766 }
767
John McCall7d166272011-05-15 07:14:44 +0000768 // Add in the cookie size if necessary.
769 if (cookieSize != 0) {
770 sizeWithoutCookie = size;
771
John McCall7d166272011-05-15 07:14:44 +0000772 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000773 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000774
775 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
776 llvm::Value *result =
777 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
778
779 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
780 if (hasOverflow)
781 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
782 else
783 hasOverflow = overflowed;
784
785 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000786 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000787
John McCall7d166272011-05-15 07:14:44 +0000788 // If we had any possibility of dynamic overflow, make a select to
789 // overwrite 'size' with an all-ones value, which should cause
790 // operator new to throw.
791 if (hasOverflow)
792 size = CGF.Builder.CreateSelect(hasOverflow,
793 llvm::Constant::getAllOnesValue(CGF.SizeTy),
794 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000795 }
John McCall1e7fe752010-09-02 09:58:18 +0000796
John McCall7d166272011-05-15 07:14:44 +0000797 if (cookieSize == 0)
798 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000799 else
John McCall7d166272011-05-15 07:14:44 +0000800 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000801
John McCall7d166272011-05-15 07:14:44 +0000802 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000803}
804
Sebastian Redl92036472012-02-22 17:37:52 +0000805static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
806 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000807
Eli Friedmand7722d92011-12-03 02:13:40 +0000808 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCalla07398e2011-06-16 04:16:24 +0000809 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedmand7722d92011-12-03 02:13:40 +0000810 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000811 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000812 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000813 else if (AllocType->isAnyComplexType())
814 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
815 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000816 else {
817 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000818 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000819 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000820 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000821 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000822 CGF.EmitAggExpr(Init, Slot);
Sebastian Redl972edf02012-02-19 16:03:09 +0000823
824 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall558d2ab2010-09-15 10:14:12 +0000825 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000826}
827
828void
829CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000830 QualType elementType,
831 llvm::Value *beginPtr,
832 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000833 if (!E->hasInitializer())
834 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000835
Sebastian Redl92036472012-02-22 17:37:52 +0000836 llvm::Value *explicitPtr = beginPtr;
John McCall19705672011-09-15 06:49:18 +0000837 // Find the end of the array, hoisted out of the loop.
838 llvm::Value *endPtr =
839 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
840
Sebastian Redl92036472012-02-22 17:37:52 +0000841 unsigned initializerElements = 0;
842
843 const Expr *Init = E->getInitializer();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000844 llvm::AllocaInst *endOfInit = 0;
845 QualType::DestructionKind dtorKind = elementType.isDestructedType();
846 EHScopeStack::stable_iterator cleanup;
847 llvm::Instruction *cleanupDominator = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000848 // If the initializer is an initializer list, first do the explicit elements.
849 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
850 initializerElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000851
852 // Enter a partial-destruction cleanup if necessary.
853 if (needsEHCleanup(dtorKind)) {
854 // In principle we could tell the cleanup where we are more
855 // directly, but the control flow can get so varied here that it
856 // would actually be quite complex. Therefore we go through an
857 // alloca.
858 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
859 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
860 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
861 getDestroyer(dtorKind));
862 cleanup = EHStack.stable_begin();
863 }
864
Sebastian Redl92036472012-02-22 17:37:52 +0000865 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000866 // Tell the cleanup that it needs to destroy up to this
867 // element. TODO: some of these stores can be trivially
868 // observed to be unnecessary.
869 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redl92036472012-02-22 17:37:52 +0000870 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
871 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
872 }
873
874 // The remaining elements are filled with the array filler expression.
875 Init = ILE->getArrayFiller();
876 }
877
John McCall19705672011-09-15 06:49:18 +0000878 // Create the continuation block.
879 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
880
Sebastian Redl92036472012-02-22 17:37:52 +0000881 // If the number of elements isn't constant, we have to now check if there is
882 // anything left to initialize.
883 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
884 // If all elements have already been initialized, skip the whole loop.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000885 if (constNum->getZExtValue() <= initializerElements) {
886 // If there was a cleanup, deactivate it.
887 if (cleanupDominator)
888 DeactivateCleanupBlock(cleanup, cleanupDominator);;
889 return;
890 }
Sebastian Redl92036472012-02-22 17:37:52 +0000891 } else {
John McCall19705672011-09-15 06:49:18 +0000892 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redl92036472012-02-22 17:37:52 +0000893 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall19705672011-09-15 06:49:18 +0000894 "array.isempty");
895 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
896 EmitBlock(nonEmptyBB);
897 }
898
899 // Enter the loop.
900 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
901 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
902
903 EmitBlock(loopBB);
904
905 // Set up the current-element phi.
906 llvm::PHINode *curPtr =
Sebastian Redl92036472012-02-22 17:37:52 +0000907 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
908 curPtr->addIncoming(explicitPtr, entryBB);
John McCall19705672011-09-15 06:49:18 +0000909
Chad Rosier577fb5b2012-02-24 00:13:55 +0000910 // Store the new cleanup position for irregular cleanups.
911 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
912
John McCall19705672011-09-15 06:49:18 +0000913 // Enter a partial-destruction cleanup if necessary.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000914 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall19705672011-09-15 06:49:18 +0000915 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
916 getDestroyer(dtorKind));
917 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000918 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000919 }
920
921 // Emit the initializer into this element.
Sebastian Redl92036472012-02-22 17:37:52 +0000922 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall19705672011-09-15 06:49:18 +0000923
924 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000925 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000926 DeactivateCleanupBlock(cleanup, cleanupDominator);
927 cleanupDominator->eraseFromParent();
928 }
John McCall19705672011-09-15 06:49:18 +0000929
930 // Advance to the next element.
931 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
932
933 // Check whether we've gotten to the end of the array and, if so,
934 // exit the loop.
935 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
936 Builder.CreateCondBr(isEnd, contBB, loopBB);
937 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
938
939 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000940}
941
Douglas Gregor59174c02010-07-21 01:10:17 +0000942static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
943 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000944 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000945 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000946 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000947 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000948}
949
Anders Carlssona4d4c012009-09-23 16:07:23 +0000950static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000951 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000952 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000953 llvm::Value *NumElements,
954 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000955 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000956 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000957 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
958 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor887ddf32012-02-23 17:07:43 +0000959 if (Ctor->isTrivial()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000960 // If new expression did not specify value-initialization, then there
961 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000962 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000963 return;
964
John McCall19705672011-09-15 06:49:18 +0000965 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000966 // Optimization: since zero initialization will just set the memory
967 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000968 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000969 return;
970 }
Douglas Gregor59174c02010-07-21 01:10:17 +0000971 }
John McCallc3c07662011-07-13 06:10:41 +0000972
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000973 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
974 CCE->arg_begin(), CCE->arg_end(),
Eli Friedmanb41ba1a2012-08-25 07:11:29 +0000975 CCE->requiresZeroInitialization());
Anders Carlssone99bdb62010-05-03 15:09:17 +0000976 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000977 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000978 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000979 // Optimization: since zero initialization will just set the memory
980 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000981 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
982 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +0000983 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000984 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
985 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000986 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000987
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000988 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000989 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000990
Sebastian Redl92036472012-02-22 17:37:52 +0000991 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000992}
993
John McCall7d8647f2010-09-14 07:57:04 +0000994namespace {
995 /// A cleanup to call the given 'operator delete' function upon
996 /// abnormal exit from a new expression.
997 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
998 size_t NumPlacementArgs;
999 const FunctionDecl *OperatorDelete;
1000 llvm::Value *Ptr;
1001 llvm::Value *AllocSize;
1002
1003 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1004
1005 public:
1006 static size_t getExtraSize(size_t NumPlacementArgs) {
1007 return NumPlacementArgs * sizeof(RValue);
1008 }
1009
1010 CallDeleteDuringNew(size_t NumPlacementArgs,
1011 const FunctionDecl *OperatorDelete,
1012 llvm::Value *Ptr,
1013 llvm::Value *AllocSize)
1014 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1015 Ptr(Ptr), AllocSize(AllocSize) {}
1016
1017 void setPlacementArg(unsigned I, RValue Arg) {
1018 assert(I < NumPlacementArgs && "index out of range");
1019 getPlacementArgs()[I] = Arg;
1020 }
1021
John McCallad346f42011-07-12 20:27:29 +00001022 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +00001023 const FunctionProtoType *FPT
1024 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1025 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +00001026 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001027
1028 CallArgList DeleteArgs;
1029
1030 // The first argument is always a void*.
1031 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001032 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001033
1034 // A member 'operator delete' can take an extra 'size_t' argument.
1035 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001036 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001037
1038 // Pass the rest of the arguments, which must match exactly.
1039 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001040 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001041
1042 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001043 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +00001044 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1045 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1046 }
1047 };
John McCall3019c442010-09-17 00:50:28 +00001048
1049 /// A cleanup to call the given 'operator delete' function upon
1050 /// abnormal exit from a new expression when the new expression is
1051 /// conditional.
1052 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1053 size_t NumPlacementArgs;
1054 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001055 DominatingValue<RValue>::saved_type Ptr;
1056 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001057
John McCall804b8072011-01-28 10:53:53 +00001058 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1059 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001060 }
1061
1062 public:
1063 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001064 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001065 }
1066
1067 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1068 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001069 DominatingValue<RValue>::saved_type Ptr,
1070 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001071 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1072 Ptr(Ptr), AllocSize(AllocSize) {}
1073
John McCall804b8072011-01-28 10:53:53 +00001074 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001075 assert(I < NumPlacementArgs && "index out of range");
1076 getPlacementArgs()[I] = Arg;
1077 }
1078
John McCallad346f42011-07-12 20:27:29 +00001079 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +00001080 const FunctionProtoType *FPT
1081 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1082 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1083 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1084
1085 CallArgList DeleteArgs;
1086
1087 // The first argument is always a void*.
1088 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001089 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001090
1091 // A member 'operator delete' can take an extra 'size_t' argument.
1092 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001093 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001094 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001095 }
1096
1097 // Pass the rest of the arguments, which must match exactly.
1098 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001099 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001100 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001101 }
1102
1103 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001104 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +00001105 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1106 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1107 }
1108 };
1109}
1110
1111/// Enter a cleanup to call 'operator delete' if the initializer in a
1112/// new-expression throws.
1113static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1114 const CXXNewExpr *E,
1115 llvm::Value *NewPtr,
1116 llvm::Value *AllocSize,
1117 const CallArgList &NewArgs) {
1118 // If we're not inside a conditional branch, then the cleanup will
1119 // dominate and we can do the easier (and more efficient) thing.
1120 if (!CGF.isInConditionalBranch()) {
1121 CallDeleteDuringNew *Cleanup = CGF.EHStack
1122 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1123 E->getNumPlacementArgs(),
1124 E->getOperatorDelete(),
1125 NewPtr, AllocSize);
1126 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001127 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001128
1129 return;
1130 }
1131
1132 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001133 DominatingValue<RValue>::saved_type SavedNewPtr =
1134 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1135 DominatingValue<RValue>::saved_type SavedAllocSize =
1136 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001137
1138 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001139 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001140 E->getNumPlacementArgs(),
1141 E->getOperatorDelete(),
1142 SavedNewPtr,
1143 SavedAllocSize);
1144 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001145 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001146 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001147
John McCall6f103ba2011-11-10 10:43:54 +00001148 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001149}
1150
Anders Carlsson16d81b82009-09-22 22:53:17 +00001151llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001152 // The element type being allocated.
1153 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001154
John McCallc2f3e7f2011-03-07 03:12:35 +00001155 // 1. Build a call to the allocation function.
1156 FunctionDecl *allocator = E->getOperatorNew();
1157 const FunctionProtoType *allocatorType =
1158 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001159
John McCallc2f3e7f2011-03-07 03:12:35 +00001160 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001161
1162 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001163 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001164
Sebastian Redl92036472012-02-22 17:37:52 +00001165 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1166 unsigned minElements = 0;
1167 if (E->isArray() && E->hasInitializer()) {
1168 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1169 minElements = ILE->getNumInits();
1170 }
1171
John McCallc2f3e7f2011-03-07 03:12:35 +00001172 llvm::Value *numElements = 0;
1173 llvm::Value *allocSizeWithoutCookie = 0;
1174 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001175 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1176 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001177
Eli Friedman04c9a492011-05-02 17:57:46 +00001178 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001179
1180 // Emit the rest of the arguments.
1181 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001182 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001183
1184 // First, use the types from the function type.
1185 // We start at 1 here because the first argument (the allocation size)
1186 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001187 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1188 ++i, ++placementArg) {
1189 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001190
John McCallc2f3e7f2011-03-07 03:12:35 +00001191 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1192 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001193 "type mismatch in call argument!");
1194
John McCall413ebdb2011-03-11 20:59:21 +00001195 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001196 }
1197
1198 // Either we've emitted all the call args, or we have a call to a
1199 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001200 assert((placementArg == E->placement_arg_end() ||
1201 allocatorType->isVariadic()) &&
1202 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001203
1204 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001205 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1206 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001207 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001208 }
1209
John McCallb1c98a32011-05-16 01:05:12 +00001210 // Emit the allocation call. If the allocator is a global placement
1211 // operator, just "inline" it directly.
1212 RValue RV;
1213 if (allocator->isReservedGlobalPlacementOperator()) {
1214 assert(allocatorArgs.size() == 2);
1215 RV = allocatorArgs[1].RV;
1216 // TODO: kill any unnecessary computations done for the size
1217 // argument.
1218 } else {
John McCall0f3d0972012-07-07 06:41:13 +00001219 RV = EmitCall(CGM.getTypes().arrangeFreeFunctionCall(allocatorArgs,
1220 allocatorType),
John McCallb1c98a32011-05-16 01:05:12 +00001221 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1222 allocatorArgs, allocator);
1223 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001224
John McCallc2f3e7f2011-03-07 03:12:35 +00001225 // Emit a null check on the allocation result if the allocation
1226 // function is allowed to return null (because it has a non-throwing
1227 // exception spec; for this part, we inline
1228 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1229 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001230 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001231 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001232
John McCallc2f3e7f2011-03-07 03:12:35 +00001233 llvm::BasicBlock *nullCheckBB = 0;
1234 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001235
John McCallc2f3e7f2011-03-07 03:12:35 +00001236 llvm::Value *allocation = RV.getScalarVal();
1237 unsigned AS =
1238 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001239
John McCalla7f633f2011-03-07 01:52:56 +00001240 // The null-check means that the initializer is conditionally
1241 // evaluated.
1242 ConditionalEvaluation conditional(*this);
1243
John McCallc2f3e7f2011-03-07 03:12:35 +00001244 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001245 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001246
1247 nullCheckBB = Builder.GetInsertBlock();
1248 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1249 contBB = createBasicBlock("new.cont");
1250
1251 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1252 Builder.CreateCondBr(isNull, contBB, notNullBB);
1253 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001254 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001255
John McCall7d8647f2010-09-14 07:57:04 +00001256 // If there's an operator delete, enter a cleanup to call it if an
1257 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001258 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001259 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001260 if (E->getOperatorDelete() &&
1261 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001262 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1263 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001264 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001265 }
1266
Eli Friedman576cf172011-09-06 18:53:03 +00001267 assert((allocSize == allocSizeWithoutCookie) ==
1268 CalculateCookiePadding(*this, E).isZero());
1269 if (allocSize != allocSizeWithoutCookie) {
1270 assert(E->isArray());
1271 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1272 numElements,
1273 E, allocType);
1274 }
1275
Chris Lattner2acc6e32011-07-18 04:24:23 +00001276 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001277 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1278 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001279
John McCall19705672011-09-15 06:49:18 +00001280 EmitNewInitializer(*this, E, allocType, result, numElements,
1281 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001282 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001283 // NewPtr is a pointer to the base element type. If we're
1284 // allocating an array of arrays, we'll need to cast back to the
1285 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001286 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001287 if (result->getType() != resultType)
1288 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001289 }
John McCall7d8647f2010-09-14 07:57:04 +00001290
1291 // Deactivate the 'operator delete' cleanup if we finished
1292 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001293 if (operatorDeleteCleanup.isValid()) {
1294 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1295 cleanupDominator->eraseFromParent();
1296 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001297
John McCallc2f3e7f2011-03-07 03:12:35 +00001298 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001299 conditional.end(*this);
1300
John McCallc2f3e7f2011-03-07 03:12:35 +00001301 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1302 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001303
Jay Foadbbf3bac2011-03-30 11:28:58 +00001304 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001305 PHI->addIncoming(result, notNullBB);
1306 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1307 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001308
John McCallc2f3e7f2011-03-07 03:12:35 +00001309 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001310 }
John McCall1e7fe752010-09-02 09:58:18 +00001311
John McCallc2f3e7f2011-03-07 03:12:35 +00001312 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001313}
1314
Eli Friedman5fe05982009-11-18 00:50:08 +00001315void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1316 llvm::Value *Ptr,
1317 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001318 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1319
Eli Friedman5fe05982009-11-18 00:50:08 +00001320 const FunctionProtoType *DeleteFTy =
1321 DeleteFD->getType()->getAs<FunctionProtoType>();
1322
1323 CallArgList DeleteArgs;
1324
Anders Carlsson871d0782009-12-13 20:04:38 +00001325 // Check if we need to pass the size to the delete operator.
1326 llvm::Value *Size = 0;
1327 QualType SizeTy;
1328 if (DeleteFTy->getNumArgs() == 2) {
1329 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001330 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1331 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1332 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001333 }
1334
Eli Friedman5fe05982009-11-18 00:50:08 +00001335 QualType ArgTy = DeleteFTy->getArgType(0);
1336 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001337 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001338
Anders Carlsson871d0782009-12-13 20:04:38 +00001339 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001340 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001341
1342 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001343 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001344 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001345 DeleteArgs, DeleteFD);
1346}
1347
John McCall1e7fe752010-09-02 09:58:18 +00001348namespace {
1349 /// Calls the given 'operator delete' on a single object.
1350 struct CallObjectDelete : EHScopeStack::Cleanup {
1351 llvm::Value *Ptr;
1352 const FunctionDecl *OperatorDelete;
1353 QualType ElementType;
1354
1355 CallObjectDelete(llvm::Value *Ptr,
1356 const FunctionDecl *OperatorDelete,
1357 QualType ElementType)
1358 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1359
John McCallad346f42011-07-12 20:27:29 +00001360 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001361 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1362 }
1363 };
1364}
1365
1366/// Emit the code for deleting a single object.
1367static void EmitObjectDelete(CodeGenFunction &CGF,
1368 const FunctionDecl *OperatorDelete,
1369 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001370 QualType ElementType,
1371 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001372 // Find the destructor for the type, if applicable. If the
1373 // destructor is virtual, we'll just emit the vcall and return.
1374 const CXXDestructorDecl *Dtor = 0;
1375 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1376 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001377 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001378 Dtor = RD->getDestructor();
1379
1380 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001381 if (UseGlobalDelete) {
1382 // If we're supposed to call the global delete, make sure we do so
1383 // even if the destructor throws.
1384 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1385 Ptr, OperatorDelete,
1386 ElementType);
1387 }
1388
Chris Lattner2acc6e32011-07-18 04:24:23 +00001389 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +00001390 CGF.getTypes().GetFunctionType(
1391 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall1e7fe752010-09-02 09:58:18 +00001392
1393 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001394 = CGF.BuildVirtualCall(Dtor,
1395 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1396 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001397 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1398 0, 0);
1399
Douglas Gregora8b20f72011-07-13 00:54:47 +00001400 if (UseGlobalDelete) {
1401 CGF.PopCleanupBlock();
1402 }
1403
John McCall1e7fe752010-09-02 09:58:18 +00001404 return;
1405 }
1406 }
1407 }
1408
1409 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001410 // This doesn't have to a conditional cleanup because we're going
1411 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001412 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1413 Ptr, OperatorDelete, ElementType);
1414
1415 if (Dtor)
1416 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1417 /*ForVirtualBase=*/false, Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001418 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001419 ElementType->isObjCLifetimeType()) {
1420 switch (ElementType.getObjCLifetime()) {
1421 case Qualifiers::OCL_None:
1422 case Qualifiers::OCL_ExplicitNone:
1423 case Qualifiers::OCL_Autoreleasing:
1424 break;
John McCall1e7fe752010-09-02 09:58:18 +00001425
John McCallf85e1932011-06-15 23:02:42 +00001426 case Qualifiers::OCL_Strong: {
1427 // Load the pointer value.
1428 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1429 ElementType.isVolatileQualified());
1430
1431 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1432 break;
1433 }
1434
1435 case Qualifiers::OCL_Weak:
1436 CGF.EmitARCDestroyWeak(Ptr);
1437 break;
1438 }
1439 }
1440
John McCall1e7fe752010-09-02 09:58:18 +00001441 CGF.PopCleanupBlock();
1442}
1443
1444namespace {
1445 /// Calls the given 'operator delete' on an array of objects.
1446 struct CallArrayDelete : EHScopeStack::Cleanup {
1447 llvm::Value *Ptr;
1448 const FunctionDecl *OperatorDelete;
1449 llvm::Value *NumElements;
1450 QualType ElementType;
1451 CharUnits CookieSize;
1452
1453 CallArrayDelete(llvm::Value *Ptr,
1454 const FunctionDecl *OperatorDelete,
1455 llvm::Value *NumElements,
1456 QualType ElementType,
1457 CharUnits CookieSize)
1458 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1459 ElementType(ElementType), CookieSize(CookieSize) {}
1460
John McCallad346f42011-07-12 20:27:29 +00001461 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001462 const FunctionProtoType *DeleteFTy =
1463 OperatorDelete->getType()->getAs<FunctionProtoType>();
1464 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1465
1466 CallArgList Args;
1467
1468 // Pass the pointer as the first argument.
1469 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1470 llvm::Value *DeletePtr
1471 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001472 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001473
1474 // Pass the original requested size as the second argument.
1475 if (DeleteFTy->getNumArgs() == 2) {
1476 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001477 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001478 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1479
1480 CharUnits ElementTypeSize =
1481 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1482
1483 // The size of an element, multiplied by the number of elements.
1484 llvm::Value *Size
1485 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1486 Size = CGF.Builder.CreateMul(Size, NumElements);
1487
1488 // Plus the size of the cookie if applicable.
1489 if (!CookieSize.isZero()) {
1490 llvm::Value *CookieSizeV
1491 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1492 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1493 }
1494
Eli Friedman04c9a492011-05-02 17:57:46 +00001495 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001496 }
1497
1498 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001499 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001500 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1501 ReturnValueSlot(), Args, OperatorDelete);
1502 }
1503 };
1504}
1505
1506/// Emit the code for deleting an array of objects.
1507static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001508 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001509 llvm::Value *deletedPtr,
1510 QualType elementType) {
1511 llvm::Value *numElements = 0;
1512 llvm::Value *allocatedPtr = 0;
1513 CharUnits cookieSize;
1514 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1515 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001516
John McCall7cfd76c2011-07-13 01:41:37 +00001517 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001518
1519 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001520 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001521 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001522 allocatedPtr, operatorDelete,
1523 numElements, elementType,
1524 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001525
John McCall7cfd76c2011-07-13 01:41:37 +00001526 // Destroy the elements.
1527 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1528 assert(numElements && "no element count for a type with a destructor!");
1529
John McCall7cfd76c2011-07-13 01:41:37 +00001530 llvm::Value *arrayEnd =
1531 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001532
1533 // Note that it is legal to allocate a zero-length array, and we
1534 // can never fold the check away because the length should always
1535 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001536 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1537 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001538 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001539 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001540 }
1541
John McCall7cfd76c2011-07-13 01:41:37 +00001542 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001543 CGF.PopCleanupBlock();
1544}
1545
Anders Carlsson16d81b82009-09-22 22:53:17 +00001546void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001547 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001548 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001549
1550 // Null check the pointer.
1551 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1552 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1553
Anders Carlssonb9241242011-04-11 00:30:07 +00001554 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001555
1556 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1557 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001558
John McCall1e7fe752010-09-02 09:58:18 +00001559 // We might be deleting a pointer to array. If so, GEP down to the
1560 // first non-array element.
1561 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1562 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1563 if (DeleteTy->isConstantArrayType()) {
1564 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001565 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001566
1567 GEP.push_back(Zero); // point at the outermost array
1568
1569 // For each layer of array type we're pointing at:
1570 while (const ConstantArrayType *Arr
1571 = getContext().getAsConstantArrayType(DeleteTy)) {
1572 // 1. Unpeel the array type.
1573 DeleteTy = Arr->getElementType();
1574
1575 // 2. GEP to the first element of the array.
1576 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001577 }
John McCall1e7fe752010-09-02 09:58:18 +00001578
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001579 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001580 }
1581
Douglas Gregoreede61a2010-09-02 17:38:50 +00001582 assert(ConvertTypeForMem(DeleteTy) ==
1583 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001584
1585 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001586 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001587 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001588 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1589 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001590 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001591
Anders Carlsson16d81b82009-09-22 22:53:17 +00001592 EmitBlock(DeleteEnd);
1593}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001594
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001595static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1596 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001597 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001598
1599 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1600}
1601
1602static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001603 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001604 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001605 CGF.Builder.CreateUnreachable();
1606}
1607
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001608static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1609 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001610 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001611 // Get the vtable pointer.
1612 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1613
1614 // C++ [expr.typeid]p2:
1615 // If the glvalue expression is obtained by applying the unary * operator to
1616 // a pointer and the pointer is a null pointer value, the typeid expression
1617 // throws the std::bad_typeid exception.
1618 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1619 if (UO->getOpcode() == UO_Deref) {
1620 llvm::BasicBlock *BadTypeidBlock =
1621 CGF.createBasicBlock("typeid.bad_typeid");
1622 llvm::BasicBlock *EndBlock =
1623 CGF.createBasicBlock("typeid.end");
1624
1625 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1626 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1627
1628 CGF.EmitBlock(BadTypeidBlock);
1629 EmitBadTypeidCall(CGF);
1630 CGF.EmitBlock(EndBlock);
1631 }
1632 }
1633
1634 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1635 StdTypeInfoPtrTy->getPointerTo());
1636
1637 // Load the type info.
1638 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1639 return CGF.Builder.CreateLoad(Value);
1640}
1641
John McCall3ad32c82011-01-28 08:37:24 +00001642llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001643 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001644 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001645
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001646 if (E->isTypeOperand()) {
1647 llvm::Constant *TypeInfo =
1648 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001649 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001650 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001651
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001652 // C++ [expr.typeid]p2:
1653 // When typeid is applied to a glvalue expression whose type is a
1654 // polymorphic class type, the result refers to a std::type_info object
1655 // representing the type of the most derived object (that is, the dynamic
1656 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001657 if (E->isPotentiallyEvaluated())
1658 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1659 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001660
1661 QualType OperandTy = E->getExprOperand()->getType();
1662 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1663 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001664}
Mike Stumpc849c052009-11-16 06:50:58 +00001665
Anders Carlssonf0cb4a62011-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 Lattner8b418682012-02-07 00:39:47 +00001672 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001673 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001674 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1675
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001676 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001677
Chris Lattner2acc6e32011-07-18 04:24:23 +00001678 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-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 Lattner8b418682012-02-07 00:39:47 +00001686 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001687 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1688}
1689
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001690static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001691 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001692 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001693 CGF.Builder.CreateUnreachable();
1694}
1695
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001696static llvm::Value *
1697EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1698 QualType SrcTy, QualType DestTy,
1699 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001700 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001701 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001702 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-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 Carlsson3ddcdd52011-04-11 01:45:29 +00001764 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001765 }
1766
1767 return Value;
1768}
1769
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001770static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1771 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001772 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-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 Carlssonf0cb4a62011-04-11 00:46:40 +00001784llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001785 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001786 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001787
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001788 if (DCE->isAlwaysNull())
1789 return EmitDynamicCastToNull(*this, DestTy);
1790
1791 QualType SrcTy = DCE->getSubExpr()->getType();
1792
Anders Carlssonf0cb4a62011-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 Carlsson1d7088d2009-12-17 07:09:17 +00001797
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001798 llvm::BasicBlock *CastNull = 0;
1799 llvm::BasicBlock *CastNotNull = 0;
1800 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001801
Anders Carlssonf0cb4a62011-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 Stumpc849c052009-11-16 06:50:58 +00001809 }
1810
Anders Carlssonf0cb4a62011-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 Stumpc849c052009-11-16 06:50:58 +00001831}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001832
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001833void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001834 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001835 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1836 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001837
Eli Friedman4c5d8af2012-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 Christopherc07b18e2012-02-29 03:25:18 +00001841 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001842 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001843
David Blaikie581deb32012-06-06 20:45:41 +00001844 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001845 ArrayRef<VarDecl *> ArrayIndexes;
1846 if (CurField->getType()->isArrayType())
1847 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001848 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001849 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001850}