blob: 777036bc3b3741e286bce2be558e34cfd1f15679 [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 Carlsson3b5ad222010-01-01 20:29:01 +000080/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
81/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000082static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
83 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000084 const CXXMethodDecl *MD) {
85
Anders Carlsson1679f5a2011-01-29 03:52:01 +000086 // When building with -fapple-kext, all calls must go through the vtable since
87 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000088 if (Context.getLangOptions().AppleKext)
89 return false;
90
Anders Carlsson1679f5a2011-01-29 03:52:01 +000091 // If the most derived class is marked final, we know that no subclass can
92 // override this member function and so we can devirtualize it. For example:
93 //
94 // struct A { virtual void f(); }
95 // struct B final : A { };
96 //
97 // void f(B *b) {
98 // b->f();
99 // }
100 //
101 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
102 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
103 return true;
104
Anders Carlssonf89e0422011-01-23 21:07:30 +0000105 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000106 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000107 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000108 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000109
Anders Carlssonf89e0422011-01-23 21:07:30 +0000110 // Similarly, if the class itself is marked 'final' it can't be overridden
111 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000112 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000113 return true;
114
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000115 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
116 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
117 // This is a record decl. We know the type and can devirtualize it.
118 return VD->getType()->isRecordType();
119 }
120
121 return false;
122 }
123
124 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000125 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000126 return true;
127
128 // And calls on bound temporaries.
129 if (isa<CXXBindTemporaryExpr>(Base))
130 return true;
131
132 // Check if this is a call expr that returns a record type.
133 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
134 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000135
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000136 // We can't devirtualize the call.
137 return false;
138}
139
Francois Pichetdbee3412011-01-18 05:04:39 +0000140// Note: This function also emit constructor calls to support a MSVC
141// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
143 ReturnValueSlot ReturnValue) {
144 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
145 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
146
147 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
148 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
149
Devang Patelc69e1cf2010-09-30 19:05:55 +0000150 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000151 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
152 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000153 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
154 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
155 DI->getOrCreateRecordType(PTy->getPointeeType(),
156 MD->getParent()->getLocation());
157 }
158 }
159
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000160 if (MD->isStatic()) {
161 // The method is static, emit it as we would a regular call.
162 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
163 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
164 ReturnValue, CE->arg_begin(), CE->arg_end());
165 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000166
John McCallfc400282010-09-03 01:26:39 +0000167 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000169 if (ME->isArrow())
170 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000171 else
172 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173
John McCallfc400282010-09-03 01:26:39 +0000174 if (MD->isTrivial()) {
175 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000176 if (isa<CXXConstructorDecl>(MD) &&
177 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
178 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000179
Francois Pichetdbee3412011-01-18 05:04:39 +0000180 if (MD->isCopyAssignmentOperator()) {
181 // We don't like to generate the trivial copy assignment operator when
182 // it isn't necessary; just produce the proper effect here.
183 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
184 EmitAggregateCopy(This, RHS, CE->getType());
185 return RValue::get(This);
186 }
187
188 if (isa<CXXConstructorDecl>(MD) &&
189 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
190 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
191 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
192 CE->arg_begin(), CE->arg_end());
193 return RValue::get(This);
194 }
195 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000196 }
197
John McCallfc400282010-09-03 01:26:39 +0000198 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000199 const CGFunctionInfo *FInfo = 0;
200 if (isa<CXXDestructorDecl>(MD))
201 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
202 Dtor_Complete);
203 else if (isa<CXXConstructorDecl>(MD))
204 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
205 Ctor_Complete);
206 else
207 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000208
209 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
210 const llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000211 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000212
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000213 // C++ [class.virtual]p12:
214 // Explicit qualification with the scope operator (5.1) suppresses the
215 // virtual call mechanism.
216 //
217 // We also don't emit a virtual call if the base expression has a record type
218 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000219 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000220 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
221 && !canDevirtualizeMemberFunctionCalls(getContext(),
222 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000223 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000224 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
225 if (UseVirtualCall) {
226 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000227 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000228 if (getContext().getLangOptions().AppleKext &&
229 MD->isVirtual() &&
230 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000231 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000232 else
233 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000234 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000235 } else if (const CXXConstructorDecl *Ctor =
236 dyn_cast<CXXConstructorDecl>(MD)) {
237 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000238 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000239 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000240 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000241 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000242 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000243 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000244 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000245 else
246 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000247 }
248
Anders Carlssonc997d422010-01-02 01:01:18 +0000249 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000250 CE->arg_begin(), CE->arg_end());
251}
252
253RValue
254CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
255 ReturnValueSlot ReturnValue) {
256 const BinaryOperator *BO =
257 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
258 const Expr *BaseExpr = BO->getLHS();
259 const Expr *MemFnExpr = BO->getRHS();
260
261 const MemberPointerType *MPT =
262 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000263
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 const FunctionProtoType *FPT =
265 MPT->getPointeeType()->getAs<FunctionProtoType>();
266 const CXXRecordDecl *RD =
267 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
268
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000269 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000270 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000271
272 // Emit the 'this' pointer.
273 llvm::Value *This;
274
John McCall2de56d12010-08-25 11:45:40 +0000275 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276 This = EmitScalarExpr(BaseExpr);
277 else
278 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000279
John McCall93d557b2010-08-22 00:05:51 +0000280 // Ask the ABI to load the callee. Note that This is modified.
281 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000282 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000283
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 CallArgList Args;
285
286 QualType ThisType =
287 getContext().getPointerType(getContext().getTagDeclType(RD));
288
289 // Push the this ptr.
290 Args.push_back(std::make_pair(RValue::get(This), ThisType));
291
292 // And the rest of the call args
293 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall04a67a62010-02-05 21:31:56 +0000294 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000295 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
296 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000297}
298
299RValue
300CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
301 const CXXMethodDecl *MD,
302 ReturnValueSlot ReturnValue) {
303 assert(MD->isInstance() &&
304 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000305 LValue LV = EmitLValue(E->getArg(0));
306 llvm::Value *This = LV.getAddress();
307
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000308 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
310 if (ClassDecl->hasTrivialCopyAssignment()) {
311 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
312 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
314 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000315 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000316 return RValue::get(This);
317 }
318 }
319
320 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
321 const llvm::Type *Ty =
322 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
323 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000324 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000325 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000326 !canDevirtualizeMemberFunctionCalls(getContext(),
327 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000328 Callee = BuildVirtualCall(MD, This, Ty);
329 else
330 Callee = CGM.GetAddrOfFunction(MD, Ty);
331
Anders Carlssonc997d422010-01-02 01:01:18 +0000332 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000333 E->arg_begin() + 1, E->arg_end());
334}
335
336void
John McCall558d2ab2010-09-15 10:14:12 +0000337CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
338 AggValueSlot Dest) {
339 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000340 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000341
342 // If we require zero initialization before (or instead of) calling the
343 // constructor, as can be the case with a non-user-provided default
344 // constructor, emit the zero initialization now.
345 if (E->requiresZeroInitialization())
John McCall558d2ab2010-09-15 10:14:12 +0000346 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000347
348 // If this is a call to a trivial default constructor, do nothing.
349 if (CD->isTrivial() && CD->isDefaultConstructor())
350 return;
351
John McCallfc1e6c72010-09-18 00:58:34 +0000352 // Elide the constructor if we're constructing from a temporary.
353 // The temporary check is required because Sema sets this on NRVO
354 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000355 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000356 assert(getContext().hasSameUnqualifiedType(E->getType(),
357 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000358 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
359 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000360 return;
361 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000362 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000363
364 const ConstantArrayType *Array
365 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000366 if (Array) {
367 QualType BaseElementTy = getContext().getBaseElementType(Array);
368 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
369 BasePtr = llvm::PointerType::getUnqual(BasePtr);
370 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000371 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000372
373 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
374 E->arg_begin(), E->arg_end());
375 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000376 else {
377 CXXCtorType Type =
378 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
379 ? Ctor_Complete : Ctor_Base;
380 bool ForVirtualBase =
381 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
382
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000383 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000384 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000385 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000386 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000387}
388
Fariborz Jahanian34999872010-11-13 21:53:34 +0000389void
390CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
391 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000392 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000393 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000394 Exp = E->getSubExpr();
395 assert(isa<CXXConstructExpr>(Exp) &&
396 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
397 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
398 const CXXConstructorDecl *CD = E->getConstructor();
399 RunCleanupsScope Scope(*this);
400
401 // If we require zero initialization before (or instead of) calling the
402 // constructor, as can be the case with a non-user-provided default
403 // constructor, emit the zero initialization now.
404 // FIXME. Do I still need this for a copy ctor synthesis?
405 if (E->requiresZeroInitialization())
406 EmitNullInitialization(Dest, E->getType());
407
Chandler Carruth858a5462010-11-15 13:54:43 +0000408 assert(!getContext().getAsConstantArrayType(E->getType())
409 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000410 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
411 E->arg_begin(), E->arg_end());
412}
413
John McCall5172ed92010-08-23 01:17:59 +0000414/// Check whether the given operator new[] is the global placement
415/// operator new[].
416static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
417 const FunctionDecl *Fn) {
418 // Must be in global scope. Note that allocation functions can't be
419 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000420 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000421 return false;
422
423 // Signature must be void *operator new[](size_t, void*).
424 // The size_t is common to all operator new[]s.
425 if (Fn->getNumParams() != 2)
426 return false;
427
428 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
429 return (ParamType == Ctx.VoidPtrTy);
430}
431
John McCall1e7fe752010-09-02 09:58:18 +0000432static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
433 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000434 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000435 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000436
Anders Carlssondd937552009-12-13 20:34:34 +0000437 // No cookie is required if the new operator being used is
438 // ::operator new[](size_t, void*).
439 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000440 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000441 return CharUnits::Zero();
442
John McCall6ec278d2011-01-27 09:37:56 +0000443 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000444}
445
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000446static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000447 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000448 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000449 llvm::Value *&NumElements,
450 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000451 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000452
453 const llvm::IntegerType *SizeTy =
454 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000455
John McCall1e7fe752010-09-02 09:58:18 +0000456 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
457
Douglas Gregor59174c02010-07-21 01:10:17 +0000458 if (!E->isArray()) {
459 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
460 return SizeWithoutCookie;
461 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000462
John McCall1e7fe752010-09-02 09:58:18 +0000463 // Figure out the cookie size.
464 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
465
Anders Carlssona4d4c012009-09-23 16:07:23 +0000466 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000467 // We multiply the size of all dimensions for NumElements.
468 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000469 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000470 assert(NumElements->getType() == SizeTy && "element count not a size_t");
471
472 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000473 while (const ConstantArrayType *CAT
474 = CGF.getContext().getAsConstantArrayType(ElemType)) {
475 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000476 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000477 }
478
John McCall1e7fe752010-09-02 09:58:18 +0000479 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000480
Chris Lattner806941e2010-07-20 21:55:52 +0000481 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
482 // Don't bloat the -O0 code.
483 if (llvm::ConstantInt *NumElementsC =
484 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000485 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000486 unsigned SizeWidth = NEC.getBitWidth();
487
488 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000489 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000490 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000491 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000492
493 if (!CookieSize.isZero()) {
494 // Save the current size without a cookie. We don't care if an
495 // overflow's already happened because SizeWithoutCookie isn't
496 // used if the allocator returns null or throws, as it should
497 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000498 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000499 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
500
501 // Add the cookie size.
502 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000503 }
504
John McCall1e7fe752010-09-02 09:58:18 +0000505 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000506 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000507 Size = llvm::ConstantInt::get(SizeTy, SC);
508 } else {
509 // On overflow, produce a -1 so operator new throws.
510 Size = llvm::Constant::getAllOnesValue(SizeTy);
511 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000512
John McCall1e7fe752010-09-02 09:58:18 +0000513 // Scale NumElements while we're at it.
514 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
515 NumElements = llvm::ConstantInt::get(SizeTy, N);
516
517 // Otherwise, we don't need to do an overflow-checked multiplication if
518 // we're multiplying by one.
519 } else if (TypeSize.isOne()) {
520 assert(ArraySizeMultiplier == 1);
521
522 Size = NumElements;
523
524 // If we need a cookie, add its size in with an overflow check.
525 // This is maybe a little paranoid.
526 if (!CookieSize.isZero()) {
527 SizeWithoutCookie = Size;
528
529 llvm::Value *CookieSizeV
530 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
531
532 const llvm::Type *Types[] = { SizeTy };
533 llvm::Value *UAddF
534 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
535 llvm::Value *AddRes
536 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
537
538 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
539 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
540 Size = CGF.Builder.CreateSelect(DidOverflow,
541 llvm::ConstantInt::get(SizeTy, -1),
542 Size);
543 }
544
545 // Otherwise use the int.umul.with.overflow intrinsic.
546 } else {
547 llvm::Value *OutermostElementSize
548 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
549
550 llvm::Value *NumOutermostElements = NumElements;
551
552 // Scale NumElements by the array size multiplier. This might
553 // overflow, but only if the multiplication below also overflows,
554 // in which case this multiplication isn't used.
555 if (ArraySizeMultiplier != 1)
556 NumElements = CGF.Builder.CreateMul(NumElements,
557 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
558
559 // The requested size of the outermost array is non-constant.
560 // Multiply that by the static size of the elements of that array;
561 // on unsigned overflow, set the size to -1 to trigger an
562 // exception from the allocation routine. This is sufficient to
563 // prevent buffer overruns from the allocator returning a
564 // seemingly valid pointer to insufficient space. This idea comes
565 // originally from MSVC, and GCC has an open bug requesting
566 // similar behavior:
567 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
568 //
569 // This will not be sufficient for C++0x, which requires a
570 // specific exception class (std::bad_array_new_length).
571 // That will require ABI support that has not yet been specified.
572 const llvm::Type *Types[] = { SizeTy };
573 llvm::Value *UMulF
574 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
575 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
576 OutermostElementSize);
577
578 // The overflow bit.
579 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
580
581 // The result of the multiplication.
582 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
583
584 // If we have a cookie, we need to add that size in, too.
585 if (!CookieSize.isZero()) {
586 SizeWithoutCookie = Size;
587
588 llvm::Value *CookieSizeV
589 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
590 llvm::Value *UAddF
591 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
592 llvm::Value *AddRes
593 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
594
595 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
596
597 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedman5536daa2011-04-09 19:54:33 +0000598 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall1e7fe752010-09-02 09:58:18 +0000599 }
600
601 Size = CGF.Builder.CreateSelect(DidOverflow,
602 llvm::ConstantInt::get(SizeTy, -1),
603 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000604 }
John McCall1e7fe752010-09-02 09:58:18 +0000605
606 if (CookieSize.isZero())
607 SizeWithoutCookie = Size;
608 else
609 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
610
Chris Lattner806941e2010-07-20 21:55:52 +0000611 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000612}
613
Fariborz Jahanianef668722010-06-25 18:26:07 +0000614static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
615 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000616
617 assert(E->getNumConstructorArgs() == 1 &&
618 "Can only have one argument to initializer of POD type.");
619
620 const Expr *Init = E->getConstructorArg(0);
621 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000622
623 unsigned Alignment =
624 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000625 if (!CGF.hasAggregateLLVMType(AllocType))
626 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000627 AllocType.isVolatileQualified(), Alignment,
628 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000629 else if (AllocType->isAnyComplexType())
630 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
631 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000632 else {
633 AggValueSlot Slot
634 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
635 CGF.EmitAggExpr(Init, Slot);
636 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000637}
638
639void
640CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
641 llvm::Value *NewPtr,
642 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000643 // We have a POD type.
644 if (E->getNumConstructorArgs() == 0)
645 return;
646
Fariborz Jahanianef668722010-06-25 18:26:07 +0000647 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
648
649 // Create a temporary for the loop index and initialize it with 0.
650 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
651 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
652 Builder.CreateStore(Zero, IndexPtr);
653
654 // Start the loop with a block that tests the condition.
655 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
656 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
657
658 EmitBlock(CondBlock);
659
660 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
661
662 // Generate: if (loop-index < number-of-elements fall to the loop body,
663 // otherwise, go to the block after the for-loop.
664 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
665 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
666 // If the condition is true, execute the body.
667 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
668
669 EmitBlock(ForBody);
670
671 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
672 // Inside the loop body, emit the constructor call on the array element.
673 Counter = Builder.CreateLoad(IndexPtr);
674 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
675 "arrayidx");
676 StoreAnyExprIntoOneUnit(*this, E, Address);
677
678 EmitBlock(ContinueBlock);
679
680 // Emit the increment of the loop counter.
681 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
682 Counter = Builder.CreateLoad(IndexPtr);
683 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
684 Builder.CreateStore(NextVal, IndexPtr);
685
686 // Finally, branch back up to the condition for the next iteration.
687 EmitBranch(CondBlock);
688
689 // Emit the fall-through block.
690 EmitBlock(AfterFor, true);
691}
692
Douglas Gregor59174c02010-07-21 01:10:17 +0000693static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
694 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000695 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000696 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000697 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000698 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000699}
700
Anders Carlssona4d4c012009-09-23 16:07:23 +0000701static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
702 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000703 llvm::Value *NumElements,
704 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000705 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000706 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000707 bool RequiresZeroInitialization = false;
708 if (Ctor->getParent()->hasTrivialConstructor()) {
709 // If new expression did not specify value-initialization, then there
710 // is no initialization.
711 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
712 return;
713
John McCallf16aa102010-08-22 21:01:12 +0000714 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000715 // Optimization: since zero initialization will just set the memory
716 // to all zeroes, generate a single memset to do it in one shot.
717 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
718 AllocSizeWithoutCookie);
719 return;
720 }
721
722 RequiresZeroInitialization = true;
723 }
724
725 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
726 E->constructor_arg_begin(),
727 E->constructor_arg_end(),
728 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000729 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000730 } else if (E->getNumConstructorArgs() == 1 &&
731 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
732 // Optimization: since zero initialization will just set the memory
733 // to all zeroes, generate a single memset to do it in one shot.
734 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
735 AllocSizeWithoutCookie);
736 return;
737 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000738 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
739 return;
740 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000741 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000742
743 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000744 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
745 // direct initialization. C++ [dcl.init]p5 requires that we
746 // zero-initialize storage if there are no user-declared constructors.
747 if (E->hasInitializer() &&
748 !Ctor->getParent()->hasUserDeclaredConstructor() &&
749 !Ctor->getParent()->isEmpty())
750 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
751
Douglas Gregor84745672010-07-07 23:37:33 +0000752 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
753 NewPtr, E->constructor_arg_begin(),
754 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000755
756 return;
757 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000758 // We have a POD type.
759 if (E->getNumConstructorArgs() == 0)
760 return;
761
Fariborz Jahanianef668722010-06-25 18:26:07 +0000762 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000763}
764
John McCall7d8647f2010-09-14 07:57:04 +0000765namespace {
766 /// A cleanup to call the given 'operator delete' function upon
767 /// abnormal exit from a new expression.
768 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
769 size_t NumPlacementArgs;
770 const FunctionDecl *OperatorDelete;
771 llvm::Value *Ptr;
772 llvm::Value *AllocSize;
773
774 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
775
776 public:
777 static size_t getExtraSize(size_t NumPlacementArgs) {
778 return NumPlacementArgs * sizeof(RValue);
779 }
780
781 CallDeleteDuringNew(size_t NumPlacementArgs,
782 const FunctionDecl *OperatorDelete,
783 llvm::Value *Ptr,
784 llvm::Value *AllocSize)
785 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
786 Ptr(Ptr), AllocSize(AllocSize) {}
787
788 void setPlacementArg(unsigned I, RValue Arg) {
789 assert(I < NumPlacementArgs && "index out of range");
790 getPlacementArgs()[I] = Arg;
791 }
792
793 void Emit(CodeGenFunction &CGF, bool IsForEH) {
794 const FunctionProtoType *FPT
795 = OperatorDelete->getType()->getAs<FunctionProtoType>();
796 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000797 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000798
799 CallArgList DeleteArgs;
800
801 // The first argument is always a void*.
802 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
803 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
804
805 // A member 'operator delete' can take an extra 'size_t' argument.
806 if (FPT->getNumArgs() == NumPlacementArgs + 2)
807 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
808
809 // Pass the rest of the arguments, which must match exactly.
810 for (unsigned I = 0; I != NumPlacementArgs; ++I)
811 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
812
813 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000814 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000815 CGF.CGM.GetAddrOfFunction(OperatorDelete),
816 ReturnValueSlot(), DeleteArgs, OperatorDelete);
817 }
818 };
John McCall3019c442010-09-17 00:50:28 +0000819
820 /// A cleanup to call the given 'operator delete' function upon
821 /// abnormal exit from a new expression when the new expression is
822 /// conditional.
823 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
824 size_t NumPlacementArgs;
825 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000826 DominatingValue<RValue>::saved_type Ptr;
827 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000828
John McCall804b8072011-01-28 10:53:53 +0000829 DominatingValue<RValue>::saved_type *getPlacementArgs() {
830 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000831 }
832
833 public:
834 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000835 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000836 }
837
838 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
839 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000840 DominatingValue<RValue>::saved_type Ptr,
841 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000842 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
843 Ptr(Ptr), AllocSize(AllocSize) {}
844
John McCall804b8072011-01-28 10:53:53 +0000845 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000846 assert(I < NumPlacementArgs && "index out of range");
847 getPlacementArgs()[I] = Arg;
848 }
849
850 void Emit(CodeGenFunction &CGF, bool IsForEH) {
851 const FunctionProtoType *FPT
852 = OperatorDelete->getType()->getAs<FunctionProtoType>();
853 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
854 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
855
856 CallArgList DeleteArgs;
857
858 // The first argument is always a void*.
859 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCall804b8072011-01-28 10:53:53 +0000860 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall3019c442010-09-17 00:50:28 +0000861
862 // A member 'operator delete' can take an extra 'size_t' argument.
863 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000864 RValue RV = AllocSize.restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000865 DeleteArgs.push_back(std::make_pair(RV, *AI++));
866 }
867
868 // Pass the rest of the arguments, which must match exactly.
869 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000870 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000871 DeleteArgs.push_back(std::make_pair(RV, *AI++));
872 }
873
874 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000875 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000876 CGF.CGM.GetAddrOfFunction(OperatorDelete),
877 ReturnValueSlot(), DeleteArgs, OperatorDelete);
878 }
879 };
880}
881
882/// Enter a cleanup to call 'operator delete' if the initializer in a
883/// new-expression throws.
884static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
885 const CXXNewExpr *E,
886 llvm::Value *NewPtr,
887 llvm::Value *AllocSize,
888 const CallArgList &NewArgs) {
889 // If we're not inside a conditional branch, then the cleanup will
890 // dominate and we can do the easier (and more efficient) thing.
891 if (!CGF.isInConditionalBranch()) {
892 CallDeleteDuringNew *Cleanup = CGF.EHStack
893 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
894 E->getNumPlacementArgs(),
895 E->getOperatorDelete(),
896 NewPtr, AllocSize);
897 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
898 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
899
900 return;
901 }
902
903 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000904 DominatingValue<RValue>::saved_type SavedNewPtr =
905 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
906 DominatingValue<RValue>::saved_type SavedAllocSize =
907 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000908
909 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
910 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
911 E->getNumPlacementArgs(),
912 E->getOperatorDelete(),
913 SavedNewPtr,
914 SavedAllocSize);
915 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000916 Cleanup->setPlacementArg(I,
917 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000918
919 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000920}
921
Anders Carlsson16d81b82009-09-22 22:53:17 +0000922llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000923 // The element type being allocated.
924 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +0000925
John McCallc2f3e7f2011-03-07 03:12:35 +0000926 // 1. Build a call to the allocation function.
927 FunctionDecl *allocator = E->getOperatorNew();
928 const FunctionProtoType *allocatorType =
929 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000930
John McCallc2f3e7f2011-03-07 03:12:35 +0000931 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000932
933 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000934 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000935
John McCallc2f3e7f2011-03-07 03:12:35 +0000936 llvm::Value *numElements = 0;
937 llvm::Value *allocSizeWithoutCookie = 0;
938 llvm::Value *allocSize =
939 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
940 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000941
John McCallc2f3e7f2011-03-07 03:12:35 +0000942 allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000943
944 // Emit the rest of the arguments.
945 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +0000946 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000947
948 // First, use the types from the function type.
949 // We start at 1 here because the first argument (the allocation size)
950 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +0000951 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
952 ++i, ++placementArg) {
953 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000954
John McCallc2f3e7f2011-03-07 03:12:35 +0000955 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
956 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +0000957 "type mismatch in call argument!");
958
John McCall413ebdb2011-03-11 20:59:21 +0000959 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000960 }
961
962 // Either we've emitted all the call args, or we have a call to a
963 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +0000964 assert((placementArg == E->placement_arg_end() ||
965 allocatorType->isVariadic()) &&
966 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +0000967
968 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000969 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
970 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +0000971 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +0000972 }
973
John McCallc2f3e7f2011-03-07 03:12:35 +0000974 // Emit the allocation call.
Anders Carlsson16d81b82009-09-22 22:53:17 +0000975 RValue RV =
John McCallc2f3e7f2011-03-07 03:12:35 +0000976 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
977 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
978 allocatorArgs, allocator);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000979
John McCallc2f3e7f2011-03-07 03:12:35 +0000980 // Emit a null check on the allocation result if the allocation
981 // function is allowed to return null (because it has a non-throwing
982 // exception spec; for this part, we inline
983 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
984 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000985 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallc2f3e7f2011-03-07 03:12:35 +0000986 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +0000987
John McCallc2f3e7f2011-03-07 03:12:35 +0000988 llvm::BasicBlock *nullCheckBB = 0;
989 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000990
John McCallc2f3e7f2011-03-07 03:12:35 +0000991 llvm::Value *allocation = RV.getScalarVal();
992 unsigned AS =
993 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000994
John McCalla7f633f2011-03-07 01:52:56 +0000995 // The null-check means that the initializer is conditionally
996 // evaluated.
997 ConditionalEvaluation conditional(*this);
998
John McCallc2f3e7f2011-03-07 03:12:35 +0000999 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001000 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001001
1002 nullCheckBB = Builder.GetInsertBlock();
1003 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1004 contBB = createBasicBlock("new.cont");
1005
1006 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1007 Builder.CreateCondBr(isNull, contBB, notNullBB);
1008 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001009 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001010
John McCallc2f3e7f2011-03-07 03:12:35 +00001011 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001012 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001013 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001014 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001015 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1016 numElements,
1017 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001018 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001019
John McCall7d8647f2010-09-14 07:57:04 +00001020 // If there's an operator delete, enter a cleanup to call it if an
1021 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001022 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7d8647f2010-09-14 07:57:04 +00001023 if (E->getOperatorDelete()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001024 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1025 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001026 }
1027
John McCallc2f3e7f2011-03-07 03:12:35 +00001028 const llvm::Type *elementPtrTy
1029 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1030 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001031
John McCall1e7fe752010-09-02 09:58:18 +00001032 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001033 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001034
1035 // NewPtr is a pointer to the base element type. If we're
1036 // allocating an array of arrays, we'll need to cast back to the
1037 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001038 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1039 if (result->getType() != resultType)
1040 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001041 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001042 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001043 }
John McCall7d8647f2010-09-14 07:57:04 +00001044
1045 // Deactivate the 'operator delete' cleanup if we finished
1046 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001047 if (operatorDeleteCleanup.isValid())
1048 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001049
John McCallc2f3e7f2011-03-07 03:12:35 +00001050 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001051 conditional.end(*this);
1052
John McCallc2f3e7f2011-03-07 03:12:35 +00001053 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1054 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001055
Jay Foadbbf3bac2011-03-30 11:28:58 +00001056 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001057 PHI->addIncoming(result, notNullBB);
1058 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1059 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001060
John McCallc2f3e7f2011-03-07 03:12:35 +00001061 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001062 }
John McCall1e7fe752010-09-02 09:58:18 +00001063
John McCallc2f3e7f2011-03-07 03:12:35 +00001064 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001065}
1066
Eli Friedman5fe05982009-11-18 00:50:08 +00001067void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1068 llvm::Value *Ptr,
1069 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001070 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1071
Eli Friedman5fe05982009-11-18 00:50:08 +00001072 const FunctionProtoType *DeleteFTy =
1073 DeleteFD->getType()->getAs<FunctionProtoType>();
1074
1075 CallArgList DeleteArgs;
1076
Anders Carlsson871d0782009-12-13 20:04:38 +00001077 // Check if we need to pass the size to the delete operator.
1078 llvm::Value *Size = 0;
1079 QualType SizeTy;
1080 if (DeleteFTy->getNumArgs() == 2) {
1081 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001082 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1083 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1084 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001085 }
1086
Eli Friedman5fe05982009-11-18 00:50:08 +00001087 QualType ArgTy = DeleteFTy->getArgType(0);
1088 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1089 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1090
Anders Carlsson871d0782009-12-13 20:04:38 +00001091 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +00001092 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +00001093
1094 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001095 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001096 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001097 DeleteArgs, DeleteFD);
1098}
1099
John McCall1e7fe752010-09-02 09:58:18 +00001100namespace {
1101 /// Calls the given 'operator delete' on a single object.
1102 struct CallObjectDelete : EHScopeStack::Cleanup {
1103 llvm::Value *Ptr;
1104 const FunctionDecl *OperatorDelete;
1105 QualType ElementType;
1106
1107 CallObjectDelete(llvm::Value *Ptr,
1108 const FunctionDecl *OperatorDelete,
1109 QualType ElementType)
1110 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1111
1112 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1113 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1114 }
1115 };
1116}
1117
1118/// Emit the code for deleting a single object.
1119static void EmitObjectDelete(CodeGenFunction &CGF,
1120 const FunctionDecl *OperatorDelete,
1121 llvm::Value *Ptr,
1122 QualType ElementType) {
1123 // Find the destructor for the type, if applicable. If the
1124 // destructor is virtual, we'll just emit the vcall and return.
1125 const CXXDestructorDecl *Dtor = 0;
1126 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1127 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1128 if (!RD->hasTrivialDestructor()) {
1129 Dtor = RD->getDestructor();
1130
1131 if (Dtor->isVirtual()) {
1132 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001133 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1134 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001135 /*isVariadic=*/false);
1136
1137 llvm::Value *Callee
1138 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1139 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1140 0, 0);
1141
1142 // The dtor took care of deleting the object.
1143 return;
1144 }
1145 }
1146 }
1147
1148 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001149 // This doesn't have to a conditional cleanup because we're going
1150 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001151 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1152 Ptr, OperatorDelete, ElementType);
1153
1154 if (Dtor)
1155 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1156 /*ForVirtualBase=*/false, Ptr);
1157
1158 CGF.PopCleanupBlock();
1159}
1160
1161namespace {
1162 /// Calls the given 'operator delete' on an array of objects.
1163 struct CallArrayDelete : EHScopeStack::Cleanup {
1164 llvm::Value *Ptr;
1165 const FunctionDecl *OperatorDelete;
1166 llvm::Value *NumElements;
1167 QualType ElementType;
1168 CharUnits CookieSize;
1169
1170 CallArrayDelete(llvm::Value *Ptr,
1171 const FunctionDecl *OperatorDelete,
1172 llvm::Value *NumElements,
1173 QualType ElementType,
1174 CharUnits CookieSize)
1175 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1176 ElementType(ElementType), CookieSize(CookieSize) {}
1177
1178 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1179 const FunctionProtoType *DeleteFTy =
1180 OperatorDelete->getType()->getAs<FunctionProtoType>();
1181 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1182
1183 CallArgList Args;
1184
1185 // Pass the pointer as the first argument.
1186 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1187 llvm::Value *DeletePtr
1188 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1189 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1190
1191 // Pass the original requested size as the second argument.
1192 if (DeleteFTy->getNumArgs() == 2) {
1193 QualType size_t = DeleteFTy->getArgType(1);
1194 const llvm::IntegerType *SizeTy
1195 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1196
1197 CharUnits ElementTypeSize =
1198 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1199
1200 // The size of an element, multiplied by the number of elements.
1201 llvm::Value *Size
1202 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1203 Size = CGF.Builder.CreateMul(Size, NumElements);
1204
1205 // Plus the size of the cookie if applicable.
1206 if (!CookieSize.isZero()) {
1207 llvm::Value *CookieSizeV
1208 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1209 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1210 }
1211
1212 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1213 }
1214
1215 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001216 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001217 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1218 ReturnValueSlot(), Args, OperatorDelete);
1219 }
1220 };
1221}
1222
1223/// Emit the code for deleting an array of objects.
1224static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001225 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001226 llvm::Value *Ptr,
1227 QualType ElementType) {
1228 llvm::Value *NumElements = 0;
1229 llvm::Value *AllocatedPtr = 0;
1230 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001231 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001232 NumElements, AllocatedPtr, CookieSize);
1233
1234 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1235
1236 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001237 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001238 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1239 AllocatedPtr, OperatorDelete,
1240 NumElements, ElementType,
1241 CookieSize);
1242
1243 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1244 if (!RD->hasTrivialDestructor()) {
1245 assert(NumElements && "ReadArrayCookie didn't find element count"
1246 " for a class with destructor");
1247 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1248 }
1249 }
1250
1251 CGF.PopCleanupBlock();
1252}
1253
Anders Carlsson16d81b82009-09-22 22:53:17 +00001254void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001255
Douglas Gregor90916562009-09-29 18:16:17 +00001256 // Get at the argument before we performed the implicit conversion
1257 // to void*.
1258 const Expr *Arg = E->getArgument();
1259 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001260 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001261 ICE->getType()->isVoidPointerType())
1262 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001263 else
1264 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001265 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001266
Douglas Gregor90916562009-09-29 18:16:17 +00001267 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001268
1269 // Null check the pointer.
1270 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1271 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1272
1273 llvm::Value *IsNull =
1274 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1275 "isnull");
1276
1277 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1278 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001279
John McCall1e7fe752010-09-02 09:58:18 +00001280 // We might be deleting a pointer to array. If so, GEP down to the
1281 // first non-array element.
1282 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1283 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1284 if (DeleteTy->isConstantArrayType()) {
1285 llvm::Value *Zero = Builder.getInt32(0);
1286 llvm::SmallVector<llvm::Value*,8> GEP;
1287
1288 GEP.push_back(Zero); // point at the outermost array
1289
1290 // For each layer of array type we're pointing at:
1291 while (const ConstantArrayType *Arr
1292 = getContext().getAsConstantArrayType(DeleteTy)) {
1293 // 1. Unpeel the array type.
1294 DeleteTy = Arr->getElementType();
1295
1296 // 2. GEP to the first element of the array.
1297 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001298 }
John McCall1e7fe752010-09-02 09:58:18 +00001299
1300 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001301 }
1302
Douglas Gregoreede61a2010-09-02 17:38:50 +00001303 assert(ConvertTypeForMem(DeleteTy) ==
1304 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001305
1306 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001307 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001308 } else {
1309 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1310 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001311
Anders Carlsson16d81b82009-09-22 22:53:17 +00001312 EmitBlock(DeleteEnd);
1313}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001314
John McCall3ad32c82011-01-28 08:37:24 +00001315llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001316 QualType Ty = E->getType();
1317 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001318
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001319 if (E->isTypeOperand()) {
1320 llvm::Constant *TypeInfo =
1321 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1322 return Builder.CreateBitCast(TypeInfo, LTy);
1323 }
1324
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001325 Expr *subE = E->getExprOperand();
Mike Stump5fae8562009-11-17 22:33:00 +00001326 Ty = subE->getType();
1327 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1328 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001329 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1330 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1331 if (RD->isPolymorphic()) {
1332 // FIXME: if subE is an lvalue do
1333 LValue Obj = EmitLValue(subE);
1334 llvm::Value *This = Obj.getAddress();
Mike Stumpf549e892009-11-15 16:52:53 +00001335 // We need to do a zero check for *p, unless it has NonNullAttr.
1336 // FIXME: PointerType->hasAttr<NonNullAttr>()
1337 bool CanBeZero = false;
Mike Stumpdb519a42009-11-17 00:45:21 +00001338 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +00001339 if (UO->getOpcode() == UO_Deref)
Mike Stumpf549e892009-11-15 16:52:53 +00001340 CanBeZero = true;
1341 if (CanBeZero) {
1342 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1343 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1344
Dan Gohman043fb9a2010-10-26 18:44:08 +00001345 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1346 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stumpf549e892009-11-15 16:52:53 +00001347 NonZeroBlock, ZeroBlock);
1348 EmitBlock(ZeroBlock);
1349 /// Call __cxa_bad_typeid
John McCalld16c2cf2011-02-08 08:22:06 +00001350 const llvm::Type *ResultType = llvm::Type::getVoidTy(getLLVMContext());
Mike Stumpf549e892009-11-15 16:52:53 +00001351 const llvm::FunctionType *FTy;
1352 FTy = llvm::FunctionType::get(ResultType, false);
1353 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stumpc849c052009-11-16 06:50:58 +00001354 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stumpf549e892009-11-15 16:52:53 +00001355 Builder.CreateUnreachable();
1356 EmitBlock(NonZeroBlock);
1357 }
Dan Gohman043fb9a2010-10-26 18:44:08 +00001358 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001359 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1360 V = Builder.CreateLoad(V);
1361 return V;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001362 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001363 }
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001364 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001365}
Mike Stumpc849c052009-11-16 06:50:58 +00001366
1367llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1368 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001369 QualType SrcTy = DCE->getSubExpr()->getType();
1370 QualType DestTy = DCE->getTypeAsWritten();
1371 QualType InnerType = DestTy->getPointeeType();
1372
Mike Stumpc849c052009-11-16 06:50:58 +00001373 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump2b35baf2009-11-16 22:52:20 +00001374
Mike Stumpc849c052009-11-16 06:50:58 +00001375 bool CanBeZero = false;
Mike Stumpc849c052009-11-16 06:50:58 +00001376 bool ToVoid = false;
Mike Stump2b35baf2009-11-16 22:52:20 +00001377 bool ThrowOnBad = false;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001378 if (DestTy->isPointerType()) {
Mike Stumpc849c052009-11-16 06:50:58 +00001379 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1380 CanBeZero = true;
1381 if (InnerType->isVoidType())
1382 ToVoid = true;
1383 } else {
1384 LTy = LTy->getPointerTo();
Douglas Gregor485ee322010-05-14 21:14:41 +00001385
1386 // FIXME: What if exceptions are disabled?
Mike Stumpc849c052009-11-16 06:50:58 +00001387 ThrowOnBad = true;
1388 }
1389
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001390 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1391 SrcTy = SrcTy->getPointeeType();
1392 SrcTy = SrcTy.getUnqualifiedType();
1393
Anders Carlsson6f0e4852009-12-18 14:55:04 +00001394 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001395 DestTy = DestTy->getPointeeType();
1396 DestTy = DestTy.getUnqualifiedType();
Mike Stumpc849c052009-11-16 06:50:58 +00001397
Mike Stumpc849c052009-11-16 06:50:58 +00001398 llvm::BasicBlock *ContBlock = createBasicBlock();
1399 llvm::BasicBlock *NullBlock = 0;
1400 llvm::BasicBlock *NonZeroBlock = 0;
1401 if (CanBeZero) {
1402 NonZeroBlock = createBasicBlock();
1403 NullBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001404 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +00001405 EmitBlock(NonZeroBlock);
1406 }
1407
Mike Stumpc849c052009-11-16 06:50:58 +00001408 llvm::BasicBlock *BadCastBlock = 0;
Mike Stumpc849c052009-11-16 06:50:58 +00001409
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001410 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump2b35baf2009-11-16 22:52:20 +00001411
1412 // See if this is a dynamic_cast(void*)
1413 if (ToVoid) {
1414 llvm::Value *This = V;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001415 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump2b35baf2009-11-16 22:52:20 +00001416 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1417 V = Builder.CreateLoad(V, "offset to top");
John McCalld16c2cf2011-02-08 08:22:06 +00001418 This = EmitCastToVoidPtr(This);
Mike Stump2b35baf2009-11-16 22:52:20 +00001419 V = Builder.CreateInBoundsGEP(This, V);
1420 V = Builder.CreateBitCast(V, LTy);
1421 } else {
1422 /// Call __dynamic_cast
John McCalld16c2cf2011-02-08 08:22:06 +00001423 const llvm::Type *ResultType = Int8PtrTy;
Mike Stump2b35baf2009-11-16 22:52:20 +00001424 const llvm::FunctionType *FTy;
1425 std::vector<const llvm::Type*> ArgTys;
John McCalld16c2cf2011-02-08 08:22:06 +00001426 ArgTys.push_back(Int8PtrTy);
1427 ArgTys.push_back(Int8PtrTy);
1428 ArgTys.push_back(Int8PtrTy);
Mike Stump2b35baf2009-11-16 22:52:20 +00001429 ArgTys.push_back(PtrDiffTy);
1430 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump2b35baf2009-11-16 22:52:20 +00001431
1432 // FIXME: Calculate better hint.
1433 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001434
1435 assert(SrcTy->isRecordType() && "Src type must be record type!");
1436 assert(DestTy->isRecordType() && "Dest type must be record type!");
1437
Douglas Gregor154fe982009-12-23 22:04:40 +00001438 llvm::Value *SrcArg
1439 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1440 llvm::Value *DestArg
1441 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001442
John McCalld16c2cf2011-02-08 08:22:06 +00001443 V = Builder.CreateBitCast(V, Int8PtrTy);
Mike Stump2b35baf2009-11-16 22:52:20 +00001444 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001445 V, SrcArg, DestArg, hint);
Mike Stump2b35baf2009-11-16 22:52:20 +00001446 V = Builder.CreateBitCast(V, LTy);
1447
1448 if (ThrowOnBad) {
1449 BadCastBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001450 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump2b35baf2009-11-16 22:52:20 +00001451 EmitBlock(BadCastBlock);
Douglas Gregor485ee322010-05-14 21:14:41 +00001452 /// Invoke __cxa_bad_cast
John McCalld16c2cf2011-02-08 08:22:06 +00001453 ResultType = llvm::Type::getVoidTy(getLLVMContext());
Mike Stump2b35baf2009-11-16 22:52:20 +00001454 const llvm::FunctionType *FBadTy;
Mike Stumpfde17be2009-11-17 03:01:03 +00001455 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump2b35baf2009-11-16 22:52:20 +00001456 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregor485ee322010-05-14 21:14:41 +00001457 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1458 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1459 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1460 EmitBlock(Cont);
1461 } else {
1462 // FIXME: Does this ever make sense?
1463 Builder.CreateCall(F)->setDoesNotReturn();
1464 }
Mike Stump8b152b82009-11-17 00:08:50 +00001465 Builder.CreateUnreachable();
Mike Stump2b35baf2009-11-16 22:52:20 +00001466 }
Mike Stumpc849c052009-11-16 06:50:58 +00001467 }
1468
1469 if (CanBeZero) {
1470 Builder.CreateBr(ContBlock);
1471 EmitBlock(NullBlock);
1472 Builder.CreateBr(ContBlock);
1473 }
1474 EmitBlock(ContBlock);
1475 if (CanBeZero) {
Jay Foadbbf3bac2011-03-30 11:28:58 +00001476 llvm::PHINode *PHI = Builder.CreatePHI(LTy, 2);
Mike Stumpc849c052009-11-16 06:50:58 +00001477 PHI->addIncoming(V, NonZeroBlock);
1478 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +00001479 V = PHI;
1480 }
1481
1482 return V;
1483}