blob: 4d5f8827de228bac9e648185a8c39a847e30a27a [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 Carlsson16d81b82009-09-22 22:53:17 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson3b5ad222010-01-01 20:29:01 +000023RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24 llvm::Value *Callee,
25 ReturnValueSlot ReturnValue,
26 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000027 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000028 CallExpr::const_arg_iterator ArgBeg,
29 CallExpr::const_arg_iterator ArgEnd) {
30 assert(MD->isInstance() &&
31 "Trying to emit a member call expr on a static method!");
32
33 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
34
35 CallArgList Args;
36
37 // Push the this ptr.
38 Args.push_back(std::make_pair(RValue::get(This),
39 MD->getThisType(getContext())));
40
Anders Carlssonc997d422010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
44 Args.push_back(std::make_pair(RValue::get(VTT), T));
45 }
46
Anders Carlsson3b5ad222010-01-01 20:29:01 +000047 // And the rest of the call args
48 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49
John McCall04a67a62010-02-05 21:31:56 +000050 QualType ResultType = FPT->getResultType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000051 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
52 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000053 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000054}
55
Anders Carlsson1679f5a2011-01-29 03:52:01 +000056static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000057 const Expr *E = Base;
58
59 while (true) {
60 E = E->IgnoreParens();
61 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
62 if (CE->getCastKind() == CK_DerivedToBase ||
63 CE->getCastKind() == CK_UncheckedDerivedToBase ||
64 CE->getCastKind() == CK_NoOp) {
65 E = CE->getSubExpr();
66 continue;
67 }
68 }
69
70 break;
71 }
72
73 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000074 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
75 DerivedType = PTy->getPointeeType();
76
77 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
78}
79
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000080// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
81// quite what we want.
82static const Expr *skipNoOpCastsAndParens(const Expr *E) {
83 while (true) {
84 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
85 E = PE->getSubExpr();
86 continue;
87 }
88
89 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
90 if (CE->getCastKind() == CK_NoOp) {
91 E = CE->getSubExpr();
92 continue;
93 }
94 }
95 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
96 if (UO->getOpcode() == UO_Extension) {
97 E = UO->getSubExpr();
98 continue;
99 }
100 }
101 return E;
102 }
103}
104
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000105/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
106/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000107static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
108 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000109 const CXXMethodDecl *MD) {
110
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000111 // When building with -fapple-kext, all calls must go through the vtable since
112 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000113 if (Context.getLangOptions().AppleKext)
114 return false;
115
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000116 // If the most derived class is marked final, we know that no subclass can
117 // override this member function and so we can devirtualize it. For example:
118 //
119 // struct A { virtual void f(); }
120 // struct B final : A { };
121 //
122 // void f(B *b) {
123 // b->f();
124 // }
125 //
126 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
127 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
128 return true;
129
Anders Carlssonf89e0422011-01-23 21:07:30 +0000130 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000131 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000132 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000133 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000134
Anders Carlssonf89e0422011-01-23 21:07:30 +0000135 // Similarly, if the class itself is marked 'final' it can't be overridden
136 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000137 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000138 return true;
139
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000140 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000141 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
142 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
143 // This is a record decl. We know the type and can devirtualize it.
144 return VD->getType()->isRecordType();
145 }
146
147 return false;
148 }
149
150 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000151 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000152 return true;
153
154 // And calls on bound temporaries.
155 if (isa<CXXBindTemporaryExpr>(Base))
156 return true;
157
158 // Check if this is a call expr that returns a record type.
159 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
160 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000161
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000162 // We can't devirtualize the call.
163 return false;
164}
165
Francois Pichetdbee3412011-01-18 05:04:39 +0000166// Note: This function also emit constructor calls to support a MSVC
167// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
169 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000170 const Expr *callee = CE->getCallee()->IgnoreParens();
171
172 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000174
175 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
177
Devang Patelc69e1cf2010-09-30 19:05:55 +0000178 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000179 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
180 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000181 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
182 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
183 DI->getOrCreateRecordType(PTy->getPointeeType(),
184 MD->getParent()->getLocation());
185 }
186 }
187
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000188 if (MD->isStatic()) {
189 // The method is static, emit it as we would a regular call.
190 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
191 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
192 ReturnValue, CE->arg_begin(), CE->arg_end());
193 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000194
John McCallfc400282010-09-03 01:26:39 +0000195 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000196 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000197 if (ME->isArrow())
198 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000199 else
200 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000201
John McCallfc400282010-09-03 01:26:39 +0000202 if (MD->isTrivial()) {
203 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000204 if (isa<CXXConstructorDecl>(MD) &&
205 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
206 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000207
Francois Pichetdbee3412011-01-18 05:04:39 +0000208 if (MD->isCopyAssignmentOperator()) {
209 // We don't like to generate the trivial copy assignment operator when
210 // it isn't necessary; just produce the proper effect here.
211 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
212 EmitAggregateCopy(This, RHS, CE->getType());
213 return RValue::get(This);
214 }
215
216 if (isa<CXXConstructorDecl>(MD) &&
217 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
218 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
219 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
220 CE->arg_begin(), CE->arg_end());
221 return RValue::get(This);
222 }
223 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000224 }
225
John McCallfc400282010-09-03 01:26:39 +0000226 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000227 const CGFunctionInfo *FInfo = 0;
228 if (isa<CXXDestructorDecl>(MD))
229 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
230 Dtor_Complete);
231 else if (isa<CXXConstructorDecl>(MD))
232 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
233 Ctor_Complete);
234 else
235 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000236
237 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
238 const llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000239 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000240
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000241 // C++ [class.virtual]p12:
242 // Explicit qualification with the scope operator (5.1) suppresses the
243 // virtual call mechanism.
244 //
245 // We also don't emit a virtual call if the base expression has a record type
246 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000247 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000248 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
249 && !canDevirtualizeMemberFunctionCalls(getContext(),
250 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000251 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000252 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
253 if (UseVirtualCall) {
254 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000255 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000256 if (getContext().getLangOptions().AppleKext &&
257 MD->isVirtual() &&
258 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000259 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000260 else
261 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000262 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000263 } else if (const CXXConstructorDecl *Ctor =
264 dyn_cast<CXXConstructorDecl>(MD)) {
265 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000266 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000267 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000268 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000269 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000270 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000271 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000272 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000273 else
274 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000275 }
276
Anders Carlssonc997d422010-01-02 01:01:18 +0000277 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000278 CE->arg_begin(), CE->arg_end());
279}
280
281RValue
282CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
283 ReturnValueSlot ReturnValue) {
284 const BinaryOperator *BO =
285 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
286 const Expr *BaseExpr = BO->getLHS();
287 const Expr *MemFnExpr = BO->getRHS();
288
289 const MemberPointerType *MPT =
290 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000291
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000292 const FunctionProtoType *FPT =
293 MPT->getPointeeType()->getAs<FunctionProtoType>();
294 const CXXRecordDecl *RD =
295 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
296
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000297 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000298 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000299
300 // Emit the 'this' pointer.
301 llvm::Value *This;
302
John McCall2de56d12010-08-25 11:45:40 +0000303 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000304 This = EmitScalarExpr(BaseExpr);
305 else
306 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000307
John McCall93d557b2010-08-22 00:05:51 +0000308 // Ask the ABI to load the callee. Note that This is modified.
309 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000310 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000311
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000312 CallArgList Args;
313
314 QualType ThisType =
315 getContext().getPointerType(getContext().getTagDeclType(RD));
316
317 // Push the this ptr.
318 Args.push_back(std::make_pair(RValue::get(This), ThisType));
319
320 // And the rest of the call args
321 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall04a67a62010-02-05 21:31:56 +0000322 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000323 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
324 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000325}
326
327RValue
328CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
329 const CXXMethodDecl *MD,
330 ReturnValueSlot ReturnValue) {
331 assert(MD->isInstance() &&
332 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000333 LValue LV = EmitLValue(E->getArg(0));
334 llvm::Value *This = LV.getAddress();
335
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000336 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000337 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
338 if (ClassDecl->hasTrivialCopyAssignment()) {
339 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
340 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000341 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
342 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000343 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344 return RValue::get(This);
345 }
346 }
347
348 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
349 const llvm::Type *Ty =
350 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
351 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000352 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000353 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000354 !canDevirtualizeMemberFunctionCalls(getContext(),
355 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000356 Callee = BuildVirtualCall(MD, This, Ty);
357 else
358 Callee = CGM.GetAddrOfFunction(MD, Ty);
359
Anders Carlssonc997d422010-01-02 01:01:18 +0000360 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000361 E->arg_begin() + 1, E->arg_end());
362}
363
364void
John McCall558d2ab2010-09-15 10:14:12 +0000365CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
366 AggValueSlot Dest) {
367 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000368 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000369
370 // If we require zero initialization before (or instead of) calling the
371 // constructor, as can be the case with a non-user-provided default
372 // constructor, emit the zero initialization now.
373 if (E->requiresZeroInitialization())
John McCall558d2ab2010-09-15 10:14:12 +0000374 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000375
376 // If this is a call to a trivial default constructor, do nothing.
377 if (CD->isTrivial() && CD->isDefaultConstructor())
378 return;
379
John McCallfc1e6c72010-09-18 00:58:34 +0000380 // Elide the constructor if we're constructing from a temporary.
381 // The temporary check is required because Sema sets this on NRVO
382 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000383 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000384 assert(getContext().hasSameUnqualifiedType(E->getType(),
385 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000386 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
387 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000388 return;
389 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000390 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000391
392 const ConstantArrayType *Array
393 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000394 if (Array) {
395 QualType BaseElementTy = getContext().getBaseElementType(Array);
396 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
397 BasePtr = llvm::PointerType::getUnqual(BasePtr);
398 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000399 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000400
401 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
402 E->arg_begin(), E->arg_end());
403 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000404 else {
405 CXXCtorType Type =
406 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
407 ? Ctor_Complete : Ctor_Base;
408 bool ForVirtualBase =
409 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
410
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000411 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000412 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000413 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000414 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000415}
416
Fariborz Jahanian34999872010-11-13 21:53:34 +0000417void
418CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
419 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000420 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000421 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000422 Exp = E->getSubExpr();
423 assert(isa<CXXConstructExpr>(Exp) &&
424 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
425 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
426 const CXXConstructorDecl *CD = E->getConstructor();
427 RunCleanupsScope Scope(*this);
428
429 // If we require zero initialization before (or instead of) calling the
430 // constructor, as can be the case with a non-user-provided default
431 // constructor, emit the zero initialization now.
432 // FIXME. Do I still need this for a copy ctor synthesis?
433 if (E->requiresZeroInitialization())
434 EmitNullInitialization(Dest, E->getType());
435
Chandler Carruth858a5462010-11-15 13:54:43 +0000436 assert(!getContext().getAsConstantArrayType(E->getType())
437 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000438 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
439 E->arg_begin(), E->arg_end());
440}
441
John McCall5172ed92010-08-23 01:17:59 +0000442/// Check whether the given operator new[] is the global placement
443/// operator new[].
444static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
445 const FunctionDecl *Fn) {
446 // Must be in global scope. Note that allocation functions can't be
447 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000448 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000449 return false;
450
451 // Signature must be void *operator new[](size_t, void*).
452 // The size_t is common to all operator new[]s.
453 if (Fn->getNumParams() != 2)
454 return false;
455
456 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
457 return (ParamType == Ctx.VoidPtrTy);
458}
459
John McCall1e7fe752010-09-02 09:58:18 +0000460static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
461 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000462 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000463 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000464
Anders Carlssondd937552009-12-13 20:34:34 +0000465 // No cookie is required if the new operator being used is
466 // ::operator new[](size_t, void*).
467 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000468 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000469 return CharUnits::Zero();
470
John McCall6ec278d2011-01-27 09:37:56 +0000471 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000472}
473
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000474static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000475 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000476 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000477 llvm::Value *&NumElements,
478 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000479 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000480
481 const llvm::IntegerType *SizeTy =
482 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000483
John McCall1e7fe752010-09-02 09:58:18 +0000484 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
485
Douglas Gregor59174c02010-07-21 01:10:17 +0000486 if (!E->isArray()) {
487 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
488 return SizeWithoutCookie;
489 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000490
John McCall1e7fe752010-09-02 09:58:18 +0000491 // Figure out the cookie size.
492 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
493
Anders Carlssona4d4c012009-09-23 16:07:23 +0000494 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000495 // We multiply the size of all dimensions for NumElements.
496 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000497 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000498 assert(NumElements->getType() == SizeTy && "element count not a size_t");
499
500 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000501 while (const ConstantArrayType *CAT
502 = CGF.getContext().getAsConstantArrayType(ElemType)) {
503 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000504 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000505 }
506
John McCall1e7fe752010-09-02 09:58:18 +0000507 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000508
Chris Lattner806941e2010-07-20 21:55:52 +0000509 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
510 // Don't bloat the -O0 code.
511 if (llvm::ConstantInt *NumElementsC =
512 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000513 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000514 unsigned SizeWidth = NEC.getBitWidth();
515
516 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000517 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000518 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000519 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000520
521 if (!CookieSize.isZero()) {
522 // Save the current size without a cookie. We don't care if an
523 // overflow's already happened because SizeWithoutCookie isn't
524 // used if the allocator returns null or throws, as it should
525 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000526 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000527 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
528
529 // Add the cookie size.
530 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000531 }
532
John McCall1e7fe752010-09-02 09:58:18 +0000533 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000534 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000535 Size = llvm::ConstantInt::get(SizeTy, SC);
536 } else {
537 // On overflow, produce a -1 so operator new throws.
538 Size = llvm::Constant::getAllOnesValue(SizeTy);
539 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000540
John McCall1e7fe752010-09-02 09:58:18 +0000541 // Scale NumElements while we're at it.
542 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
543 NumElements = llvm::ConstantInt::get(SizeTy, N);
544
545 // Otherwise, we don't need to do an overflow-checked multiplication if
546 // we're multiplying by one.
547 } else if (TypeSize.isOne()) {
548 assert(ArraySizeMultiplier == 1);
549
550 Size = NumElements;
551
552 // If we need a cookie, add its size in with an overflow check.
553 // This is maybe a little paranoid.
554 if (!CookieSize.isZero()) {
555 SizeWithoutCookie = Size;
556
557 llvm::Value *CookieSizeV
558 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
559
560 const llvm::Type *Types[] = { SizeTy };
561 llvm::Value *UAddF
562 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
563 llvm::Value *AddRes
564 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
565
566 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
567 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
568 Size = CGF.Builder.CreateSelect(DidOverflow,
569 llvm::ConstantInt::get(SizeTy, -1),
570 Size);
571 }
572
573 // Otherwise use the int.umul.with.overflow intrinsic.
574 } else {
575 llvm::Value *OutermostElementSize
576 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
577
578 llvm::Value *NumOutermostElements = NumElements;
579
580 // Scale NumElements by the array size multiplier. This might
581 // overflow, but only if the multiplication below also overflows,
582 // in which case this multiplication isn't used.
583 if (ArraySizeMultiplier != 1)
584 NumElements = CGF.Builder.CreateMul(NumElements,
585 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
586
587 // The requested size of the outermost array is non-constant.
588 // Multiply that by the static size of the elements of that array;
589 // on unsigned overflow, set the size to -1 to trigger an
590 // exception from the allocation routine. This is sufficient to
591 // prevent buffer overruns from the allocator returning a
592 // seemingly valid pointer to insufficient space. This idea comes
593 // originally from MSVC, and GCC has an open bug requesting
594 // similar behavior:
595 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
596 //
597 // This will not be sufficient for C++0x, which requires a
598 // specific exception class (std::bad_array_new_length).
599 // That will require ABI support that has not yet been specified.
600 const llvm::Type *Types[] = { SizeTy };
601 llvm::Value *UMulF
602 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
603 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
604 OutermostElementSize);
605
606 // The overflow bit.
607 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
608
609 // The result of the multiplication.
610 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
611
612 // If we have a cookie, we need to add that size in, too.
613 if (!CookieSize.isZero()) {
614 SizeWithoutCookie = Size;
615
616 llvm::Value *CookieSizeV
617 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
618 llvm::Value *UAddF
619 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
620 llvm::Value *AddRes
621 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
622
623 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
624
625 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedman5536daa2011-04-09 19:54:33 +0000626 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall1e7fe752010-09-02 09:58:18 +0000627 }
628
629 Size = CGF.Builder.CreateSelect(DidOverflow,
630 llvm::ConstantInt::get(SizeTy, -1),
631 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000632 }
John McCall1e7fe752010-09-02 09:58:18 +0000633
634 if (CookieSize.isZero())
635 SizeWithoutCookie = Size;
636 else
637 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
638
Chris Lattner806941e2010-07-20 21:55:52 +0000639 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000640}
641
Fariborz Jahanianef668722010-06-25 18:26:07 +0000642static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
643 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000644
645 assert(E->getNumConstructorArgs() == 1 &&
646 "Can only have one argument to initializer of POD type.");
647
648 const Expr *Init = E->getConstructorArg(0);
649 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000650
651 unsigned Alignment =
652 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000653 if (!CGF.hasAggregateLLVMType(AllocType))
654 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000655 AllocType.isVolatileQualified(), Alignment,
656 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000657 else if (AllocType->isAnyComplexType())
658 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
659 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000660 else {
661 AggValueSlot Slot
662 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
663 CGF.EmitAggExpr(Init, Slot);
664 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000665}
666
667void
668CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
669 llvm::Value *NewPtr,
670 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000671 // We have a POD type.
672 if (E->getNumConstructorArgs() == 0)
673 return;
674
Fariborz Jahanianef668722010-06-25 18:26:07 +0000675 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
676
677 // Create a temporary for the loop index and initialize it with 0.
678 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
679 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
680 Builder.CreateStore(Zero, IndexPtr);
681
682 // Start the loop with a block that tests the condition.
683 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
684 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
685
686 EmitBlock(CondBlock);
687
688 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
689
690 // Generate: if (loop-index < number-of-elements fall to the loop body,
691 // otherwise, go to the block after the for-loop.
692 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
693 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
694 // If the condition is true, execute the body.
695 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
696
697 EmitBlock(ForBody);
698
699 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
700 // Inside the loop body, emit the constructor call on the array element.
701 Counter = Builder.CreateLoad(IndexPtr);
702 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
703 "arrayidx");
704 StoreAnyExprIntoOneUnit(*this, E, Address);
705
706 EmitBlock(ContinueBlock);
707
708 // Emit the increment of the loop counter.
709 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
710 Counter = Builder.CreateLoad(IndexPtr);
711 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
712 Builder.CreateStore(NextVal, IndexPtr);
713
714 // Finally, branch back up to the condition for the next iteration.
715 EmitBranch(CondBlock);
716
717 // Emit the fall-through block.
718 EmitBlock(AfterFor, true);
719}
720
Douglas Gregor59174c02010-07-21 01:10:17 +0000721static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
722 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000723 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000724 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000725 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000726 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000727}
728
Anders Carlssona4d4c012009-09-23 16:07:23 +0000729static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
730 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000731 llvm::Value *NumElements,
732 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000733 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000734 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000735 bool RequiresZeroInitialization = false;
736 if (Ctor->getParent()->hasTrivialConstructor()) {
737 // If new expression did not specify value-initialization, then there
738 // is no initialization.
739 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
740 return;
741
John McCallf16aa102010-08-22 21:01:12 +0000742 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000743 // Optimization: since zero initialization will just set the memory
744 // to all zeroes, generate a single memset to do it in one shot.
745 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
746 AllocSizeWithoutCookie);
747 return;
748 }
749
750 RequiresZeroInitialization = true;
751 }
752
753 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
754 E->constructor_arg_begin(),
755 E->constructor_arg_end(),
756 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000757 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000758 } else if (E->getNumConstructorArgs() == 1 &&
759 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
760 // Optimization: since zero initialization will just set the memory
761 // to all zeroes, generate a single memset to do it in one shot.
762 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
763 AllocSizeWithoutCookie);
764 return;
765 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000766 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
767 return;
768 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000769 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000770
771 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000772 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
773 // direct initialization. C++ [dcl.init]p5 requires that we
774 // zero-initialize storage if there are no user-declared constructors.
775 if (E->hasInitializer() &&
776 !Ctor->getParent()->hasUserDeclaredConstructor() &&
777 !Ctor->getParent()->isEmpty())
778 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
779
Douglas Gregor84745672010-07-07 23:37:33 +0000780 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
781 NewPtr, E->constructor_arg_begin(),
782 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000783
784 return;
785 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000786 // We have a POD type.
787 if (E->getNumConstructorArgs() == 0)
788 return;
789
Fariborz Jahanianef668722010-06-25 18:26:07 +0000790 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000791}
792
John McCall7d8647f2010-09-14 07:57:04 +0000793namespace {
794 /// A cleanup to call the given 'operator delete' function upon
795 /// abnormal exit from a new expression.
796 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
797 size_t NumPlacementArgs;
798 const FunctionDecl *OperatorDelete;
799 llvm::Value *Ptr;
800 llvm::Value *AllocSize;
801
802 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
803
804 public:
805 static size_t getExtraSize(size_t NumPlacementArgs) {
806 return NumPlacementArgs * sizeof(RValue);
807 }
808
809 CallDeleteDuringNew(size_t NumPlacementArgs,
810 const FunctionDecl *OperatorDelete,
811 llvm::Value *Ptr,
812 llvm::Value *AllocSize)
813 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
814 Ptr(Ptr), AllocSize(AllocSize) {}
815
816 void setPlacementArg(unsigned I, RValue Arg) {
817 assert(I < NumPlacementArgs && "index out of range");
818 getPlacementArgs()[I] = Arg;
819 }
820
821 void Emit(CodeGenFunction &CGF, bool IsForEH) {
822 const FunctionProtoType *FPT
823 = OperatorDelete->getType()->getAs<FunctionProtoType>();
824 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000825 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000826
827 CallArgList DeleteArgs;
828
829 // The first argument is always a void*.
830 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
831 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
832
833 // A member 'operator delete' can take an extra 'size_t' argument.
834 if (FPT->getNumArgs() == NumPlacementArgs + 2)
835 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
836
837 // Pass the rest of the arguments, which must match exactly.
838 for (unsigned I = 0; I != NumPlacementArgs; ++I)
839 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
840
841 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000842 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000843 CGF.CGM.GetAddrOfFunction(OperatorDelete),
844 ReturnValueSlot(), DeleteArgs, OperatorDelete);
845 }
846 };
John McCall3019c442010-09-17 00:50:28 +0000847
848 /// A cleanup to call the given 'operator delete' function upon
849 /// abnormal exit from a new expression when the new expression is
850 /// conditional.
851 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
852 size_t NumPlacementArgs;
853 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000854 DominatingValue<RValue>::saved_type Ptr;
855 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000856
John McCall804b8072011-01-28 10:53:53 +0000857 DominatingValue<RValue>::saved_type *getPlacementArgs() {
858 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000859 }
860
861 public:
862 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000863 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000864 }
865
866 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
867 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000868 DominatingValue<RValue>::saved_type Ptr,
869 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000870 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
871 Ptr(Ptr), AllocSize(AllocSize) {}
872
John McCall804b8072011-01-28 10:53:53 +0000873 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000874 assert(I < NumPlacementArgs && "index out of range");
875 getPlacementArgs()[I] = Arg;
876 }
877
878 void Emit(CodeGenFunction &CGF, bool IsForEH) {
879 const FunctionProtoType *FPT
880 = OperatorDelete->getType()->getAs<FunctionProtoType>();
881 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
882 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
883
884 CallArgList DeleteArgs;
885
886 // The first argument is always a void*.
887 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCall804b8072011-01-28 10:53:53 +0000888 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall3019c442010-09-17 00:50:28 +0000889
890 // A member 'operator delete' can take an extra 'size_t' argument.
891 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000892 RValue RV = AllocSize.restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000893 DeleteArgs.push_back(std::make_pair(RV, *AI++));
894 }
895
896 // Pass the rest of the arguments, which must match exactly.
897 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000898 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000899 DeleteArgs.push_back(std::make_pair(RV, *AI++));
900 }
901
902 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000903 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000904 CGF.CGM.GetAddrOfFunction(OperatorDelete),
905 ReturnValueSlot(), DeleteArgs, OperatorDelete);
906 }
907 };
908}
909
910/// Enter a cleanup to call 'operator delete' if the initializer in a
911/// new-expression throws.
912static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
913 const CXXNewExpr *E,
914 llvm::Value *NewPtr,
915 llvm::Value *AllocSize,
916 const CallArgList &NewArgs) {
917 // If we're not inside a conditional branch, then the cleanup will
918 // dominate and we can do the easier (and more efficient) thing.
919 if (!CGF.isInConditionalBranch()) {
920 CallDeleteDuringNew *Cleanup = CGF.EHStack
921 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
922 E->getNumPlacementArgs(),
923 E->getOperatorDelete(),
924 NewPtr, AllocSize);
925 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
926 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
927
928 return;
929 }
930
931 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000932 DominatingValue<RValue>::saved_type SavedNewPtr =
933 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
934 DominatingValue<RValue>::saved_type SavedAllocSize =
935 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000936
937 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
938 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
939 E->getNumPlacementArgs(),
940 E->getOperatorDelete(),
941 SavedNewPtr,
942 SavedAllocSize);
943 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000944 Cleanup->setPlacementArg(I,
945 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000946
947 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000948}
949
Anders Carlsson16d81b82009-09-22 22:53:17 +0000950llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000951 // The element type being allocated.
952 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +0000953
John McCallc2f3e7f2011-03-07 03:12:35 +0000954 // 1. Build a call to the allocation function.
955 FunctionDecl *allocator = E->getOperatorNew();
956 const FunctionProtoType *allocatorType =
957 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000958
John McCallc2f3e7f2011-03-07 03:12:35 +0000959 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000960
961 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000962 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000963
John McCallc2f3e7f2011-03-07 03:12:35 +0000964 llvm::Value *numElements = 0;
965 llvm::Value *allocSizeWithoutCookie = 0;
966 llvm::Value *allocSize =
967 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
968 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000969
John McCallc2f3e7f2011-03-07 03:12:35 +0000970 allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000971
972 // Emit the rest of the arguments.
973 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +0000974 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000975
976 // First, use the types from the function type.
977 // We start at 1 here because the first argument (the allocation size)
978 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +0000979 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
980 ++i, ++placementArg) {
981 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000982
John McCallc2f3e7f2011-03-07 03:12:35 +0000983 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
984 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +0000985 "type mismatch in call argument!");
986
John McCall413ebdb2011-03-11 20:59:21 +0000987 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000988 }
989
990 // Either we've emitted all the call args, or we have a call to a
991 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +0000992 assert((placementArg == E->placement_arg_end() ||
993 allocatorType->isVariadic()) &&
994 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +0000995
996 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000997 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
998 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +0000999 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001000 }
1001
John McCallc2f3e7f2011-03-07 03:12:35 +00001002 // Emit the allocation call.
Anders Carlsson16d81b82009-09-22 22:53:17 +00001003 RValue RV =
John McCallc2f3e7f2011-03-07 03:12:35 +00001004 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1005 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1006 allocatorArgs, allocator);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001007
John McCallc2f3e7f2011-03-07 03:12:35 +00001008 // Emit a null check on the allocation result if the allocation
1009 // function is allowed to return null (because it has a non-throwing
1010 // exception spec; for this part, we inline
1011 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1012 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001013 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallc2f3e7f2011-03-07 03:12:35 +00001014 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001015
John McCallc2f3e7f2011-03-07 03:12:35 +00001016 llvm::BasicBlock *nullCheckBB = 0;
1017 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001018
John McCallc2f3e7f2011-03-07 03:12:35 +00001019 llvm::Value *allocation = RV.getScalarVal();
1020 unsigned AS =
1021 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001022
John McCalla7f633f2011-03-07 01:52:56 +00001023 // The null-check means that the initializer is conditionally
1024 // evaluated.
1025 ConditionalEvaluation conditional(*this);
1026
John McCallc2f3e7f2011-03-07 03:12:35 +00001027 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001028 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001029
1030 nullCheckBB = Builder.GetInsertBlock();
1031 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1032 contBB = createBasicBlock("new.cont");
1033
1034 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1035 Builder.CreateCondBr(isNull, contBB, notNullBB);
1036 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001037 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001038
John McCallc2f3e7f2011-03-07 03:12:35 +00001039 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001040 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001041 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001042 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001043 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1044 numElements,
1045 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001046 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001047
John McCall7d8647f2010-09-14 07:57:04 +00001048 // If there's an operator delete, enter a cleanup to call it if an
1049 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001050 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7d8647f2010-09-14 07:57:04 +00001051 if (E->getOperatorDelete()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001052 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1053 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001054 }
1055
John McCallc2f3e7f2011-03-07 03:12:35 +00001056 const llvm::Type *elementPtrTy
1057 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1058 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001059
John McCall1e7fe752010-09-02 09:58:18 +00001060 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001061 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001062
1063 // NewPtr is a pointer to the base element type. If we're
1064 // allocating an array of arrays, we'll need to cast back to the
1065 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001066 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1067 if (result->getType() != resultType)
1068 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001069 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001070 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001071 }
John McCall7d8647f2010-09-14 07:57:04 +00001072
1073 // Deactivate the 'operator delete' cleanup if we finished
1074 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001075 if (operatorDeleteCleanup.isValid())
1076 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001077
John McCallc2f3e7f2011-03-07 03:12:35 +00001078 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001079 conditional.end(*this);
1080
John McCallc2f3e7f2011-03-07 03:12:35 +00001081 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1082 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001083
Jay Foadbbf3bac2011-03-30 11:28:58 +00001084 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001085 PHI->addIncoming(result, notNullBB);
1086 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1087 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001088
John McCallc2f3e7f2011-03-07 03:12:35 +00001089 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001090 }
John McCall1e7fe752010-09-02 09:58:18 +00001091
John McCallc2f3e7f2011-03-07 03:12:35 +00001092 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001093}
1094
Eli Friedman5fe05982009-11-18 00:50:08 +00001095void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1096 llvm::Value *Ptr,
1097 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001098 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1099
Eli Friedman5fe05982009-11-18 00:50:08 +00001100 const FunctionProtoType *DeleteFTy =
1101 DeleteFD->getType()->getAs<FunctionProtoType>();
1102
1103 CallArgList DeleteArgs;
1104
Anders Carlsson871d0782009-12-13 20:04:38 +00001105 // Check if we need to pass the size to the delete operator.
1106 llvm::Value *Size = 0;
1107 QualType SizeTy;
1108 if (DeleteFTy->getNumArgs() == 2) {
1109 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001110 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1111 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1112 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001113 }
1114
Eli Friedman5fe05982009-11-18 00:50:08 +00001115 QualType ArgTy = DeleteFTy->getArgType(0);
1116 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1117 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1118
Anders Carlsson871d0782009-12-13 20:04:38 +00001119 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +00001120 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +00001121
1122 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001123 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001124 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001125 DeleteArgs, DeleteFD);
1126}
1127
John McCall1e7fe752010-09-02 09:58:18 +00001128namespace {
1129 /// Calls the given 'operator delete' on a single object.
1130 struct CallObjectDelete : EHScopeStack::Cleanup {
1131 llvm::Value *Ptr;
1132 const FunctionDecl *OperatorDelete;
1133 QualType ElementType;
1134
1135 CallObjectDelete(llvm::Value *Ptr,
1136 const FunctionDecl *OperatorDelete,
1137 QualType ElementType)
1138 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1139
1140 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1141 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1142 }
1143 };
1144}
1145
1146/// Emit the code for deleting a single object.
1147static void EmitObjectDelete(CodeGenFunction &CGF,
1148 const FunctionDecl *OperatorDelete,
1149 llvm::Value *Ptr,
1150 QualType ElementType) {
1151 // Find the destructor for the type, if applicable. If the
1152 // destructor is virtual, we'll just emit the vcall and return.
1153 const CXXDestructorDecl *Dtor = 0;
1154 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1155 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1156 if (!RD->hasTrivialDestructor()) {
1157 Dtor = RD->getDestructor();
1158
1159 if (Dtor->isVirtual()) {
1160 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001161 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1162 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001163 /*isVariadic=*/false);
1164
1165 llvm::Value *Callee
1166 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1167 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1168 0, 0);
1169
1170 // The dtor took care of deleting the object.
1171 return;
1172 }
1173 }
1174 }
1175
1176 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001177 // This doesn't have to a conditional cleanup because we're going
1178 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001179 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1180 Ptr, OperatorDelete, ElementType);
1181
1182 if (Dtor)
1183 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1184 /*ForVirtualBase=*/false, Ptr);
1185
1186 CGF.PopCleanupBlock();
1187}
1188
1189namespace {
1190 /// Calls the given 'operator delete' on an array of objects.
1191 struct CallArrayDelete : EHScopeStack::Cleanup {
1192 llvm::Value *Ptr;
1193 const FunctionDecl *OperatorDelete;
1194 llvm::Value *NumElements;
1195 QualType ElementType;
1196 CharUnits CookieSize;
1197
1198 CallArrayDelete(llvm::Value *Ptr,
1199 const FunctionDecl *OperatorDelete,
1200 llvm::Value *NumElements,
1201 QualType ElementType,
1202 CharUnits CookieSize)
1203 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1204 ElementType(ElementType), CookieSize(CookieSize) {}
1205
1206 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1207 const FunctionProtoType *DeleteFTy =
1208 OperatorDelete->getType()->getAs<FunctionProtoType>();
1209 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1210
1211 CallArgList Args;
1212
1213 // Pass the pointer as the first argument.
1214 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1215 llvm::Value *DeletePtr
1216 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1217 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1218
1219 // Pass the original requested size as the second argument.
1220 if (DeleteFTy->getNumArgs() == 2) {
1221 QualType size_t = DeleteFTy->getArgType(1);
1222 const llvm::IntegerType *SizeTy
1223 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1224
1225 CharUnits ElementTypeSize =
1226 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1227
1228 // The size of an element, multiplied by the number of elements.
1229 llvm::Value *Size
1230 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1231 Size = CGF.Builder.CreateMul(Size, NumElements);
1232
1233 // Plus the size of the cookie if applicable.
1234 if (!CookieSize.isZero()) {
1235 llvm::Value *CookieSizeV
1236 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1237 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1238 }
1239
1240 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1241 }
1242
1243 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001244 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001245 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1246 ReturnValueSlot(), Args, OperatorDelete);
1247 }
1248 };
1249}
1250
1251/// Emit the code for deleting an array of objects.
1252static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001253 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001254 llvm::Value *Ptr,
1255 QualType ElementType) {
1256 llvm::Value *NumElements = 0;
1257 llvm::Value *AllocatedPtr = 0;
1258 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001259 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001260 NumElements, AllocatedPtr, CookieSize);
1261
1262 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1263
1264 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001265 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001266 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1267 AllocatedPtr, OperatorDelete,
1268 NumElements, ElementType,
1269 CookieSize);
1270
1271 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1272 if (!RD->hasTrivialDestructor()) {
1273 assert(NumElements && "ReadArrayCookie didn't find element count"
1274 " for a class with destructor");
1275 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1276 }
1277 }
1278
1279 CGF.PopCleanupBlock();
1280}
1281
Anders Carlsson16d81b82009-09-22 22:53:17 +00001282void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001283
Douglas Gregor90916562009-09-29 18:16:17 +00001284 // Get at the argument before we performed the implicit conversion
1285 // to void*.
1286 const Expr *Arg = E->getArgument();
1287 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001288 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001289 ICE->getType()->isVoidPointerType())
1290 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001291 else
1292 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001293 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001294
Douglas Gregor90916562009-09-29 18:16:17 +00001295 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001296
1297 // Null check the pointer.
1298 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1299 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1300
Anders Carlssonb9241242011-04-11 00:30:07 +00001301 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001302
1303 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1304 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001305
John McCall1e7fe752010-09-02 09:58:18 +00001306 // We might be deleting a pointer to array. If so, GEP down to the
1307 // first non-array element.
1308 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1309 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1310 if (DeleteTy->isConstantArrayType()) {
1311 llvm::Value *Zero = Builder.getInt32(0);
1312 llvm::SmallVector<llvm::Value*,8> GEP;
1313
1314 GEP.push_back(Zero); // point at the outermost array
1315
1316 // For each layer of array type we're pointing at:
1317 while (const ConstantArrayType *Arr
1318 = getContext().getAsConstantArrayType(DeleteTy)) {
1319 // 1. Unpeel the array type.
1320 DeleteTy = Arr->getElementType();
1321
1322 // 2. GEP to the first element of the array.
1323 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001324 }
John McCall1e7fe752010-09-02 09:58:18 +00001325
1326 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001327 }
1328
Douglas Gregoreede61a2010-09-02 17:38:50 +00001329 assert(ConvertTypeForMem(DeleteTy) ==
1330 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001331
1332 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001333 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001334 } else {
1335 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1336 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001337
Anders Carlsson16d81b82009-09-22 22:53:17 +00001338 EmitBlock(DeleteEnd);
1339}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001340
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001341static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1342 // void __cxa_bad_typeid();
1343
1344 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1345 const llvm::FunctionType *FTy =
1346 llvm::FunctionType::get(VoidTy, false);
1347
1348 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1349}
1350
1351static void EmitBadTypeidCall(CodeGenFunction &CGF) {
1352 llvm::Value *F = getBadTypeidFn(CGF);
1353 if (llvm::BasicBlock *InvokeDest = CGF.getInvokeDest()) {
1354 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
1355 CGF.Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1356 CGF.EmitBlock(Cont);
1357 } else
1358 CGF.Builder.CreateCall(F)->setDoesNotReturn();
1359
1360 CGF.Builder.CreateUnreachable();
1361}
1362
John McCall3ad32c82011-01-28 08:37:24 +00001363llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001364 QualType Ty = E->getType();
1365 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001366
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001367 if (E->isTypeOperand()) {
1368 llvm::Constant *TypeInfo =
1369 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1370 return Builder.CreateBitCast(TypeInfo, LTy);
1371 }
1372
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001373 Expr *subE = E->getExprOperand();
Mike Stump5fae8562009-11-17 22:33:00 +00001374 Ty = subE->getType();
1375 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1376 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001377 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1378 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1379 if (RD->isPolymorphic()) {
1380 // FIXME: if subE is an lvalue do
1381 LValue Obj = EmitLValue(subE);
1382 llvm::Value *This = Obj.getAddress();
Mike Stumpf549e892009-11-15 16:52:53 +00001383 // We need to do a zero check for *p, unless it has NonNullAttr.
1384 // FIXME: PointerType->hasAttr<NonNullAttr>()
1385 bool CanBeZero = false;
Mike Stumpdb519a42009-11-17 00:45:21 +00001386 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +00001387 if (UO->getOpcode() == UO_Deref)
Mike Stumpf549e892009-11-15 16:52:53 +00001388 CanBeZero = true;
1389 if (CanBeZero) {
1390 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1391 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1392
Dan Gohman043fb9a2010-10-26 18:44:08 +00001393 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1394 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stumpf549e892009-11-15 16:52:53 +00001395 NonZeroBlock, ZeroBlock);
1396 EmitBlock(ZeroBlock);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001397
1398 EmitBadTypeidCall(*this);
1399
Mike Stumpf549e892009-11-15 16:52:53 +00001400 EmitBlock(NonZeroBlock);
1401 }
Dan Gohman043fb9a2010-10-26 18:44:08 +00001402 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001403 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1404 V = Builder.CreateLoad(V);
1405 return V;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001406 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001407 }
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001408 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001409}
Mike Stumpc849c052009-11-16 06:50:58 +00001410
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001411static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1412 // void *__dynamic_cast(const void *sub,
1413 // const abi::__class_type_info *src,
1414 // const abi::__class_type_info *dst,
1415 // std::ptrdiff_t src2dst_offset);
1416
1417 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1418 const llvm::Type *PtrDiffTy =
1419 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1420
1421 const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1422
1423 const llvm::FunctionType *FTy =
1424 llvm::FunctionType::get(Int8PtrTy, Args, false);
1425
1426 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1427}
1428
1429static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1430 // void __cxa_bad_cast();
1431
1432 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1433 const llvm::FunctionType *FTy =
1434 llvm::FunctionType::get(VoidTy, false);
1435
1436 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1437}
1438
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001439static void EmitBadCastCall(CodeGenFunction &CGF) {
1440 llvm::Value *F = getBadCastFn(CGF);
1441 if (llvm::BasicBlock *InvokeDest = CGF.getInvokeDest()) {
1442 llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
1443 CGF.Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1444 CGF.EmitBlock(Cont);
1445 } else
1446 CGF.Builder.CreateCall(F)->setDoesNotReturn();
1447
1448 CGF.Builder.CreateUnreachable();
1449}
1450
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001451static llvm::Value *
1452EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1453 QualType SrcTy, QualType DestTy,
1454 llvm::BasicBlock *CastEnd) {
1455 const llvm::Type *PtrDiffLTy =
1456 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1457 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1458
1459 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1460 if (PTy->getPointeeType()->isVoidType()) {
1461 // C++ [expr.dynamic.cast]p7:
1462 // If T is "pointer to cv void," then the result is a pointer to the
1463 // most derived object pointed to by v.
1464
1465 // Get the vtable pointer.
1466 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1467
1468 // Get the offset-to-top from the vtable.
1469 llvm::Value *OffsetToTop =
1470 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1471 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1472
1473 // Finally, add the offset to the pointer.
1474 Value = CGF.EmitCastToVoidPtr(Value);
1475 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1476
1477 return CGF.Builder.CreateBitCast(Value, DestLTy);
1478 }
1479 }
1480
1481 QualType SrcRecordTy;
1482 QualType DestRecordTy;
1483
1484 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1485 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1486 DestRecordTy = DestPTy->getPointeeType();
1487 } else {
1488 SrcRecordTy = SrcTy;
1489 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1490 }
1491
1492 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1493 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1494
1495 llvm::Value *SrcRTTI =
1496 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1497 llvm::Value *DestRTTI =
1498 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1499
1500 // FIXME: Actually compute a hint here.
1501 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1502
1503 // Emit the call to __dynamic_cast.
1504 Value = CGF.EmitCastToVoidPtr(Value);
1505 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1506 SrcRTTI, DestRTTI, OffsetHint);
1507 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1508
1509 /// C++ [expr.dynamic.cast]p9:
1510 /// A failed cast to reference type throws std::bad_cast
1511 if (DestTy->isReferenceType()) {
1512 llvm::BasicBlock *BadCastBlock =
1513 CGF.createBasicBlock("dynamic_cast.bad_cast");
1514
1515 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1516 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1517
1518 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001519 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001520 }
1521
1522 return Value;
1523}
1524
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001525static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1526 QualType DestTy) {
1527 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1528 if (DestTy->isPointerType())
1529 return llvm::Constant::getNullValue(DestLTy);
1530
1531 /// C++ [expr.dynamic.cast]p9:
1532 /// A failed cast to reference type throws std::bad_cast
1533 EmitBadCastCall(CGF);
1534
1535 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1536 return llvm::UndefValue::get(DestLTy);
1537}
1538
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001539llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001540 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001541 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001542
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001543 if (DCE->isAlwaysNull())
1544 return EmitDynamicCastToNull(*this, DestTy);
1545
1546 QualType SrcTy = DCE->getSubExpr()->getType();
1547
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001548 // C++ [expr.dynamic.cast]p4:
1549 // If the value of v is a null pointer value in the pointer case, the result
1550 // is the null pointer value of type T.
1551 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001552
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001553 llvm::BasicBlock *CastNull = 0;
1554 llvm::BasicBlock *CastNotNull = 0;
1555 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001556
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001557 if (ShouldNullCheckSrcValue) {
1558 CastNull = createBasicBlock("dynamic_cast.null");
1559 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1560
1561 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1562 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1563 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001564 }
1565
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001566 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1567
1568 if (ShouldNullCheckSrcValue) {
1569 EmitBranch(CastEnd);
1570
1571 EmitBlock(CastNull);
1572 EmitBranch(CastEnd);
1573 }
1574
1575 EmitBlock(CastEnd);
1576
1577 if (ShouldNullCheckSrcValue) {
1578 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1579 PHI->addIncoming(Value, CastNotNull);
1580 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1581
1582 Value = PHI;
1583 }
1584
1585 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001586}