blob: 01d671a2d9b3291e42dd2f853d5de5ba68ec15f9 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson27da15b2010-01-01 20:29:01 +000023RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24 llvm::Value *Callee,
25 ReturnValueSlot ReturnValue,
26 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000027 llvm::Value *VTT,
Anders Carlsson27da15b2010-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 Carlssone36a6b32010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
44 Args.push_back(std::make_pair(RValue::get(VTT), T));
45 }
46
Anders Carlsson27da15b2010-01-01 20:29:01 +000047 // And the rest of the call args
48 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49
John McCallab26cfa2010-02-05 21:31:56 +000050 QualType ResultType = FPT->getResultType();
51 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +000052 FPT->getExtInfo()),
53 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000054}
55
56/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
57/// expr can be devirtualized.
Anders Carlssona7911fa2010-10-27 13:28:46 +000058static bool canDevirtualizeMemberFunctionCalls(const Expr *Base,
59 const CXXMethodDecl *MD) {
60
61 // If the member function has the "final" attribute, we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +000062 // overridden and can therefore devirtualize it.
Anders Carlssona7911fa2010-10-27 13:28:46 +000063 if (MD->hasAttr<FinalAttr>())
64 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +000065
66 // Similarly, if the class itself has the "final" attribute it can't be
67 // overridden and we can therefore devirtualize the member function call.
68 if (MD->getParent()->hasAttr<FinalAttr>())
69 return true;
70
Anders Carlsson27da15b2010-01-01 20:29:01 +000071 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
72 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
73 // This is a record decl. We know the type and can devirtualize it.
74 return VD->getType()->isRecordType();
75 }
76
77 return false;
78 }
79
80 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +000081 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +000082 return true;
83
84 // And calls on bound temporaries.
85 if (isa<CXXBindTemporaryExpr>(Base))
86 return true;
87
88 // Check if this is a call expr that returns a record type.
89 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
90 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +000091
Anders Carlsson27da15b2010-01-01 20:29:01 +000092 // We can't devirtualize the call.
93 return false;
94}
95
Francois Pichet64225792011-01-18 05:04:39 +000096// Note: This function also emit constructor calls to support a MSVC
97// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +000098RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
99 ReturnValueSlot ReturnValue) {
100 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
101 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
102
103 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
104 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
105
Devang Patel91bbb552010-09-30 19:05:55 +0000106 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000107 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
108 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000109 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
110 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
111 DI->getOrCreateRecordType(PTy->getPointeeType(),
112 MD->getParent()->getLocation());
113 }
114 }
115
Anders Carlsson27da15b2010-01-01 20:29:01 +0000116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
119 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
120 ReturnValue, CE->arg_begin(), CE->arg_end());
121 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000122
John McCall0d635f52010-09-03 01:26:39 +0000123 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000124 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000125 if (ME->isArrow())
126 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000127 else
128 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000129
John McCall0d635f52010-09-03 01:26:39 +0000130 if (MD->isTrivial()) {
131 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000132 if (isa<CXXConstructorDecl>(MD) &&
133 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
134 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000135
Francois Pichet64225792011-01-18 05:04:39 +0000136 if (MD->isCopyAssignmentOperator()) {
137 // We don't like to generate the trivial copy assignment operator when
138 // it isn't necessary; just produce the proper effect here.
139 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
140 EmitAggregateCopy(This, RHS, CE->getType());
141 return RValue::get(This);
142 }
143
144 if (isa<CXXConstructorDecl>(MD) &&
145 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
146 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
147 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
148 CE->arg_begin(), CE->arg_end());
149 return RValue::get(This);
150 }
151 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000152 }
153
John McCall0d635f52010-09-03 01:26:39 +0000154 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000155 const CGFunctionInfo *FInfo = 0;
156 if (isa<CXXDestructorDecl>(MD))
157 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
158 Dtor_Complete);
159 else if (isa<CXXConstructorDecl>(MD))
160 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
161 Ctor_Complete);
162 else
163 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCall0d635f52010-09-03 01:26:39 +0000164
165 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
166 const llvm::Type *Ty
Francois Pichet64225792011-01-18 05:04:39 +0000167 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCall0d635f52010-09-03 01:26:39 +0000168
Anders Carlsson27da15b2010-01-01 20:29:01 +0000169 // C++ [class.virtual]p12:
170 // Explicit qualification with the scope operator (5.1) suppresses the
171 // virtual call mechanism.
172 //
173 // We also don't emit a virtual call if the base expression has a record type
174 // because then we know what the type is.
John McCall0d635f52010-09-03 01:26:39 +0000175 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
Anders Carlssona7911fa2010-10-27 13:28:46 +0000176 && !canDevirtualizeMemberFunctionCalls(ME->getBase(), MD);
John McCall0d635f52010-09-03 01:26:39 +0000177
Anders Carlsson27da15b2010-01-01 20:29:01 +0000178 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000179 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
180 if (UseVirtualCall) {
181 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000182 } else {
John McCall0d635f52010-09-03 01:26:39 +0000183 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000184 }
Francois Pichet64225792011-01-18 05:04:39 +0000185 } else if (const CXXConstructorDecl *Ctor =
186 dyn_cast<CXXConstructorDecl>(MD)) {
187 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000188 } else if (UseVirtualCall) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000189 Callee = BuildVirtualCall(MD, This, Ty);
190 } else {
191 Callee = CGM.GetAddrOfFunction(MD, Ty);
192 }
193
Anders Carlssone36a6b32010-01-02 01:01:18 +0000194 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000195 CE->arg_begin(), CE->arg_end());
196}
197
198RValue
199CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
200 ReturnValueSlot ReturnValue) {
201 const BinaryOperator *BO =
202 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
203 const Expr *BaseExpr = BO->getLHS();
204 const Expr *MemFnExpr = BO->getRHS();
205
206 const MemberPointerType *MPT =
207 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000208
Anders Carlsson27da15b2010-01-01 20:29:01 +0000209 const FunctionProtoType *FPT =
210 MPT->getPointeeType()->getAs<FunctionProtoType>();
211 const CXXRecordDecl *RD =
212 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
213
Anders Carlsson27da15b2010-01-01 20:29:01 +0000214 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000215 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000216
217 // Emit the 'this' pointer.
218 llvm::Value *This;
219
John McCalle3027922010-08-25 11:45:40 +0000220 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 This = EmitScalarExpr(BaseExpr);
222 else
223 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000224
John McCall475999d2010-08-22 00:05:51 +0000225 // Ask the ABI to load the callee. Note that This is modified.
226 llvm::Value *Callee =
227 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000228
Anders Carlsson27da15b2010-01-01 20:29:01 +0000229 CallArgList Args;
230
231 QualType ThisType =
232 getContext().getPointerType(getContext().getTagDeclType(RD));
233
234 // Push the this ptr.
235 Args.push_back(std::make_pair(RValue::get(This), ThisType));
236
237 // And the rest of the call args
238 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallab26cfa2010-02-05 21:31:56 +0000239 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
240 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000241 ReturnValue, Args);
242}
243
244RValue
245CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
246 const CXXMethodDecl *MD,
247 ReturnValueSlot ReturnValue) {
248 assert(MD->isInstance() &&
249 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000250 LValue LV = EmitLValue(E->getArg(0));
251 llvm::Value *This = LV.getAddress();
252
Douglas Gregorec3bec02010-09-27 22:37:28 +0000253 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000254 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
255 if (ClassDecl->hasTrivialCopyAssignment()) {
256 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
257 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000258 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
259 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000260 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000261 return RValue::get(This);
262 }
263 }
264
265 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
266 const llvm::Type *Ty =
267 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
268 FPT->isVariadic());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000269 llvm::Value *Callee;
Anders Carlssona7911fa2010-10-27 13:28:46 +0000270 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0), MD))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000271 Callee = BuildVirtualCall(MD, This, Ty);
272 else
273 Callee = CGM.GetAddrOfFunction(MD, Ty);
274
Anders Carlssone36a6b32010-01-02 01:01:18 +0000275 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 E->arg_begin() + 1, E->arg_end());
277}
278
279void
John McCall7a626f62010-09-15 10:14:12 +0000280CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
281 AggValueSlot Dest) {
282 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000283 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000284
285 // If we require zero initialization before (or instead of) calling the
286 // constructor, as can be the case with a non-user-provided default
287 // constructor, emit the zero initialization now.
288 if (E->requiresZeroInitialization())
John McCall7a626f62010-09-15 10:14:12 +0000289 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000290
291 // If this is a call to a trivial default constructor, do nothing.
292 if (CD->isTrivial() && CD->isDefaultConstructor())
293 return;
294
John McCall8ea46b62010-09-18 00:58:34 +0000295 // Elide the constructor if we're constructing from a temporary.
296 // The temporary check is required because Sema sets this on NRVO
297 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000299 assert(getContext().hasSameUnqualifiedType(E->getType(),
300 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000301 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
302 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000303 return;
304 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000306
307 const ConstantArrayType *Array
308 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000309 if (Array) {
310 QualType BaseElementTy = getContext().getBaseElementType(Array);
311 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
312 BasePtr = llvm::PointerType::getUnqual(BasePtr);
313 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000314 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000315
316 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
317 E->arg_begin(), E->arg_end());
318 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000319 else {
320 CXXCtorType Type =
321 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
322 ? Ctor_Complete : Ctor_Base;
323 bool ForVirtualBase =
324 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
325
Anders Carlsson27da15b2010-01-01 20:29:01 +0000326 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000327 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000328 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000329 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000330}
331
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000332void
333CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
334 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000335 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000336 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000337 Exp = E->getSubExpr();
338 assert(isa<CXXConstructExpr>(Exp) &&
339 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
340 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
341 const CXXConstructorDecl *CD = E->getConstructor();
342 RunCleanupsScope Scope(*this);
343
344 // If we require zero initialization before (or instead of) calling the
345 // constructor, as can be the case with a non-user-provided default
346 // constructor, emit the zero initialization now.
347 // FIXME. Do I still need this for a copy ctor synthesis?
348 if (E->requiresZeroInitialization())
349 EmitNullInitialization(Dest, E->getType());
350
Chandler Carruth99da11c2010-11-15 13:54:43 +0000351 assert(!getContext().getAsConstantArrayType(E->getType())
352 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000353 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
354 E->arg_begin(), E->arg_end());
355}
356
John McCallaa4149a2010-08-23 01:17:59 +0000357/// Check whether the given operator new[] is the global placement
358/// operator new[].
359static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
360 const FunctionDecl *Fn) {
361 // Must be in global scope. Note that allocation functions can't be
362 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000363 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000364 return false;
365
366 // Signature must be void *operator new[](size_t, void*).
367 // The size_t is common to all operator new[]s.
368 if (Fn->getNumParams() != 2)
369 return false;
370
371 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
372 return (ParamType == Ctx.VoidPtrTy);
373}
374
John McCall8ed55a52010-09-02 09:58:18 +0000375static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
376 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000377 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000378 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000379
Anders Carlsson399f4992009-12-13 20:34:34 +0000380 // No cookie is required if the new operator being used is
381 // ::operator new[](size_t, void*).
382 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000383 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000384 return CharUnits::Zero();
385
John McCall8ed55a52010-09-02 09:58:18 +0000386 return CGF.CGM.getCXXABI().GetArrayCookieSize(E->getAllocatedType());
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000387}
388
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000389static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000390 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000391 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000392 llvm::Value *&NumElements,
393 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000394 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000395
396 const llvm::IntegerType *SizeTy =
397 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000398
John McCall8ed55a52010-09-02 09:58:18 +0000399 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
400
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000401 if (!E->isArray()) {
402 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
403 return SizeWithoutCookie;
404 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000405
John McCall8ed55a52010-09-02 09:58:18 +0000406 // Figure out the cookie size.
407 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
408
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000409 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000410 // We multiply the size of all dimensions for NumElements.
411 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000412 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000413 assert(NumElements->getType() == SizeTy && "element count not a size_t");
414
415 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000416 while (const ConstantArrayType *CAT
417 = CGF.getContext().getAsConstantArrayType(ElemType)) {
418 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000419 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000420 }
421
John McCall8ed55a52010-09-02 09:58:18 +0000422 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000423
Chris Lattner32ac5832010-07-20 21:55:52 +0000424 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
425 // Don't bloat the -O0 code.
426 if (llvm::ConstantInt *NumElementsC =
427 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000428 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000429 unsigned SizeWidth = NEC.getBitWidth();
430
431 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000432 NEC = NEC.zext(SizeWidth*2);
John McCall8ed55a52010-09-02 09:58:18 +0000433 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000434 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000435
436 if (!CookieSize.isZero()) {
437 // Save the current size without a cookie. We don't care if an
438 // overflow's already happened because SizeWithoutCookie isn't
439 // used if the allocator returns null or throws, as it should
440 // always do on an overflow.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000441 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000442 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
443
444 // Add the cookie size.
445 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000446 }
447
John McCall8ed55a52010-09-02 09:58:18 +0000448 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000449 SC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000450 Size = llvm::ConstantInt::get(SizeTy, SC);
451 } else {
452 // On overflow, produce a -1 so operator new throws.
453 Size = llvm::Constant::getAllOnesValue(SizeTy);
454 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000455
John McCall8ed55a52010-09-02 09:58:18 +0000456 // Scale NumElements while we're at it.
457 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
458 NumElements = llvm::ConstantInt::get(SizeTy, N);
459
460 // Otherwise, we don't need to do an overflow-checked multiplication if
461 // we're multiplying by one.
462 } else if (TypeSize.isOne()) {
463 assert(ArraySizeMultiplier == 1);
464
465 Size = NumElements;
466
467 // If we need a cookie, add its size in with an overflow check.
468 // This is maybe a little paranoid.
469 if (!CookieSize.isZero()) {
470 SizeWithoutCookie = Size;
471
472 llvm::Value *CookieSizeV
473 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
474
475 const llvm::Type *Types[] = { SizeTy };
476 llvm::Value *UAddF
477 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
478 llvm::Value *AddRes
479 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
480
481 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
482 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
483 Size = CGF.Builder.CreateSelect(DidOverflow,
484 llvm::ConstantInt::get(SizeTy, -1),
485 Size);
486 }
487
488 // Otherwise use the int.umul.with.overflow intrinsic.
489 } else {
490 llvm::Value *OutermostElementSize
491 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
492
493 llvm::Value *NumOutermostElements = NumElements;
494
495 // Scale NumElements by the array size multiplier. This might
496 // overflow, but only if the multiplication below also overflows,
497 // in which case this multiplication isn't used.
498 if (ArraySizeMultiplier != 1)
499 NumElements = CGF.Builder.CreateMul(NumElements,
500 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
501
502 // The requested size of the outermost array is non-constant.
503 // Multiply that by the static size of the elements of that array;
504 // on unsigned overflow, set the size to -1 to trigger an
505 // exception from the allocation routine. This is sufficient to
506 // prevent buffer overruns from the allocator returning a
507 // seemingly valid pointer to insufficient space. This idea comes
508 // originally from MSVC, and GCC has an open bug requesting
509 // similar behavior:
510 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
511 //
512 // This will not be sufficient for C++0x, which requires a
513 // specific exception class (std::bad_array_new_length).
514 // That will require ABI support that has not yet been specified.
515 const llvm::Type *Types[] = { SizeTy };
516 llvm::Value *UMulF
517 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
518 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
519 OutermostElementSize);
520
521 // The overflow bit.
522 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
523
524 // The result of the multiplication.
525 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
526
527 // If we have a cookie, we need to add that size in, too.
528 if (!CookieSize.isZero()) {
529 SizeWithoutCookie = Size;
530
531 llvm::Value *CookieSizeV
532 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
533 llvm::Value *UAddF
534 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
535 llvm::Value *AddRes
536 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
537
538 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
539
540 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
541 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
542 }
543
544 Size = CGF.Builder.CreateSelect(DidOverflow,
545 llvm::ConstantInt::get(SizeTy, -1),
546 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000547 }
John McCall8ed55a52010-09-02 09:58:18 +0000548
549 if (CookieSize.isZero())
550 SizeWithoutCookie = Size;
551 else
552 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
553
Chris Lattner32ac5832010-07-20 21:55:52 +0000554 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000555}
556
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000557static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
558 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000559
560 assert(E->getNumConstructorArgs() == 1 &&
561 "Can only have one argument to initializer of POD type.");
562
563 const Expr *Init = E->getConstructorArg(0);
564 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000565
566 unsigned Alignment =
567 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000568 if (!CGF.hasAggregateLLVMType(AllocType))
569 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000570 AllocType.isVolatileQualified(), Alignment,
571 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000572 else if (AllocType->isAnyComplexType())
573 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
574 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000575 else {
576 AggValueSlot Slot
577 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
578 CGF.EmitAggExpr(Init, Slot);
579 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000580}
581
582void
583CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
584 llvm::Value *NewPtr,
585 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000586 // We have a POD type.
587 if (E->getNumConstructorArgs() == 0)
588 return;
589
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000590 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
591
592 // Create a temporary for the loop index and initialize it with 0.
593 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
594 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
595 Builder.CreateStore(Zero, IndexPtr);
596
597 // Start the loop with a block that tests the condition.
598 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
599 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
600
601 EmitBlock(CondBlock);
602
603 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
604
605 // Generate: if (loop-index < number-of-elements fall to the loop body,
606 // otherwise, go to the block after the for-loop.
607 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
608 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
609 // If the condition is true, execute the body.
610 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
611
612 EmitBlock(ForBody);
613
614 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
615 // Inside the loop body, emit the constructor call on the array element.
616 Counter = Builder.CreateLoad(IndexPtr);
617 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
618 "arrayidx");
619 StoreAnyExprIntoOneUnit(*this, E, Address);
620
621 EmitBlock(ContinueBlock);
622
623 // Emit the increment of the loop counter.
624 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
625 Counter = Builder.CreateLoad(IndexPtr);
626 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
627 Builder.CreateStore(NextVal, IndexPtr);
628
629 // Finally, branch back up to the condition for the next iteration.
630 EmitBranch(CondBlock);
631
632 // Emit the fall-through block.
633 EmitBlock(AfterFor, true);
634}
635
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000636static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
637 llvm::Value *NewPtr, llvm::Value *Size) {
638 llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
639 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
640 if (NewPtr->getType() != BP)
641 NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000642
Ken Dyck705ba072011-01-19 01:58:38 +0000643 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000644 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000645 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000646}
647
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000648static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
649 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000650 llvm::Value *NumElements,
651 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000652 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000653 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000654 bool RequiresZeroInitialization = false;
655 if (Ctor->getParent()->hasTrivialConstructor()) {
656 // If new expression did not specify value-initialization, then there
657 // is no initialization.
658 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
659 return;
660
John McCall614dbdc2010-08-22 21:01:12 +0000661 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000662 // Optimization: since zero initialization will just set the memory
663 // to all zeroes, generate a single memset to do it in one shot.
664 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
665 AllocSizeWithoutCookie);
666 return;
667 }
668
669 RequiresZeroInitialization = true;
670 }
671
672 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
673 E->constructor_arg_begin(),
674 E->constructor_arg_end(),
675 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000676 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000677 } else if (E->getNumConstructorArgs() == 1 &&
678 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
679 // Optimization: since zero initialization will just set the memory
680 // to all zeroes, generate a single memset to do it in one shot.
681 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
682 AllocSizeWithoutCookie);
683 return;
684 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000685 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
686 return;
687 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000688 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000689
690 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000691 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
692 // direct initialization. C++ [dcl.init]p5 requires that we
693 // zero-initialize storage if there are no user-declared constructors.
694 if (E->hasInitializer() &&
695 !Ctor->getParent()->hasUserDeclaredConstructor() &&
696 !Ctor->getParent()->isEmpty())
697 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
698
Douglas Gregore1823702010-07-07 23:37:33 +0000699 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
700 NewPtr, E->constructor_arg_begin(),
701 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000702
703 return;
704 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000705 // We have a POD type.
706 if (E->getNumConstructorArgs() == 0)
707 return;
708
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000709 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000710}
711
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000712namespace {
John McCall7f9c92a2010-09-17 00:50:28 +0000713/// A utility class for saving an rvalue.
714class SavedRValue {
715public:
716 enum Kind { ScalarLiteral, ScalarAddress,
717 AggregateLiteral, AggregateAddress,
718 Complex };
719
720private:
721 llvm::Value *Value;
722 Kind K;
723
724 SavedRValue(llvm::Value *V, Kind K) : Value(V), K(K) {}
725
726public:
727 SavedRValue() {}
728
729 static SavedRValue forScalarLiteral(llvm::Value *V) {
730 return SavedRValue(V, ScalarLiteral);
731 }
732
733 static SavedRValue forScalarAddress(llvm::Value *Addr) {
734 return SavedRValue(Addr, ScalarAddress);
735 }
736
737 static SavedRValue forAggregateLiteral(llvm::Value *V) {
738 return SavedRValue(V, AggregateLiteral);
739 }
740
741 static SavedRValue forAggregateAddress(llvm::Value *Addr) {
742 return SavedRValue(Addr, AggregateAddress);
743 }
744
745 static SavedRValue forComplexAddress(llvm::Value *Addr) {
746 return SavedRValue(Addr, Complex);
747 }
748
749 Kind getKind() const { return K; }
750 llvm::Value *getValue() const { return Value; }
751};
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000752} // end anonymous namespace
John McCall7f9c92a2010-09-17 00:50:28 +0000753
754/// Given an r-value, perform the code necessary to make sure that a
755/// future RestoreRValue will be able to load the value without
756/// domination concerns.
757static SavedRValue SaveRValue(CodeGenFunction &CGF, RValue RV) {
758 if (RV.isScalar()) {
759 llvm::Value *V = RV.getScalarVal();
760
761 // These automatically dominate and don't need to be saved.
762 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
763 return SavedRValue::forScalarLiteral(V);
764
765 // Everything else needs an alloca.
766 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
767 CGF.Builder.CreateStore(V, Addr);
768 return SavedRValue::forScalarAddress(Addr);
769 }
770
771 if (RV.isComplex()) {
772 CodeGenFunction::ComplexPairTy V = RV.getComplexVal();
773 const llvm::Type *ComplexTy =
774 llvm::StructType::get(CGF.getLLVMContext(),
775 V.first->getType(), V.second->getType(),
776 (void*) 0);
777 llvm::Value *Addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
778 CGF.StoreComplexToAddr(V, Addr, /*volatile*/ false);
779 return SavedRValue::forComplexAddress(Addr);
780 }
781
782 assert(RV.isAggregate());
783 llvm::Value *V = RV.getAggregateAddr(); // TODO: volatile?
784 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
785 return SavedRValue::forAggregateLiteral(V);
786
787 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
788 CGF.Builder.CreateStore(V, Addr);
789 return SavedRValue::forAggregateAddress(Addr);
790}
791
792/// Given a saved r-value produced by SaveRValue, perform the code
793/// necessary to restore it to usability at the current insertion
794/// point.
795static RValue RestoreRValue(CodeGenFunction &CGF, SavedRValue RV) {
796 switch (RV.getKind()) {
797 case SavedRValue::ScalarLiteral:
798 return RValue::get(RV.getValue());
799 case SavedRValue::ScalarAddress:
800 return RValue::get(CGF.Builder.CreateLoad(RV.getValue()));
801 case SavedRValue::AggregateLiteral:
802 return RValue::getAggregate(RV.getValue());
803 case SavedRValue::AggregateAddress:
804 return RValue::getAggregate(CGF.Builder.CreateLoad(RV.getValue()));
805 case SavedRValue::Complex:
806 return RValue::getComplex(CGF.LoadComplexFromAddr(RV.getValue(), false));
807 }
808
809 llvm_unreachable("bad saved r-value kind");
810 return RValue();
811}
812
John McCall824c2f52010-09-14 07:57:04 +0000813namespace {
814 /// A cleanup to call the given 'operator delete' function upon
815 /// abnormal exit from a new expression.
816 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
817 size_t NumPlacementArgs;
818 const FunctionDecl *OperatorDelete;
819 llvm::Value *Ptr;
820 llvm::Value *AllocSize;
821
822 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
823
824 public:
825 static size_t getExtraSize(size_t NumPlacementArgs) {
826 return NumPlacementArgs * sizeof(RValue);
827 }
828
829 CallDeleteDuringNew(size_t NumPlacementArgs,
830 const FunctionDecl *OperatorDelete,
831 llvm::Value *Ptr,
832 llvm::Value *AllocSize)
833 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
834 Ptr(Ptr), AllocSize(AllocSize) {}
835
836 void setPlacementArg(unsigned I, RValue Arg) {
837 assert(I < NumPlacementArgs && "index out of range");
838 getPlacementArgs()[I] = Arg;
839 }
840
841 void Emit(CodeGenFunction &CGF, bool IsForEH) {
842 const FunctionProtoType *FPT
843 = OperatorDelete->getType()->getAs<FunctionProtoType>();
844 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000845 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000846
847 CallArgList DeleteArgs;
848
849 // The first argument is always a void*.
850 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
851 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
852
853 // A member 'operator delete' can take an extra 'size_t' argument.
854 if (FPT->getNumArgs() == NumPlacementArgs + 2)
855 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
856
857 // Pass the rest of the arguments, which must match exactly.
858 for (unsigned I = 0; I != NumPlacementArgs; ++I)
859 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
860
861 // Call 'operator delete'.
862 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
863 CGF.CGM.GetAddrOfFunction(OperatorDelete),
864 ReturnValueSlot(), DeleteArgs, OperatorDelete);
865 }
866 };
John McCall7f9c92a2010-09-17 00:50:28 +0000867
868 /// A cleanup to call the given 'operator delete' function upon
869 /// abnormal exit from a new expression when the new expression is
870 /// conditional.
871 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
872 size_t NumPlacementArgs;
873 const FunctionDecl *OperatorDelete;
874 SavedRValue Ptr;
875 SavedRValue AllocSize;
876
877 SavedRValue *getPlacementArgs() {
878 return reinterpret_cast<SavedRValue*>(this+1);
879 }
880
881 public:
882 static size_t getExtraSize(size_t NumPlacementArgs) {
883 return NumPlacementArgs * sizeof(SavedRValue);
884 }
885
886 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
887 const FunctionDecl *OperatorDelete,
888 SavedRValue Ptr,
889 SavedRValue AllocSize)
890 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
891 Ptr(Ptr), AllocSize(AllocSize) {}
892
893 void setPlacementArg(unsigned I, SavedRValue Arg) {
894 assert(I < NumPlacementArgs && "index out of range");
895 getPlacementArgs()[I] = Arg;
896 }
897
898 void Emit(CodeGenFunction &CGF, bool IsForEH) {
899 const FunctionProtoType *FPT
900 = OperatorDelete->getType()->getAs<FunctionProtoType>();
901 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
902 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
903
904 CallArgList DeleteArgs;
905
906 // The first argument is always a void*.
907 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
908 DeleteArgs.push_back(std::make_pair(RestoreRValue(CGF, Ptr), *AI++));
909
910 // A member 'operator delete' can take an extra 'size_t' argument.
911 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
912 RValue RV = RestoreRValue(CGF, AllocSize);
913 DeleteArgs.push_back(std::make_pair(RV, *AI++));
914 }
915
916 // Pass the rest of the arguments, which must match exactly.
917 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
918 RValue RV = RestoreRValue(CGF, getPlacementArgs()[I]);
919 DeleteArgs.push_back(std::make_pair(RV, *AI++));
920 }
921
922 // Call 'operator delete'.
923 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
924 CGF.CGM.GetAddrOfFunction(OperatorDelete),
925 ReturnValueSlot(), DeleteArgs, OperatorDelete);
926 }
927 };
928}
929
930/// Enter a cleanup to call 'operator delete' if the initializer in a
931/// new-expression throws.
932static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
933 const CXXNewExpr *E,
934 llvm::Value *NewPtr,
935 llvm::Value *AllocSize,
936 const CallArgList &NewArgs) {
937 // If we're not inside a conditional branch, then the cleanup will
938 // dominate and we can do the easier (and more efficient) thing.
939 if (!CGF.isInConditionalBranch()) {
940 CallDeleteDuringNew *Cleanup = CGF.EHStack
941 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
942 E->getNumPlacementArgs(),
943 E->getOperatorDelete(),
944 NewPtr, AllocSize);
945 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
946 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
947
948 return;
949 }
950
951 // Otherwise, we need to save all this stuff.
952 SavedRValue SavedNewPtr = SaveRValue(CGF, RValue::get(NewPtr));
953 SavedRValue SavedAllocSize = SaveRValue(CGF, RValue::get(AllocSize));
954
955 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
956 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
957 E->getNumPlacementArgs(),
958 E->getOperatorDelete(),
959 SavedNewPtr,
960 SavedAllocSize);
961 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
962 Cleanup->setPlacementArg(I, SaveRValue(CGF, NewArgs[I+1].first));
963
964 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000965}
966
Anders Carlssoncc52f652009-09-22 22:53:17 +0000967llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoncc52f652009-09-22 22:53:17 +0000968 QualType AllocType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000969 if (AllocType->isArrayType())
970 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
971 AllocType = AType->getElementType();
972
Anders Carlssoncc52f652009-09-22 22:53:17 +0000973 FunctionDecl *NewFD = E->getOperatorNew();
974 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
975
976 CallArgList NewArgs;
977
978 // The allocation size is the first argument.
979 QualType SizeTy = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000980
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000981 llvm::Value *NumElements = 0;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000982 llvm::Value *AllocSizeWithoutCookie = 0;
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000983 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000984 *this, E, NumElements,
985 AllocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000986
Anders Carlssoncc52f652009-09-22 22:53:17 +0000987 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
988
989 // Emit the rest of the arguments.
990 // FIXME: Ideally, this should just use EmitCallArgs.
991 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
992
993 // First, use the types from the function type.
994 // We start at 1 here because the first argument (the allocation size)
995 // has already been emitted.
996 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
997 QualType ArgType = NewFTy->getArgType(i);
998
999 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1000 getTypePtr() ==
1001 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
1002 "type mismatch in call argument!");
1003
1004 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
1005 ArgType));
1006
1007 }
1008
1009 // Either we've emitted all the call args, or we have a call to a
1010 // variadic function.
1011 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
1012 "Extra arguments in non-variadic function!");
1013
1014 // If we still have any arguments, emit them using the type of the argument.
1015 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
1016 NewArg != NewArgEnd; ++NewArg) {
1017 QualType ArgType = NewArg->getType();
1018 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
1019 ArgType));
1020 }
1021
1022 // Emit the call to new.
1023 RValue RV =
John McCallab26cfa2010-02-05 21:31:56 +00001024 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001025 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001026
1027 // If an allocation function is declared with an empty exception specification
1028 // it returns null to indicate failure to allocate storage. [expr.new]p13.
1029 // (We don't need to check for null when there's no new initializer and
1030 // we're allocating a POD type).
1031 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
1032 !(AllocType->isPODType() && !E->hasInitializer());
1033
John McCall8ed55a52010-09-02 09:58:18 +00001034 llvm::BasicBlock *NullCheckSource = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001035 llvm::BasicBlock *NewNotNull = 0;
1036 llvm::BasicBlock *NewEnd = 0;
1037
1038 llvm::Value *NewPtr = RV.getScalarVal();
John McCall8ed55a52010-09-02 09:58:18 +00001039 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001040
1041 if (NullCheckResult) {
John McCall8ed55a52010-09-02 09:58:18 +00001042 NullCheckSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001043 NewNotNull = createBasicBlock("new.notnull");
1044 NewEnd = createBasicBlock("new.end");
1045
John McCall8ed55a52010-09-02 09:58:18 +00001046 llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
1047 Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001048 EmitBlock(NewNotNull);
1049 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001050
John McCall8ed55a52010-09-02 09:58:18 +00001051 assert((AllocSize == AllocSizeWithoutCookie) ==
1052 CalculateCookiePadding(*this, E).isZero());
1053 if (AllocSize != AllocSizeWithoutCookie) {
1054 assert(E->isArray());
1055 NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
1056 AllocType);
1057 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001058
John McCall824c2f52010-09-14 07:57:04 +00001059 // If there's an operator delete, enter a cleanup to call it if an
1060 // exception is thrown.
1061 EHScopeStack::stable_iterator CallOperatorDelete;
1062 if (E->getOperatorDelete()) {
John McCall7f9c92a2010-09-17 00:50:28 +00001063 EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
John McCall824c2f52010-09-14 07:57:04 +00001064 CallOperatorDelete = EHStack.stable_begin();
1065 }
1066
Douglas Gregor040ad502010-09-02 23:24:14 +00001067 const llvm::Type *ElementPtrTy
1068 = ConvertTypeForMem(AllocType)->getPointerTo(AS);
John McCall8ed55a52010-09-02 09:58:18 +00001069 NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001070
John McCall8ed55a52010-09-02 09:58:18 +00001071 if (E->isArray()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001072 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001073
1074 // NewPtr is a pointer to the base element type. If we're
1075 // allocating an array of arrays, we'll need to cast back to the
1076 // array pointer type.
Douglas Gregor040ad502010-09-02 23:24:14 +00001077 const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
John McCall8ed55a52010-09-02 09:58:18 +00001078 if (NewPtr->getType() != ResultTy)
1079 NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
1080 } else {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001081 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001082 }
John McCall824c2f52010-09-14 07:57:04 +00001083
1084 // Deactivate the 'operator delete' cleanup if we finished
1085 // initialization.
1086 if (CallOperatorDelete.isValid())
1087 DeactivateCleanupBlock(CallOperatorDelete);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001088
Anders Carlssoncc52f652009-09-22 22:53:17 +00001089 if (NullCheckResult) {
1090 Builder.CreateBr(NewEnd);
John McCall8ed55a52010-09-02 09:58:18 +00001091 llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001092 EmitBlock(NewEnd);
1093
1094 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1095 PHI->reserveOperandSpace(2);
John McCall8ed55a52010-09-02 09:58:18 +00001096 PHI->addIncoming(NewPtr, NotNullSource);
1097 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1098 NullCheckSource);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001099
1100 NewPtr = PHI;
1101 }
John McCall8ed55a52010-09-02 09:58:18 +00001102
Anders Carlssoncc52f652009-09-22 22:53:17 +00001103 return NewPtr;
1104}
1105
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001106void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1107 llvm::Value *Ptr,
1108 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001109 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1110
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001111 const FunctionProtoType *DeleteFTy =
1112 DeleteFD->getType()->getAs<FunctionProtoType>();
1113
1114 CallArgList DeleteArgs;
1115
Anders Carlsson21122cf2009-12-13 20:04:38 +00001116 // Check if we need to pass the size to the delete operator.
1117 llvm::Value *Size = 0;
1118 QualType SizeTy;
1119 if (DeleteFTy->getNumArgs() == 2) {
1120 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001121 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1122 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1123 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001124 }
1125
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001126 QualType ArgTy = DeleteFTy->getArgType(0);
1127 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1128 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1129
Anders Carlsson21122cf2009-12-13 20:04:38 +00001130 if (Size)
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001131 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001132
1133 // Emit the call to delete.
John McCallab26cfa2010-02-05 21:31:56 +00001134 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001135 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001136 DeleteArgs, DeleteFD);
1137}
1138
John McCall8ed55a52010-09-02 09:58:18 +00001139namespace {
1140 /// Calls the given 'operator delete' on a single object.
1141 struct CallObjectDelete : EHScopeStack::Cleanup {
1142 llvm::Value *Ptr;
1143 const FunctionDecl *OperatorDelete;
1144 QualType ElementType;
1145
1146 CallObjectDelete(llvm::Value *Ptr,
1147 const FunctionDecl *OperatorDelete,
1148 QualType ElementType)
1149 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1150
1151 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1152 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1153 }
1154 };
1155}
1156
1157/// Emit the code for deleting a single object.
1158static void EmitObjectDelete(CodeGenFunction &CGF,
1159 const FunctionDecl *OperatorDelete,
1160 llvm::Value *Ptr,
1161 QualType ElementType) {
1162 // Find the destructor for the type, if applicable. If the
1163 // destructor is virtual, we'll just emit the vcall and return.
1164 const CXXDestructorDecl *Dtor = 0;
1165 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1166 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1167 if (!RD->hasTrivialDestructor()) {
1168 Dtor = RD->getDestructor();
1169
1170 if (Dtor->isVirtual()) {
1171 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001172 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1173 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001174 /*isVariadic=*/false);
1175
1176 llvm::Value *Callee
1177 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1178 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1179 0, 0);
1180
1181 // The dtor took care of deleting the object.
1182 return;
1183 }
1184 }
1185 }
1186
1187 // Make sure that we call delete even if the dtor throws.
1188 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1189 Ptr, OperatorDelete, ElementType);
1190
1191 if (Dtor)
1192 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1193 /*ForVirtualBase=*/false, Ptr);
1194
1195 CGF.PopCleanupBlock();
1196}
1197
1198namespace {
1199 /// Calls the given 'operator delete' on an array of objects.
1200 struct CallArrayDelete : EHScopeStack::Cleanup {
1201 llvm::Value *Ptr;
1202 const FunctionDecl *OperatorDelete;
1203 llvm::Value *NumElements;
1204 QualType ElementType;
1205 CharUnits CookieSize;
1206
1207 CallArrayDelete(llvm::Value *Ptr,
1208 const FunctionDecl *OperatorDelete,
1209 llvm::Value *NumElements,
1210 QualType ElementType,
1211 CharUnits CookieSize)
1212 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1213 ElementType(ElementType), CookieSize(CookieSize) {}
1214
1215 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1216 const FunctionProtoType *DeleteFTy =
1217 OperatorDelete->getType()->getAs<FunctionProtoType>();
1218 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1219
1220 CallArgList Args;
1221
1222 // Pass the pointer as the first argument.
1223 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1224 llvm::Value *DeletePtr
1225 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1226 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1227
1228 // Pass the original requested size as the second argument.
1229 if (DeleteFTy->getNumArgs() == 2) {
1230 QualType size_t = DeleteFTy->getArgType(1);
1231 const llvm::IntegerType *SizeTy
1232 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1233
1234 CharUnits ElementTypeSize =
1235 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1236
1237 // The size of an element, multiplied by the number of elements.
1238 llvm::Value *Size
1239 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1240 Size = CGF.Builder.CreateMul(Size, NumElements);
1241
1242 // Plus the size of the cookie if applicable.
1243 if (!CookieSize.isZero()) {
1244 llvm::Value *CookieSizeV
1245 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1246 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1247 }
1248
1249 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1250 }
1251
1252 // Emit the call to delete.
1253 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1254 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1255 ReturnValueSlot(), Args, OperatorDelete);
1256 }
1257 };
1258}
1259
1260/// Emit the code for deleting an array of objects.
1261static void EmitArrayDelete(CodeGenFunction &CGF,
1262 const FunctionDecl *OperatorDelete,
1263 llvm::Value *Ptr,
1264 QualType ElementType) {
1265 llvm::Value *NumElements = 0;
1266 llvm::Value *AllocatedPtr = 0;
1267 CharUnits CookieSize;
1268 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, ElementType,
1269 NumElements, AllocatedPtr, CookieSize);
1270
1271 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1272
1273 // Make sure that we call delete even if one of the dtors throws.
1274 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1275 AllocatedPtr, OperatorDelete,
1276 NumElements, ElementType,
1277 CookieSize);
1278
1279 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1280 if (!RD->hasTrivialDestructor()) {
1281 assert(NumElements && "ReadArrayCookie didn't find element count"
1282 " for a class with destructor");
1283 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1284 }
1285 }
1286
1287 CGF.PopCleanupBlock();
1288}
1289
Anders Carlssoncc52f652009-09-22 22:53:17 +00001290void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001291
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001292 // Get at the argument before we performed the implicit conversion
1293 // to void*.
1294 const Expr *Arg = E->getArgument();
1295 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001296 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001297 ICE->getType()->isVoidPointerType())
1298 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001299 else
1300 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001301 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001302
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001303 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001304
1305 // Null check the pointer.
1306 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1307 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1308
1309 llvm::Value *IsNull =
1310 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1311 "isnull");
1312
1313 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1314 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001315
John McCall8ed55a52010-09-02 09:58:18 +00001316 // We might be deleting a pointer to array. If so, GEP down to the
1317 // first non-array element.
1318 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1319 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1320 if (DeleteTy->isConstantArrayType()) {
1321 llvm::Value *Zero = Builder.getInt32(0);
1322 llvm::SmallVector<llvm::Value*,8> GEP;
1323
1324 GEP.push_back(Zero); // point at the outermost array
1325
1326 // For each layer of array type we're pointing at:
1327 while (const ConstantArrayType *Arr
1328 = getContext().getAsConstantArrayType(DeleteTy)) {
1329 // 1. Unpeel the array type.
1330 DeleteTy = Arr->getElementType();
1331
1332 // 2. GEP to the first element of the array.
1333 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001334 }
John McCall8ed55a52010-09-02 09:58:18 +00001335
1336 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001337 }
1338
Douglas Gregor04f36212010-09-02 17:38:50 +00001339 assert(ConvertTypeForMem(DeleteTy) ==
1340 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001341
1342 if (E->isArrayForm()) {
1343 EmitArrayDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1344 } else {
1345 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1346 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001347
Anders Carlssoncc52f652009-09-22 22:53:17 +00001348 EmitBlock(DeleteEnd);
1349}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001350
1351llvm::Value * CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1352 QualType Ty = E->getType();
1353 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001354
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001355 if (E->isTypeOperand()) {
1356 llvm::Constant *TypeInfo =
1357 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1358 return Builder.CreateBitCast(TypeInfo, LTy);
1359 }
1360
Mike Stumpc9b231c2009-11-15 08:09:41 +00001361 Expr *subE = E->getExprOperand();
Mike Stump6fdfea62009-11-17 22:33:00 +00001362 Ty = subE->getType();
1363 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1364 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc9b231c2009-11-15 08:09:41 +00001365 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1366 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1367 if (RD->isPolymorphic()) {
1368 // FIXME: if subE is an lvalue do
1369 LValue Obj = EmitLValue(subE);
1370 llvm::Value *This = Obj.getAddress();
Mike Stump1bf924b2009-11-15 16:52:53 +00001371 // We need to do a zero check for *p, unless it has NonNullAttr.
1372 // FIXME: PointerType->hasAttr<NonNullAttr>()
1373 bool CanBeZero = false;
Mike Stumpc2c03342009-11-17 00:45:21 +00001374 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001375 if (UO->getOpcode() == UO_Deref)
Mike Stump1bf924b2009-11-15 16:52:53 +00001376 CanBeZero = true;
1377 if (CanBeZero) {
1378 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1379 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1380
Dan Gohman8fc50c22010-10-26 18:44:08 +00001381 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1382 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stump1bf924b2009-11-15 16:52:53 +00001383 NonZeroBlock, ZeroBlock);
1384 EmitBlock(ZeroBlock);
1385 /// Call __cxa_bad_typeid
1386 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1387 const llvm::FunctionType *FTy;
1388 FTy = llvm::FunctionType::get(ResultType, false);
1389 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stump65511702009-11-16 06:50:58 +00001390 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stump1bf924b2009-11-15 16:52:53 +00001391 Builder.CreateUnreachable();
1392 EmitBlock(NonZeroBlock);
1393 }
Dan Gohman8fc50c22010-10-26 18:44:08 +00001394 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc9b231c2009-11-15 08:09:41 +00001395 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1396 V = Builder.CreateLoad(V);
1397 return V;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001398 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001399 }
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001400 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001401}
Mike Stump65511702009-11-16 06:50:58 +00001402
1403llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1404 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001405 QualType SrcTy = DCE->getSubExpr()->getType();
1406 QualType DestTy = DCE->getTypeAsWritten();
1407 QualType InnerType = DestTy->getPointeeType();
1408
Mike Stump65511702009-11-16 06:50:58 +00001409 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001410
Mike Stump65511702009-11-16 06:50:58 +00001411 bool CanBeZero = false;
Mike Stump65511702009-11-16 06:50:58 +00001412 bool ToVoid = false;
Mike Stump6ca0e212009-11-16 22:52:20 +00001413 bool ThrowOnBad = false;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001414 if (DestTy->isPointerType()) {
Mike Stump65511702009-11-16 06:50:58 +00001415 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1416 CanBeZero = true;
1417 if (InnerType->isVoidType())
1418 ToVoid = true;
1419 } else {
1420 LTy = LTy->getPointerTo();
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001421
1422 // FIXME: What if exceptions are disabled?
Mike Stump65511702009-11-16 06:50:58 +00001423 ThrowOnBad = true;
1424 }
1425
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001426 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1427 SrcTy = SrcTy->getPointeeType();
1428 SrcTy = SrcTy.getUnqualifiedType();
1429
Anders Carlsson0087bc82009-12-18 14:55:04 +00001430 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001431 DestTy = DestTy->getPointeeType();
1432 DestTy = DestTy.getUnqualifiedType();
Mike Stump65511702009-11-16 06:50:58 +00001433
Mike Stump65511702009-11-16 06:50:58 +00001434 llvm::BasicBlock *ContBlock = createBasicBlock();
1435 llvm::BasicBlock *NullBlock = 0;
1436 llvm::BasicBlock *NonZeroBlock = 0;
1437 if (CanBeZero) {
1438 NonZeroBlock = createBasicBlock();
1439 NullBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001440 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001441 EmitBlock(NonZeroBlock);
1442 }
1443
Mike Stump65511702009-11-16 06:50:58 +00001444 llvm::BasicBlock *BadCastBlock = 0;
Mike Stump65511702009-11-16 06:50:58 +00001445
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001446 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001447
1448 // See if this is a dynamic_cast(void*)
1449 if (ToVoid) {
1450 llvm::Value *This = V;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001451 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump6ca0e212009-11-16 22:52:20 +00001452 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1453 V = Builder.CreateLoad(V, "offset to top");
1454 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1455 V = Builder.CreateInBoundsGEP(This, V);
1456 V = Builder.CreateBitCast(V, LTy);
1457 } else {
1458 /// Call __dynamic_cast
1459 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1460 const llvm::FunctionType *FTy;
1461 std::vector<const llvm::Type*> ArgTys;
1462 const llvm::Type *PtrToInt8Ty
1463 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1464 ArgTys.push_back(PtrToInt8Ty);
1465 ArgTys.push_back(PtrToInt8Ty);
1466 ArgTys.push_back(PtrToInt8Ty);
1467 ArgTys.push_back(PtrDiffTy);
1468 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001469
1470 // FIXME: Calculate better hint.
1471 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001472
1473 assert(SrcTy->isRecordType() && "Src type must be record type!");
1474 assert(DestTy->isRecordType() && "Dest type must be record type!");
1475
Douglas Gregor247894b2009-12-23 22:04:40 +00001476 llvm::Value *SrcArg
1477 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1478 llvm::Value *DestArg
1479 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001480
Mike Stump6ca0e212009-11-16 22:52:20 +00001481 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1482 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001483 V, SrcArg, DestArg, hint);
Mike Stump6ca0e212009-11-16 22:52:20 +00001484 V = Builder.CreateBitCast(V, LTy);
1485
1486 if (ThrowOnBad) {
1487 BadCastBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001488 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump6ca0e212009-11-16 22:52:20 +00001489 EmitBlock(BadCastBlock);
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001490 /// Invoke __cxa_bad_cast
Mike Stump6ca0e212009-11-16 22:52:20 +00001491 ResultType = llvm::Type::getVoidTy(VMContext);
1492 const llvm::FunctionType *FBadTy;
Mike Stump3afea1d2009-11-17 03:01:03 +00001493 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001494 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001495 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1496 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1497 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1498 EmitBlock(Cont);
1499 } else {
1500 // FIXME: Does this ever make sense?
1501 Builder.CreateCall(F)->setDoesNotReturn();
1502 }
Mike Stumpe8cdcc92009-11-17 00:08:50 +00001503 Builder.CreateUnreachable();
Mike Stump6ca0e212009-11-16 22:52:20 +00001504 }
Mike Stump65511702009-11-16 06:50:58 +00001505 }
1506
1507 if (CanBeZero) {
1508 Builder.CreateBr(ContBlock);
1509 EmitBlock(NullBlock);
1510 Builder.CreateBr(ContBlock);
1511 }
1512 EmitBlock(ContBlock);
1513 if (CanBeZero) {
1514 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump4d0e9092009-11-17 00:10:05 +00001515 PHI->reserveOperandSpace(2);
Mike Stump65511702009-11-16 06:50:58 +00001516 PHI->addIncoming(V, NonZeroBlock);
1517 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001518 V = PHI;
1519 }
1520
1521 return V;
1522}