blob: 94f95053425ee94cb72aa56ccc514aee3c26c78c [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"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000020#include "llvm/Support/CallSite.h"
21
Anders Carlsson16d81b82009-09-22 22:53:17 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson3b5ad222010-01-01 20:29:01 +000025RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26 llvm::Value *Callee,
27 ReturnValueSlot ReturnValue,
28 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000029 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000030 CallExpr::const_arg_iterator ArgBeg,
31 CallExpr::const_arg_iterator ArgEnd) {
32 assert(MD->isInstance() &&
33 "Trying to emit a member call expr on a static method!");
34
35 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
36
37 CallArgList Args;
38
39 // Push the this ptr.
40 Args.push_back(std::make_pair(RValue::get(This),
41 MD->getThisType(getContext())));
42
Anders Carlssonc997d422010-01-02 01:01:18 +000043 // If there is a VTT parameter, emit it.
44 if (VTT) {
45 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
46 Args.push_back(std::make_pair(RValue::get(VTT), T));
47 }
48
Anders Carlsson3b5ad222010-01-01 20:29:01 +000049 // And the rest of the call args
50 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
51
John McCall04a67a62010-02-05 21:31:56 +000052 QualType ResultType = FPT->getResultType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000053 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
54 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000055 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000056}
57
Anders Carlsson1679f5a2011-01-29 03:52:01 +000058static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000059 const Expr *E = Base;
60
61 while (true) {
62 E = E->IgnoreParens();
63 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
64 if (CE->getCastKind() == CK_DerivedToBase ||
65 CE->getCastKind() == CK_UncheckedDerivedToBase ||
66 CE->getCastKind() == CK_NoOp) {
67 E = CE->getSubExpr();
68 continue;
69 }
70 }
71
72 break;
73 }
74
75 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000076 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
77 DerivedType = PTy->getPointeeType();
78
79 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
80}
81
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000082// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
83// quite what we want.
84static const Expr *skipNoOpCastsAndParens(const Expr *E) {
85 while (true) {
86 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
87 E = PE->getSubExpr();
88 continue;
89 }
90
91 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
92 if (CE->getCastKind() == CK_NoOp) {
93 E = CE->getSubExpr();
94 continue;
95 }
96 }
97 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
98 if (UO->getOpcode() == UO_Extension) {
99 E = UO->getSubExpr();
100 continue;
101 }
102 }
103 return E;
104 }
105}
106
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000107/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
108/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000109static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
110 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000111 const CXXMethodDecl *MD) {
112
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000113 // When building with -fapple-kext, all calls must go through the vtable since
114 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000115 if (Context.getLangOptions().AppleKext)
116 return false;
117
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000118 // If the most derived class is marked final, we know that no subclass can
119 // override this member function and so we can devirtualize it. For example:
120 //
121 // struct A { virtual void f(); }
122 // struct B final : A { };
123 //
124 // void f(B *b) {
125 // b->f();
126 // }
127 //
128 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
129 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
130 return true;
131
Anders Carlssonf89e0422011-01-23 21:07:30 +0000132 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000133 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000134 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000135 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000136
Anders Carlssonf89e0422011-01-23 21:07:30 +0000137 // Similarly, if the class itself is marked 'final' it can't be overridden
138 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000139 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000140 return true;
141
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000142 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000143 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
144 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
145 // This is a record decl. We know the type and can devirtualize it.
146 return VD->getType()->isRecordType();
147 }
148
149 return false;
150 }
151
152 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000153 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000154 return true;
155
156 // And calls on bound temporaries.
157 if (isa<CXXBindTemporaryExpr>(Base))
158 return true;
159
160 // Check if this is a call expr that returns a record type.
161 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
162 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000163
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000164 // We can't devirtualize the call.
165 return false;
166}
167
Francois Pichetdbee3412011-01-18 05:04:39 +0000168// Note: This function also emit constructor calls to support a MSVC
169// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000170RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
171 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000172 const Expr *callee = CE->getCallee()->IgnoreParens();
173
174 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000175 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000176
177 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000178 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
179
Devang Patelc69e1cf2010-09-30 19:05:55 +0000180 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000181 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
182 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000183 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
184 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
185 DI->getOrCreateRecordType(PTy->getPointeeType(),
186 MD->getParent()->getLocation());
187 }
188 }
189
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000190 if (MD->isStatic()) {
191 // The method is static, emit it as we would a regular call.
192 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
193 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
194 ReturnValue, CE->arg_begin(), CE->arg_end());
195 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000196
John McCallfc400282010-09-03 01:26:39 +0000197 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000198 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000199 if (ME->isArrow())
200 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000201 else
202 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000203
John McCallfc400282010-09-03 01:26:39 +0000204 if (MD->isTrivial()) {
205 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000206 if (isa<CXXConstructorDecl>(MD) &&
207 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
208 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000209
Francois Pichetdbee3412011-01-18 05:04:39 +0000210 if (MD->isCopyAssignmentOperator()) {
211 // We don't like to generate the trivial copy assignment operator when
212 // it isn't necessary; just produce the proper effect here.
213 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
214 EmitAggregateCopy(This, RHS, CE->getType());
215 return RValue::get(This);
216 }
217
218 if (isa<CXXConstructorDecl>(MD) &&
219 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
220 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
221 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
222 CE->arg_begin(), CE->arg_end());
223 return RValue::get(This);
224 }
225 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000226 }
227
John McCallfc400282010-09-03 01:26:39 +0000228 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000229 const CGFunctionInfo *FInfo = 0;
230 if (isa<CXXDestructorDecl>(MD))
231 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
232 Dtor_Complete);
233 else if (isa<CXXConstructorDecl>(MD))
234 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
235 Ctor_Complete);
236 else
237 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000238
239 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
240 const llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000241 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000242
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000243 // C++ [class.virtual]p12:
244 // Explicit qualification with the scope operator (5.1) suppresses the
245 // virtual call mechanism.
246 //
247 // We also don't emit a virtual call if the base expression has a record type
248 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000249 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000250 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
251 && !canDevirtualizeMemberFunctionCalls(getContext(),
252 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000253 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000254 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
255 if (UseVirtualCall) {
256 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000257 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000258 if (getContext().getLangOptions().AppleKext &&
259 MD->isVirtual() &&
260 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000261 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000262 else
263 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000265 } else if (const CXXConstructorDecl *Ctor =
266 dyn_cast<CXXConstructorDecl>(MD)) {
267 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000268 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000269 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000270 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000271 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000272 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000273 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000274 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000275 else
276 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000277 }
278
Anders Carlssonc997d422010-01-02 01:01:18 +0000279 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000280 CE->arg_begin(), CE->arg_end());
281}
282
283RValue
284CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
285 ReturnValueSlot ReturnValue) {
286 const BinaryOperator *BO =
287 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
288 const Expr *BaseExpr = BO->getLHS();
289 const Expr *MemFnExpr = BO->getRHS();
290
291 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000292 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000293
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000294 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000295 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
298
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000299 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000301
302 // Emit the 'this' pointer.
303 llvm::Value *This;
304
John McCall2de56d12010-08-25 11:45:40 +0000305 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000306 This = EmitScalarExpr(BaseExpr);
307 else
308 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309
John McCall93d557b2010-08-22 00:05:51 +0000310 // Ask the ABI to load the callee. Note that This is modified.
311 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000312 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000314 CallArgList Args;
315
316 QualType ThisType =
317 getContext().getPointerType(getContext().getTagDeclType(RD));
318
319 // Push the this ptr.
320 Args.push_back(std::make_pair(RValue::get(This), ThisType));
321
322 // And the rest of the call args
323 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall864c0412011-04-26 20:42:42 +0000324 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000325 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326}
327
328RValue
329CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
330 const CXXMethodDecl *MD,
331 ReturnValueSlot ReturnValue) {
332 assert(MD->isInstance() &&
333 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000334 LValue LV = EmitLValue(E->getArg(0));
335 llvm::Value *This = LV.getAddress();
336
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000337 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000338 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
339 if (ClassDecl->hasTrivialCopyAssignment()) {
340 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
341 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000342 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
343 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000344 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000345 return RValue::get(This);
346 }
347 }
348
349 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
350 const llvm::Type *Ty =
351 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
352 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000353 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000354 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000355 !canDevirtualizeMemberFunctionCalls(getContext(),
356 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000357 Callee = BuildVirtualCall(MD, This, Ty);
358 else
359 Callee = CGM.GetAddrOfFunction(MD, Ty);
360
Anders Carlssonc997d422010-01-02 01:01:18 +0000361 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000362 E->arg_begin() + 1, E->arg_end());
363}
364
365void
John McCall558d2ab2010-09-15 10:14:12 +0000366CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
367 AggValueSlot Dest) {
368 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000369 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000370
371 // If we require zero initialization before (or instead of) calling the
372 // constructor, as can be the case with a non-user-provided default
373 // constructor, emit the zero initialization now.
374 if (E->requiresZeroInitialization())
John McCall558d2ab2010-09-15 10:14:12 +0000375 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000376
377 // If this is a call to a trivial default constructor, do nothing.
378 if (CD->isTrivial() && CD->isDefaultConstructor())
379 return;
380
John McCallfc1e6c72010-09-18 00:58:34 +0000381 // Elide the constructor if we're constructing from a temporary.
382 // The temporary check is required because Sema sets this on NRVO
383 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000384 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000385 assert(getContext().hasSameUnqualifiedType(E->getType(),
386 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000387 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
388 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000389 return;
390 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000391 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000392
393 const ConstantArrayType *Array
394 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000395 if (Array) {
396 QualType BaseElementTy = getContext().getBaseElementType(Array);
397 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
398 BasePtr = llvm::PointerType::getUnqual(BasePtr);
399 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000400 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000401
402 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
403 E->arg_begin(), E->arg_end());
404 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000405 else {
406 CXXCtorType Type =
407 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
408 ? Ctor_Complete : Ctor_Base;
409 bool ForVirtualBase =
410 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
411
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000412 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000413 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000414 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000415 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000416}
417
Fariborz Jahanian34999872010-11-13 21:53:34 +0000418void
419CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
420 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000421 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000422 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000423 Exp = E->getSubExpr();
424 assert(isa<CXXConstructExpr>(Exp) &&
425 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
426 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
427 const CXXConstructorDecl *CD = E->getConstructor();
428 RunCleanupsScope Scope(*this);
429
430 // If we require zero initialization before (or instead of) calling the
431 // constructor, as can be the case with a non-user-provided default
432 // constructor, emit the zero initialization now.
433 // FIXME. Do I still need this for a copy ctor synthesis?
434 if (E->requiresZeroInitialization())
435 EmitNullInitialization(Dest, E->getType());
436
Chandler Carruth858a5462010-11-15 13:54:43 +0000437 assert(!getContext().getAsConstantArrayType(E->getType())
438 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000439 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
440 E->arg_begin(), E->arg_end());
441}
442
John McCall5172ed92010-08-23 01:17:59 +0000443/// Check whether the given operator new[] is the global placement
444/// operator new[].
445static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
446 const FunctionDecl *Fn) {
447 // Must be in global scope. Note that allocation functions can't be
448 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000449 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000450 return false;
451
452 // Signature must be void *operator new[](size_t, void*).
453 // The size_t is common to all operator new[]s.
454 if (Fn->getNumParams() != 2)
455 return false;
456
457 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
458 return (ParamType == Ctx.VoidPtrTy);
459}
460
John McCall1e7fe752010-09-02 09:58:18 +0000461static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
462 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000463 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000464 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000465
Anders Carlssondd937552009-12-13 20:34:34 +0000466 // No cookie is required if the new operator being used is
467 // ::operator new[](size_t, void*).
468 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000469 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000470 return CharUnits::Zero();
471
John McCall6ec278d2011-01-27 09:37:56 +0000472 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000473}
474
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000475static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000476 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000477 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000478 llvm::Value *&NumElements,
479 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000480 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000481
482 const llvm::IntegerType *SizeTy =
483 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000484
John McCall1e7fe752010-09-02 09:58:18 +0000485 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
486
Douglas Gregor59174c02010-07-21 01:10:17 +0000487 if (!E->isArray()) {
488 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
489 return SizeWithoutCookie;
490 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000491
John McCall1e7fe752010-09-02 09:58:18 +0000492 // Figure out the cookie size.
493 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
494
Anders Carlssona4d4c012009-09-23 16:07:23 +0000495 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000496 // We multiply the size of all dimensions for NumElements.
497 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000498 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000499 assert(NumElements->getType() == SizeTy && "element count not a size_t");
500
501 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000502 while (const ConstantArrayType *CAT
503 = CGF.getContext().getAsConstantArrayType(ElemType)) {
504 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000505 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000506 }
507
John McCall1e7fe752010-09-02 09:58:18 +0000508 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000509
Chris Lattner806941e2010-07-20 21:55:52 +0000510 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
511 // Don't bloat the -O0 code.
512 if (llvm::ConstantInt *NumElementsC =
513 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000514 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000515 unsigned SizeWidth = NEC.getBitWidth();
516
517 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000518 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000519 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000520 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000521
522 if (!CookieSize.isZero()) {
523 // Save the current size without a cookie. We don't care if an
524 // overflow's already happened because SizeWithoutCookie isn't
525 // used if the allocator returns null or throws, as it should
526 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000527 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000528 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
529
530 // Add the cookie size.
531 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000532 }
533
John McCall1e7fe752010-09-02 09:58:18 +0000534 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000535 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000536 Size = llvm::ConstantInt::get(SizeTy, SC);
537 } else {
538 // On overflow, produce a -1 so operator new throws.
539 Size = llvm::Constant::getAllOnesValue(SizeTy);
540 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000541
John McCall1e7fe752010-09-02 09:58:18 +0000542 // Scale NumElements while we're at it.
543 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
544 NumElements = llvm::ConstantInt::get(SizeTy, N);
545
546 // Otherwise, we don't need to do an overflow-checked multiplication if
547 // we're multiplying by one.
548 } else if (TypeSize.isOne()) {
549 assert(ArraySizeMultiplier == 1);
550
551 Size = NumElements;
552
553 // If we need a cookie, add its size in with an overflow check.
554 // This is maybe a little paranoid.
555 if (!CookieSize.isZero()) {
556 SizeWithoutCookie = Size;
557
558 llvm::Value *CookieSizeV
559 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
560
561 const llvm::Type *Types[] = { SizeTy };
562 llvm::Value *UAddF
563 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
564 llvm::Value *AddRes
565 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
566
567 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
568 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
569 Size = CGF.Builder.CreateSelect(DidOverflow,
570 llvm::ConstantInt::get(SizeTy, -1),
571 Size);
572 }
573
574 // Otherwise use the int.umul.with.overflow intrinsic.
575 } else {
576 llvm::Value *OutermostElementSize
577 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
578
579 llvm::Value *NumOutermostElements = NumElements;
580
581 // Scale NumElements by the array size multiplier. This might
582 // overflow, but only if the multiplication below also overflows,
583 // in which case this multiplication isn't used.
584 if (ArraySizeMultiplier != 1)
585 NumElements = CGF.Builder.CreateMul(NumElements,
586 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
587
588 // The requested size of the outermost array is non-constant.
589 // Multiply that by the static size of the elements of that array;
590 // on unsigned overflow, set the size to -1 to trigger an
591 // exception from the allocation routine. This is sufficient to
592 // prevent buffer overruns from the allocator returning a
593 // seemingly valid pointer to insufficient space. This idea comes
594 // originally from MSVC, and GCC has an open bug requesting
595 // similar behavior:
596 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
597 //
598 // This will not be sufficient for C++0x, which requires a
599 // specific exception class (std::bad_array_new_length).
600 // That will require ABI support that has not yet been specified.
601 const llvm::Type *Types[] = { SizeTy };
602 llvm::Value *UMulF
603 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
604 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
605 OutermostElementSize);
606
607 // The overflow bit.
608 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
609
610 // The result of the multiplication.
611 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
612
613 // If we have a cookie, we need to add that size in, too.
614 if (!CookieSize.isZero()) {
615 SizeWithoutCookie = Size;
616
617 llvm::Value *CookieSizeV
618 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
619 llvm::Value *UAddF
620 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
621 llvm::Value *AddRes
622 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
623
624 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
625
626 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedman5536daa2011-04-09 19:54:33 +0000627 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall1e7fe752010-09-02 09:58:18 +0000628 }
629
630 Size = CGF.Builder.CreateSelect(DidOverflow,
631 llvm::ConstantInt::get(SizeTy, -1),
632 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000633 }
John McCall1e7fe752010-09-02 09:58:18 +0000634
635 if (CookieSize.isZero())
636 SizeWithoutCookie = Size;
637 else
638 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
639
Chris Lattner806941e2010-07-20 21:55:52 +0000640 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000641}
642
Fariborz Jahanianef668722010-06-25 18:26:07 +0000643static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
644 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000645
646 assert(E->getNumConstructorArgs() == 1 &&
647 "Can only have one argument to initializer of POD type.");
648
649 const Expr *Init = E->getConstructorArg(0);
650 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000651
652 unsigned Alignment =
653 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000654 if (!CGF.hasAggregateLLVMType(AllocType))
655 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000656 AllocType.isVolatileQualified(), Alignment,
657 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000658 else if (AllocType->isAnyComplexType())
659 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
660 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000661 else {
662 AggValueSlot Slot
663 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
664 CGF.EmitAggExpr(Init, Slot);
665 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000666}
667
668void
669CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
670 llvm::Value *NewPtr,
671 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000672 // We have a POD type.
673 if (E->getNumConstructorArgs() == 0)
674 return;
675
Fariborz Jahanianef668722010-06-25 18:26:07 +0000676 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
677
678 // Create a temporary for the loop index and initialize it with 0.
679 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
680 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
681 Builder.CreateStore(Zero, IndexPtr);
682
683 // Start the loop with a block that tests the condition.
684 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
685 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
686
687 EmitBlock(CondBlock);
688
689 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
690
691 // Generate: if (loop-index < number-of-elements fall to the loop body,
692 // otherwise, go to the block after the for-loop.
693 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
694 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
695 // If the condition is true, execute the body.
696 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
697
698 EmitBlock(ForBody);
699
700 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
701 // Inside the loop body, emit the constructor call on the array element.
702 Counter = Builder.CreateLoad(IndexPtr);
703 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
704 "arrayidx");
705 StoreAnyExprIntoOneUnit(*this, E, Address);
706
707 EmitBlock(ContinueBlock);
708
709 // Emit the increment of the loop counter.
710 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
711 Counter = Builder.CreateLoad(IndexPtr);
712 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
713 Builder.CreateStore(NextVal, IndexPtr);
714
715 // Finally, branch back up to the condition for the next iteration.
716 EmitBranch(CondBlock);
717
718 // Emit the fall-through block.
719 EmitBlock(AfterFor, true);
720}
721
Douglas Gregor59174c02010-07-21 01:10:17 +0000722static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
723 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000724 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000725 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000726 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000727 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000728}
729
Anders Carlssona4d4c012009-09-23 16:07:23 +0000730static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
731 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000732 llvm::Value *NumElements,
733 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000734 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000735 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000736 bool RequiresZeroInitialization = false;
737 if (Ctor->getParent()->hasTrivialConstructor()) {
738 // If new expression did not specify value-initialization, then there
739 // is no initialization.
740 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
741 return;
742
John McCallf16aa102010-08-22 21:01:12 +0000743 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000744 // Optimization: since zero initialization will just set the memory
745 // to all zeroes, generate a single memset to do it in one shot.
746 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
747 AllocSizeWithoutCookie);
748 return;
749 }
750
751 RequiresZeroInitialization = true;
752 }
753
754 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
755 E->constructor_arg_begin(),
756 E->constructor_arg_end(),
757 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000758 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000759 } else if (E->getNumConstructorArgs() == 1 &&
760 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
761 // Optimization: since zero initialization will just set the memory
762 // to all zeroes, generate a single memset to do it in one shot.
763 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
764 AllocSizeWithoutCookie);
765 return;
766 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000767 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
768 return;
769 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000770 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000771
772 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000773 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
774 // direct initialization. C++ [dcl.init]p5 requires that we
775 // zero-initialize storage if there are no user-declared constructors.
776 if (E->hasInitializer() &&
777 !Ctor->getParent()->hasUserDeclaredConstructor() &&
778 !Ctor->getParent()->isEmpty())
779 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
780
Douglas Gregor84745672010-07-07 23:37:33 +0000781 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
782 NewPtr, E->constructor_arg_begin(),
783 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000784
785 return;
786 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000787 // We have a POD type.
788 if (E->getNumConstructorArgs() == 0)
789 return;
790
Fariborz Jahanianef668722010-06-25 18:26:07 +0000791 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000792}
793
John McCall7d8647f2010-09-14 07:57:04 +0000794namespace {
795 /// A cleanup to call the given 'operator delete' function upon
796 /// abnormal exit from a new expression.
797 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
798 size_t NumPlacementArgs;
799 const FunctionDecl *OperatorDelete;
800 llvm::Value *Ptr;
801 llvm::Value *AllocSize;
802
803 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
804
805 public:
806 static size_t getExtraSize(size_t NumPlacementArgs) {
807 return NumPlacementArgs * sizeof(RValue);
808 }
809
810 CallDeleteDuringNew(size_t NumPlacementArgs,
811 const FunctionDecl *OperatorDelete,
812 llvm::Value *Ptr,
813 llvm::Value *AllocSize)
814 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
815 Ptr(Ptr), AllocSize(AllocSize) {}
816
817 void setPlacementArg(unsigned I, RValue Arg) {
818 assert(I < NumPlacementArgs && "index out of range");
819 getPlacementArgs()[I] = Arg;
820 }
821
822 void Emit(CodeGenFunction &CGF, bool IsForEH) {
823 const FunctionProtoType *FPT
824 = OperatorDelete->getType()->getAs<FunctionProtoType>();
825 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000826 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000827
828 CallArgList DeleteArgs;
829
830 // The first argument is always a void*.
831 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
832 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
833
834 // A member 'operator delete' can take an extra 'size_t' argument.
835 if (FPT->getNumArgs() == NumPlacementArgs + 2)
836 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
837
838 // Pass the rest of the arguments, which must match exactly.
839 for (unsigned I = 0; I != NumPlacementArgs; ++I)
840 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
841
842 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000843 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000844 CGF.CGM.GetAddrOfFunction(OperatorDelete),
845 ReturnValueSlot(), DeleteArgs, OperatorDelete);
846 }
847 };
John McCall3019c442010-09-17 00:50:28 +0000848
849 /// A cleanup to call the given 'operator delete' function upon
850 /// abnormal exit from a new expression when the new expression is
851 /// conditional.
852 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
853 size_t NumPlacementArgs;
854 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000855 DominatingValue<RValue>::saved_type Ptr;
856 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000857
John McCall804b8072011-01-28 10:53:53 +0000858 DominatingValue<RValue>::saved_type *getPlacementArgs() {
859 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000860 }
861
862 public:
863 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000864 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000865 }
866
867 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
868 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000869 DominatingValue<RValue>::saved_type Ptr,
870 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000871 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
872 Ptr(Ptr), AllocSize(AllocSize) {}
873
John McCall804b8072011-01-28 10:53:53 +0000874 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000875 assert(I < NumPlacementArgs && "index out of range");
876 getPlacementArgs()[I] = Arg;
877 }
878
879 void Emit(CodeGenFunction &CGF, bool IsForEH) {
880 const FunctionProtoType *FPT
881 = OperatorDelete->getType()->getAs<FunctionProtoType>();
882 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
883 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
884
885 CallArgList DeleteArgs;
886
887 // The first argument is always a void*.
888 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCall804b8072011-01-28 10:53:53 +0000889 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall3019c442010-09-17 00:50:28 +0000890
891 // A member 'operator delete' can take an extra 'size_t' argument.
892 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000893 RValue RV = AllocSize.restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000894 DeleteArgs.push_back(std::make_pair(RV, *AI++));
895 }
896
897 // Pass the rest of the arguments, which must match exactly.
898 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000899 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000900 DeleteArgs.push_back(std::make_pair(RV, *AI++));
901 }
902
903 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000904 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000905 CGF.CGM.GetAddrOfFunction(OperatorDelete),
906 ReturnValueSlot(), DeleteArgs, OperatorDelete);
907 }
908 };
909}
910
911/// Enter a cleanup to call 'operator delete' if the initializer in a
912/// new-expression throws.
913static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
914 const CXXNewExpr *E,
915 llvm::Value *NewPtr,
916 llvm::Value *AllocSize,
917 const CallArgList &NewArgs) {
918 // If we're not inside a conditional branch, then the cleanup will
919 // dominate and we can do the easier (and more efficient) thing.
920 if (!CGF.isInConditionalBranch()) {
921 CallDeleteDuringNew *Cleanup = CGF.EHStack
922 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
923 E->getNumPlacementArgs(),
924 E->getOperatorDelete(),
925 NewPtr, AllocSize);
926 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
927 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
928
929 return;
930 }
931
932 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000933 DominatingValue<RValue>::saved_type SavedNewPtr =
934 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
935 DominatingValue<RValue>::saved_type SavedAllocSize =
936 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000937
938 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
939 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
940 E->getNumPlacementArgs(),
941 E->getOperatorDelete(),
942 SavedNewPtr,
943 SavedAllocSize);
944 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000945 Cleanup->setPlacementArg(I,
946 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000947
948 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000949}
950
Anders Carlsson16d81b82009-09-22 22:53:17 +0000951llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000952 // The element type being allocated.
953 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +0000954
John McCallc2f3e7f2011-03-07 03:12:35 +0000955 // 1. Build a call to the allocation function.
956 FunctionDecl *allocator = E->getOperatorNew();
957 const FunctionProtoType *allocatorType =
958 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000959
John McCallc2f3e7f2011-03-07 03:12:35 +0000960 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000961
962 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000963 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000964
John McCallc2f3e7f2011-03-07 03:12:35 +0000965 llvm::Value *numElements = 0;
966 llvm::Value *allocSizeWithoutCookie = 0;
967 llvm::Value *allocSize =
968 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
969 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000970
John McCallc2f3e7f2011-03-07 03:12:35 +0000971 allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000972
973 // Emit the rest of the arguments.
974 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +0000975 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000976
977 // First, use the types from the function type.
978 // We start at 1 here because the first argument (the allocation size)
979 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +0000980 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
981 ++i, ++placementArg) {
982 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000983
John McCallc2f3e7f2011-03-07 03:12:35 +0000984 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
985 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +0000986 "type mismatch in call argument!");
987
John McCall413ebdb2011-03-11 20:59:21 +0000988 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000989 }
990
991 // Either we've emitted all the call args, or we have a call to a
992 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +0000993 assert((placementArg == E->placement_arg_end() ||
994 allocatorType->isVariadic()) &&
995 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +0000996
997 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000998 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
999 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001000 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001001 }
1002
John McCallc2f3e7f2011-03-07 03:12:35 +00001003 // Emit the allocation call.
Anders Carlsson16d81b82009-09-22 22:53:17 +00001004 RValue RV =
John McCallc2f3e7f2011-03-07 03:12:35 +00001005 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1006 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1007 allocatorArgs, allocator);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001008
John McCallc2f3e7f2011-03-07 03:12:35 +00001009 // Emit a null check on the allocation result if the allocation
1010 // function is allowed to return null (because it has a non-throwing
1011 // exception spec; for this part, we inline
1012 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1013 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001014 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallc2f3e7f2011-03-07 03:12:35 +00001015 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001016
John McCallc2f3e7f2011-03-07 03:12:35 +00001017 llvm::BasicBlock *nullCheckBB = 0;
1018 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001019
John McCallc2f3e7f2011-03-07 03:12:35 +00001020 llvm::Value *allocation = RV.getScalarVal();
1021 unsigned AS =
1022 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001023
John McCalla7f633f2011-03-07 01:52:56 +00001024 // The null-check means that the initializer is conditionally
1025 // evaluated.
1026 ConditionalEvaluation conditional(*this);
1027
John McCallc2f3e7f2011-03-07 03:12:35 +00001028 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001029 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001030
1031 nullCheckBB = Builder.GetInsertBlock();
1032 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1033 contBB = createBasicBlock("new.cont");
1034
1035 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1036 Builder.CreateCondBr(isNull, contBB, notNullBB);
1037 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001038 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001039
John McCallc2f3e7f2011-03-07 03:12:35 +00001040 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001041 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001042 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001043 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001044 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1045 numElements,
1046 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001047 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001048
John McCall7d8647f2010-09-14 07:57:04 +00001049 // If there's an operator delete, enter a cleanup to call it if an
1050 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001051 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7d8647f2010-09-14 07:57:04 +00001052 if (E->getOperatorDelete()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001053 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1054 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001055 }
1056
John McCallc2f3e7f2011-03-07 03:12:35 +00001057 const llvm::Type *elementPtrTy
1058 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1059 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001060
John McCall1e7fe752010-09-02 09:58:18 +00001061 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001062 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001063
1064 // NewPtr is a pointer to the base element type. If we're
1065 // allocating an array of arrays, we'll need to cast back to the
1066 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001067 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1068 if (result->getType() != resultType)
1069 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001070 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001071 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001072 }
John McCall7d8647f2010-09-14 07:57:04 +00001073
1074 // Deactivate the 'operator delete' cleanup if we finished
1075 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001076 if (operatorDeleteCleanup.isValid())
1077 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001078
John McCallc2f3e7f2011-03-07 03:12:35 +00001079 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001080 conditional.end(*this);
1081
John McCallc2f3e7f2011-03-07 03:12:35 +00001082 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1083 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001084
Jay Foadbbf3bac2011-03-30 11:28:58 +00001085 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001086 PHI->addIncoming(result, notNullBB);
1087 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1088 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001089
John McCallc2f3e7f2011-03-07 03:12:35 +00001090 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001091 }
John McCall1e7fe752010-09-02 09:58:18 +00001092
John McCallc2f3e7f2011-03-07 03:12:35 +00001093 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001094}
1095
Eli Friedman5fe05982009-11-18 00:50:08 +00001096void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1097 llvm::Value *Ptr,
1098 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001099 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1100
Eli Friedman5fe05982009-11-18 00:50:08 +00001101 const FunctionProtoType *DeleteFTy =
1102 DeleteFD->getType()->getAs<FunctionProtoType>();
1103
1104 CallArgList DeleteArgs;
1105
Anders Carlsson871d0782009-12-13 20:04:38 +00001106 // Check if we need to pass the size to the delete operator.
1107 llvm::Value *Size = 0;
1108 QualType SizeTy;
1109 if (DeleteFTy->getNumArgs() == 2) {
1110 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001111 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1112 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1113 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001114 }
1115
Eli Friedman5fe05982009-11-18 00:50:08 +00001116 QualType ArgTy = DeleteFTy->getArgType(0);
1117 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1118 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1119
Anders Carlsson871d0782009-12-13 20:04:38 +00001120 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +00001121 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +00001122
1123 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001124 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001125 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001126 DeleteArgs, DeleteFD);
1127}
1128
John McCall1e7fe752010-09-02 09:58:18 +00001129namespace {
1130 /// Calls the given 'operator delete' on a single object.
1131 struct CallObjectDelete : EHScopeStack::Cleanup {
1132 llvm::Value *Ptr;
1133 const FunctionDecl *OperatorDelete;
1134 QualType ElementType;
1135
1136 CallObjectDelete(llvm::Value *Ptr,
1137 const FunctionDecl *OperatorDelete,
1138 QualType ElementType)
1139 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1140
1141 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1142 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1143 }
1144 };
1145}
1146
1147/// Emit the code for deleting a single object.
1148static void EmitObjectDelete(CodeGenFunction &CGF,
1149 const FunctionDecl *OperatorDelete,
1150 llvm::Value *Ptr,
1151 QualType ElementType) {
1152 // Find the destructor for the type, if applicable. If the
1153 // destructor is virtual, we'll just emit the vcall and return.
1154 const CXXDestructorDecl *Dtor = 0;
1155 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1156 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1157 if (!RD->hasTrivialDestructor()) {
1158 Dtor = RD->getDestructor();
1159
1160 if (Dtor->isVirtual()) {
1161 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001162 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1163 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001164 /*isVariadic=*/false);
1165
1166 llvm::Value *Callee
1167 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1168 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1169 0, 0);
1170
1171 // The dtor took care of deleting the object.
1172 return;
1173 }
1174 }
1175 }
1176
1177 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001178 // This doesn't have to a conditional cleanup because we're going
1179 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001180 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1181 Ptr, OperatorDelete, ElementType);
1182
1183 if (Dtor)
1184 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1185 /*ForVirtualBase=*/false, Ptr);
1186
1187 CGF.PopCleanupBlock();
1188}
1189
1190namespace {
1191 /// Calls the given 'operator delete' on an array of objects.
1192 struct CallArrayDelete : EHScopeStack::Cleanup {
1193 llvm::Value *Ptr;
1194 const FunctionDecl *OperatorDelete;
1195 llvm::Value *NumElements;
1196 QualType ElementType;
1197 CharUnits CookieSize;
1198
1199 CallArrayDelete(llvm::Value *Ptr,
1200 const FunctionDecl *OperatorDelete,
1201 llvm::Value *NumElements,
1202 QualType ElementType,
1203 CharUnits CookieSize)
1204 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1205 ElementType(ElementType), CookieSize(CookieSize) {}
1206
1207 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1208 const FunctionProtoType *DeleteFTy =
1209 OperatorDelete->getType()->getAs<FunctionProtoType>();
1210 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1211
1212 CallArgList Args;
1213
1214 // Pass the pointer as the first argument.
1215 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1216 llvm::Value *DeletePtr
1217 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1218 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1219
1220 // Pass the original requested size as the second argument.
1221 if (DeleteFTy->getNumArgs() == 2) {
1222 QualType size_t = DeleteFTy->getArgType(1);
1223 const llvm::IntegerType *SizeTy
1224 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1225
1226 CharUnits ElementTypeSize =
1227 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1228
1229 // The size of an element, multiplied by the number of elements.
1230 llvm::Value *Size
1231 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1232 Size = CGF.Builder.CreateMul(Size, NumElements);
1233
1234 // Plus the size of the cookie if applicable.
1235 if (!CookieSize.isZero()) {
1236 llvm::Value *CookieSizeV
1237 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1238 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1239 }
1240
1241 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1242 }
1243
1244 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001245 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001246 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1247 ReturnValueSlot(), Args, OperatorDelete);
1248 }
1249 };
1250}
1251
1252/// Emit the code for deleting an array of objects.
1253static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001254 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001255 llvm::Value *Ptr,
1256 QualType ElementType) {
1257 llvm::Value *NumElements = 0;
1258 llvm::Value *AllocatedPtr = 0;
1259 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001260 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001261 NumElements, AllocatedPtr, CookieSize);
1262
1263 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1264
1265 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001266 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001267 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1268 AllocatedPtr, OperatorDelete,
1269 NumElements, ElementType,
1270 CookieSize);
1271
1272 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1273 if (!RD->hasTrivialDestructor()) {
1274 assert(NumElements && "ReadArrayCookie didn't find element count"
1275 " for a class with destructor");
1276 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1277 }
1278 }
1279
1280 CGF.PopCleanupBlock();
1281}
1282
Anders Carlsson16d81b82009-09-22 22:53:17 +00001283void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001284
Douglas Gregor90916562009-09-29 18:16:17 +00001285 // Get at the argument before we performed the implicit conversion
1286 // to void*.
1287 const Expr *Arg = E->getArgument();
1288 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001289 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001290 ICE->getType()->isVoidPointerType())
1291 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001292 else
1293 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001294 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001295
Douglas Gregor90916562009-09-29 18:16:17 +00001296 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001297
1298 // Null check the pointer.
1299 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1300 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1301
Anders Carlssonb9241242011-04-11 00:30:07 +00001302 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001303
1304 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1305 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001306
John McCall1e7fe752010-09-02 09:58:18 +00001307 // We might be deleting a pointer to array. If so, GEP down to the
1308 // first non-array element.
1309 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1310 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1311 if (DeleteTy->isConstantArrayType()) {
1312 llvm::Value *Zero = Builder.getInt32(0);
1313 llvm::SmallVector<llvm::Value*,8> GEP;
1314
1315 GEP.push_back(Zero); // point at the outermost array
1316
1317 // For each layer of array type we're pointing at:
1318 while (const ConstantArrayType *Arr
1319 = getContext().getAsConstantArrayType(DeleteTy)) {
1320 // 1. Unpeel the array type.
1321 DeleteTy = Arr->getElementType();
1322
1323 // 2. GEP to the first element of the array.
1324 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001325 }
John McCall1e7fe752010-09-02 09:58:18 +00001326
1327 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001328 }
1329
Douglas Gregoreede61a2010-09-02 17:38:50 +00001330 assert(ConvertTypeForMem(DeleteTy) ==
1331 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001332
1333 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001334 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001335 } else {
1336 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1337 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001338
Anders Carlsson16d81b82009-09-22 22:53:17 +00001339 EmitBlock(DeleteEnd);
1340}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001341
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001342static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1343 // void __cxa_bad_typeid();
1344
1345 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1346 const llvm::FunctionType *FTy =
1347 llvm::FunctionType::get(VoidTy, false);
1348
1349 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1350}
1351
1352static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001353 llvm::Value *Fn = getBadTypeidFn(CGF);
1354 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001355 CGF.Builder.CreateUnreachable();
1356}
1357
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001358static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1359 const Expr *E,
1360 const llvm::Type *StdTypeInfoPtrTy) {
1361 // Get the vtable pointer.
1362 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1363
1364 // C++ [expr.typeid]p2:
1365 // If the glvalue expression is obtained by applying the unary * operator to
1366 // a pointer and the pointer is a null pointer value, the typeid expression
1367 // throws the std::bad_typeid exception.
1368 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1369 if (UO->getOpcode() == UO_Deref) {
1370 llvm::BasicBlock *BadTypeidBlock =
1371 CGF.createBasicBlock("typeid.bad_typeid");
1372 llvm::BasicBlock *EndBlock =
1373 CGF.createBasicBlock("typeid.end");
1374
1375 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1376 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1377
1378 CGF.EmitBlock(BadTypeidBlock);
1379 EmitBadTypeidCall(CGF);
1380 CGF.EmitBlock(EndBlock);
1381 }
1382 }
1383
1384 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1385 StdTypeInfoPtrTy->getPointerTo());
1386
1387 // Load the type info.
1388 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1389 return CGF.Builder.CreateLoad(Value);
1390}
1391
John McCall3ad32c82011-01-28 08:37:24 +00001392llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001393 const llvm::Type *StdTypeInfoPtrTy =
1394 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001395
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001396 if (E->isTypeOperand()) {
1397 llvm::Constant *TypeInfo =
1398 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001399 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001400 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001401
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001402 // C++ [expr.typeid]p2:
1403 // When typeid is applied to a glvalue expression whose type is a
1404 // polymorphic class type, the result refers to a std::type_info object
1405 // representing the type of the most derived object (that is, the dynamic
1406 // type) to which the glvalue refers.
1407 if (E->getExprOperand()->isGLValue()) {
1408 if (const RecordType *RT =
1409 E->getExprOperand()->getType()->getAs<RecordType>()) {
1410 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1411 if (RD->isPolymorphic())
1412 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1413 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001414 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001415 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001416
1417 QualType OperandTy = E->getExprOperand()->getType();
1418 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1419 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001420}
Mike Stumpc849c052009-11-16 06:50:58 +00001421
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001422static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1423 // void *__dynamic_cast(const void *sub,
1424 // const abi::__class_type_info *src,
1425 // const abi::__class_type_info *dst,
1426 // std::ptrdiff_t src2dst_offset);
1427
1428 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1429 const llvm::Type *PtrDiffTy =
1430 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1431
1432 const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1433
1434 const llvm::FunctionType *FTy =
1435 llvm::FunctionType::get(Int8PtrTy, Args, false);
1436
1437 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1438}
1439
1440static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1441 // void __cxa_bad_cast();
1442
1443 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1444 const llvm::FunctionType *FTy =
1445 llvm::FunctionType::get(VoidTy, false);
1446
1447 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1448}
1449
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001450static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001451 llvm::Value *Fn = getBadCastFn(CGF);
1452 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001453 CGF.Builder.CreateUnreachable();
1454}
1455
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001456static llvm::Value *
1457EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1458 QualType SrcTy, QualType DestTy,
1459 llvm::BasicBlock *CastEnd) {
1460 const llvm::Type *PtrDiffLTy =
1461 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1462 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1463
1464 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1465 if (PTy->getPointeeType()->isVoidType()) {
1466 // C++ [expr.dynamic.cast]p7:
1467 // If T is "pointer to cv void," then the result is a pointer to the
1468 // most derived object pointed to by v.
1469
1470 // Get the vtable pointer.
1471 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1472
1473 // Get the offset-to-top from the vtable.
1474 llvm::Value *OffsetToTop =
1475 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1476 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1477
1478 // Finally, add the offset to the pointer.
1479 Value = CGF.EmitCastToVoidPtr(Value);
1480 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1481
1482 return CGF.Builder.CreateBitCast(Value, DestLTy);
1483 }
1484 }
1485
1486 QualType SrcRecordTy;
1487 QualType DestRecordTy;
1488
1489 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1490 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1491 DestRecordTy = DestPTy->getPointeeType();
1492 } else {
1493 SrcRecordTy = SrcTy;
1494 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1495 }
1496
1497 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1498 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1499
1500 llvm::Value *SrcRTTI =
1501 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1502 llvm::Value *DestRTTI =
1503 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1504
1505 // FIXME: Actually compute a hint here.
1506 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1507
1508 // Emit the call to __dynamic_cast.
1509 Value = CGF.EmitCastToVoidPtr(Value);
1510 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1511 SrcRTTI, DestRTTI, OffsetHint);
1512 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1513
1514 /// C++ [expr.dynamic.cast]p9:
1515 /// A failed cast to reference type throws std::bad_cast
1516 if (DestTy->isReferenceType()) {
1517 llvm::BasicBlock *BadCastBlock =
1518 CGF.createBasicBlock("dynamic_cast.bad_cast");
1519
1520 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1521 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1522
1523 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001524 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001525 }
1526
1527 return Value;
1528}
1529
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001530static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1531 QualType DestTy) {
1532 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1533 if (DestTy->isPointerType())
1534 return llvm::Constant::getNullValue(DestLTy);
1535
1536 /// C++ [expr.dynamic.cast]p9:
1537 /// A failed cast to reference type throws std::bad_cast
1538 EmitBadCastCall(CGF);
1539
1540 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1541 return llvm::UndefValue::get(DestLTy);
1542}
1543
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001544llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001545 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001546 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001547
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001548 if (DCE->isAlwaysNull())
1549 return EmitDynamicCastToNull(*this, DestTy);
1550
1551 QualType SrcTy = DCE->getSubExpr()->getType();
1552
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001553 // C++ [expr.dynamic.cast]p4:
1554 // If the value of v is a null pointer value in the pointer case, the result
1555 // is the null pointer value of type T.
1556 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001557
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001558 llvm::BasicBlock *CastNull = 0;
1559 llvm::BasicBlock *CastNotNull = 0;
1560 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001561
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001562 if (ShouldNullCheckSrcValue) {
1563 CastNull = createBasicBlock("dynamic_cast.null");
1564 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1565
1566 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1567 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1568 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001569 }
1570
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001571 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1572
1573 if (ShouldNullCheckSrcValue) {
1574 EmitBranch(CastEnd);
1575
1576 EmitBlock(CastNull);
1577 EmitBranch(CastEnd);
1578 }
1579
1580 EmitBlock(CastEnd);
1581
1582 if (ShouldNullCheckSrcValue) {
1583 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1584 PHI->addIncoming(Value, CastNotNull);
1585 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1586
1587 Value = PHI;
1588 }
1589
1590 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001591}