blob: 734449005fbcfb7d36010731d7e9eb6bb4bd00ae [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 Carlssonbbe277c2011-04-13 02:35:36 +000020#include "llvm/Support/CallSite.h"
21
Anders Carlssoncc52f652009-09-22 22:53:17 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson27da15b2010-01-01 20:29:01 +000025RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26 llvm::Value *Callee,
27 ReturnValueSlot ReturnValue,
28 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000029 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000030 CallExpr::const_arg_iterator ArgBeg,
31 CallExpr::const_arg_iterator ArgEnd) {
32 assert(MD->isInstance() &&
33 "Trying to emit a member call expr on a static method!");
34
35 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
36
37 CallArgList Args;
38
39 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000040 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000041
Anders Carlssone36a6b32010-01-02 01:01:18 +000042 // If there is a VTT parameter, emit it.
43 if (VTT) {
44 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +000045 Args.add(RValue::get(VTT), T);
Anders Carlssone36a6b32010-01-02 01:01:18 +000046 }
47
Anders Carlsson27da15b2010-01-01 20:29:01 +000048 // And the rest of the call args
49 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
50
John McCallab26cfa2010-02-05 21:31:56 +000051 QualType ResultType = FPT->getResultType();
Tilmann Scheller99cc30c2011-03-02 21:36:49 +000052 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
53 FPT->getExtInfo()),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000054 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000055}
56
Anders Carlsson1ae64c52011-01-29 03:52:01 +000057static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson6b3afd72011-01-29 05:04:11 +000058 const Expr *E = Base;
59
60 while (true) {
61 E = E->IgnoreParens();
62 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
63 if (CE->getCastKind() == CK_DerivedToBase ||
64 CE->getCastKind() == CK_UncheckedDerivedToBase ||
65 CE->getCastKind() == CK_NoOp) {
66 E = CE->getSubExpr();
67 continue;
68 }
69 }
70
71 break;
72 }
73
74 QualType DerivedType = E->getType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +000075 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
76 DerivedType = PTy->getPointeeType();
77
78 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
79}
80
Anders Carlssonc53d9e82011-04-10 18:20:53 +000081// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
82// quite what we want.
83static const Expr *skipNoOpCastsAndParens(const Expr *E) {
84 while (true) {
85 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
86 E = PE->getSubExpr();
87 continue;
88 }
89
90 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
91 if (CE->getCastKind() == CK_NoOp) {
92 E = CE->getSubExpr();
93 continue;
94 }
95 }
96 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
97 if (UO->getOpcode() == UO_Extension) {
98 E = UO->getSubExpr();
99 continue;
100 }
101 }
102 return E;
103 }
104}
105
Anders Carlsson27da15b2010-01-01 20:29:01 +0000106/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
107/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000108static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
109 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +0000110 const CXXMethodDecl *MD) {
111
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000112 // When building with -fapple-kext, all calls must go through the vtable since
113 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000114 if (Context.getLangOptions().AppleKext)
115 return false;
116
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000117 // If the most derived class is marked final, we know that no subclass can
118 // override this member function and so we can devirtualize it. For example:
119 //
120 // struct A { virtual void f(); }
121 // struct B final : A { };
122 //
123 // void f(B *b) {
124 // b->f();
125 // }
126 //
127 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
128 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
129 return true;
130
Anders Carlsson19588aa2011-01-23 21:07:30 +0000131 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000132 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000133 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000134 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000135
Anders Carlsson19588aa2011-01-23 21:07:30 +0000136 // Similarly, if the class itself is marked 'final' it can't be overridden
137 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000138 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000139 return true;
140
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000141 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000142 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
144 // This is a record decl. We know the type and can devirtualize it.
145 return VD->getType()->isRecordType();
146 }
147
148 return false;
149 }
150
151 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000152 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000153 return true;
154
155 // And calls on bound temporaries.
156 if (isa<CXXBindTemporaryExpr>(Base))
157 return true;
158
159 // Check if this is a call expr that returns a record type.
160 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
161 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000162
Anders Carlsson27da15b2010-01-01 20:29:01 +0000163 // We can't devirtualize the call.
164 return false;
165}
166
Francois Pichet64225792011-01-18 05:04:39 +0000167// Note: This function also emit constructor calls to support a MSVC
168// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000169RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
170 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000171 const Expr *callee = CE->getCallee()->IgnoreParens();
172
173 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000174 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000175
176 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000177 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
178
Devang Patel91bbb552010-09-30 19:05:55 +0000179 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000180 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
181 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000182 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
183 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
184 DI->getOrCreateRecordType(PTy->getPointeeType(),
185 MD->getParent()->getLocation());
186 }
187 }
188
Anders Carlsson27da15b2010-01-01 20:29:01 +0000189 if (MD->isStatic()) {
190 // The method is static, emit it as we would a regular call.
191 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
192 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
193 ReturnValue, CE->arg_begin(), CE->arg_end());
194 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000195
John McCall0d635f52010-09-03 01:26:39 +0000196 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000197 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000198 if (ME->isArrow())
199 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000200 else
201 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000202
John McCall0d635f52010-09-03 01:26:39 +0000203 if (MD->isTrivial()) {
204 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000205 if (isa<CXXConstructorDecl>(MD) &&
206 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
207 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000208
Francois Pichet64225792011-01-18 05:04:39 +0000209 if (MD->isCopyAssignmentOperator()) {
210 // We don't like to generate the trivial copy assignment operator when
211 // it isn't necessary; just produce the proper effect here.
212 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
213 EmitAggregateCopy(This, RHS, CE->getType());
214 return RValue::get(This);
215 }
216
217 if (isa<CXXConstructorDecl>(MD) &&
218 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
219 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
220 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
221 CE->arg_begin(), CE->arg_end());
222 return RValue::get(This);
223 }
224 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000225 }
226
John McCall0d635f52010-09-03 01:26:39 +0000227 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000228 const CGFunctionInfo *FInfo = 0;
229 if (isa<CXXDestructorDecl>(MD))
230 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
231 Dtor_Complete);
232 else if (isa<CXXConstructorDecl>(MD))
233 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
234 Ctor_Complete);
235 else
236 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCall0d635f52010-09-03 01:26:39 +0000237
238 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
239 const llvm::Type *Ty
Francois Pichet64225792011-01-18 05:04:39 +0000240 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCall0d635f52010-09-03 01:26:39 +0000241
Anders Carlsson27da15b2010-01-01 20:29:01 +0000242 // C++ [class.virtual]p12:
243 // Explicit qualification with the scope operator (5.1) suppresses the
244 // virtual call mechanism.
245 //
246 // We also don't emit a virtual call if the base expression has a record type
247 // because then we know what the type is.
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000248 bool UseVirtualCall;
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000249 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
250 && !canDevirtualizeMemberFunctionCalls(getContext(),
251 ME->getBase(), MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000253 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
254 if (UseVirtualCall) {
255 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 } else {
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000257 if (getContext().getLangOptions().AppleKext &&
258 MD->isVirtual() &&
259 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000260 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000261 else
262 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000263 }
Francois Pichet64225792011-01-18 05:04:39 +0000264 } else if (const CXXConstructorDecl *Ctor =
265 dyn_cast<CXXConstructorDecl>(MD)) {
266 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000267 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000268 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000269 } else {
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000270 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000271 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000272 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000273 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000274 else
275 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 }
277
Anders Carlssone36a6b32010-01-02 01:01:18 +0000278 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000279 CE->arg_begin(), CE->arg_end());
280}
281
282RValue
283CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
284 ReturnValueSlot ReturnValue) {
285 const BinaryOperator *BO =
286 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
287 const Expr *BaseExpr = BO->getLHS();
288 const Expr *MemFnExpr = BO->getRHS();
289
290 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000291 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000292
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000294 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 const CXXRecordDecl *RD =
296 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
297
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000299 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000300
301 // Emit the 'this' pointer.
302 llvm::Value *This;
303
John McCalle3027922010-08-25 11:45:40 +0000304 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305 This = EmitScalarExpr(BaseExpr);
306 else
307 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000308
John McCall475999d2010-08-22 00:05:51 +0000309 // Ask the ABI to load the callee. Note that This is modified.
310 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000311 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312
Anders Carlsson27da15b2010-01-01 20:29:01 +0000313 CallArgList Args;
314
315 QualType ThisType =
316 getContext().getPointerType(getContext().getTagDeclType(RD));
317
318 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000319 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000320
321 // And the rest of the call args
322 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0009fcc2011-04-26 20:42:42 +0000323 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000324 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000325}
326
327RValue
328CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
329 const CXXMethodDecl *MD,
330 ReturnValueSlot ReturnValue) {
331 assert(MD->isInstance() &&
332 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000333 LValue LV = EmitLValue(E->getArg(0));
334 llvm::Value *This = LV.getAddress();
335
Douglas Gregorec3bec02010-09-27 22:37:28 +0000336 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000337 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
338 if (ClassDecl->hasTrivialCopyAssignment()) {
339 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
340 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000341 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
342 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000343 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000344 return RValue::get(This);
345 }
346 }
347
Anders Carlssonc36783e2011-05-08 20:32:23 +0000348 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000349 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000350 E->arg_begin() + 1, E->arg_end());
351}
352
353void
John McCall7a626f62010-09-15 10:14:12 +0000354CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
355 AggValueSlot Dest) {
356 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000357 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000358
359 // If we require zero initialization before (or instead of) calling the
360 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000361 // constructor, emit the zero initialization now, unless destination is
362 // already zeroed.
363 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall7a626f62010-09-15 10:14:12 +0000364 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000365
366 // If this is a call to a trivial default constructor, do nothing.
367 if (CD->isTrivial() && CD->isDefaultConstructor())
368 return;
369
John McCall8ea46b62010-09-18 00:58:34 +0000370 // Elide the constructor if we're constructing from a temporary.
371 // The temporary check is required because Sema sets this on NRVO
372 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000373 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000374 assert(getContext().hasSameUnqualifiedType(E->getType(),
375 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000376 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
377 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000378 return;
379 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000380 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000381
382 const ConstantArrayType *Array
383 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000384 if (Array) {
385 QualType BaseElementTy = getContext().getBaseElementType(Array);
386 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
387 BasePtr = llvm::PointerType::getUnqual(BasePtr);
388 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000389 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000390
391 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
392 E->arg_begin(), E->arg_end());
393 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000394 else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000395 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000396 bool ForVirtualBase = false;
397
398 switch (E->getConstructionKind()) {
399 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000400 // We should be emitting a constructor; GlobalDecl will assert this
401 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000402 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000403
Alexis Hunt271c3682011-05-03 20:19:28 +0000404 case CXXConstructExpr::CK_Complete:
405 Type = Ctor_Complete;
406 break;
407
408 case CXXConstructExpr::CK_VirtualBase:
409 ForVirtualBase = true;
410 // fall-through
411
412 case CXXConstructExpr::CK_NonVirtualBase:
413 Type = Ctor_Base;
414 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000415
Anders Carlsson27da15b2010-01-01 20:29:01 +0000416 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000417 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000418 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000419 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000420}
421
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000422void
423CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
424 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000425 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000426 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000427 Exp = E->getSubExpr();
428 assert(isa<CXXConstructExpr>(Exp) &&
429 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
430 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
431 const CXXConstructorDecl *CD = E->getConstructor();
432 RunCleanupsScope Scope(*this);
433
434 // If we require zero initialization before (or instead of) calling the
435 // constructor, as can be the case with a non-user-provided default
436 // constructor, emit the zero initialization now.
437 // FIXME. Do I still need this for a copy ctor synthesis?
438 if (E->requiresZeroInitialization())
439 EmitNullInitialization(Dest, E->getType());
440
Chandler Carruth99da11c2010-11-15 13:54:43 +0000441 assert(!getContext().getAsConstantArrayType(E->getType())
442 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000443 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
444 E->arg_begin(), E->arg_end());
445}
446
John McCallaa4149a2010-08-23 01:17:59 +0000447/// Check whether the given operator new[] is the global placement
448/// operator new[].
449static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
450 const FunctionDecl *Fn) {
451 // Must be in global scope. Note that allocation functions can't be
452 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000453 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000454 return false;
455
456 // Signature must be void *operator new[](size_t, void*).
457 // The size_t is common to all operator new[]s.
458 if (Fn->getNumParams() != 2)
459 return false;
460
461 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
462 return (ParamType == Ctx.VoidPtrTy);
463}
464
John McCall8ed55a52010-09-02 09:58:18 +0000465static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
466 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000467 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000468 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000469
Anders Carlsson399f4992009-12-13 20:34:34 +0000470 // No cookie is required if the new operator being used is
471 // ::operator new[](size_t, void*).
472 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000473 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000474 return CharUnits::Zero();
475
John McCall284c48f2011-01-27 09:37:56 +0000476 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000477}
478
John McCall036f2f62011-05-15 07:14:44 +0000479static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
480 const CXXNewExpr *e,
481 llvm::Value *&numElements,
482 llvm::Value *&sizeWithoutCookie) {
483 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000484
John McCall036f2f62011-05-15 07:14:44 +0000485 if (!e->isArray()) {
486 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
487 sizeWithoutCookie
488 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
489 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000490 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000491
John McCall036f2f62011-05-15 07:14:44 +0000492 // The width of size_t.
493 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
494
John McCall8ed55a52010-09-02 09:58:18 +0000495 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000496 llvm::APInt cookieSize(sizeWidth,
497 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000498
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000499 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000500 // We multiply the size of all dimensions for NumElements.
501 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000502 numElements = CGF.EmitScalarExpr(e->getArraySize());
503 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000504
John McCall036f2f62011-05-15 07:14:44 +0000505 // The number of elements can be have an arbitrary integer type;
506 // essentially, we need to multiply it by a constant factor, add a
507 // cookie size, and verify that the result is representable as a
508 // size_t. That's just a gloss, though, and it's wrong in one
509 // important way: if the count is negative, it's an error even if
510 // the cookie size would bring the total size >= 0.
511 bool isSigned = e->getArraySize()->getType()->isSignedIntegerType();
512 const llvm::IntegerType *numElementsType
513 = cast<llvm::IntegerType>(numElements->getType());
514 unsigned numElementsWidth = numElementsType->getBitWidth();
515
516 // Compute the constant factor.
517 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000518 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000519 = CGF.getContext().getAsConstantArrayType(type)) {
520 type = CAT->getElementType();
521 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000522 }
523
John McCall036f2f62011-05-15 07:14:44 +0000524 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
525 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
526 typeSizeMultiplier *= arraySizeMultiplier;
527
528 // This will be a size_t.
529 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000530
Chris Lattner32ac5832010-07-20 21:55:52 +0000531 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
532 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000533 if (llvm::ConstantInt *numElementsC =
534 dyn_cast<llvm::ConstantInt>(numElements)) {
535 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000536
John McCall036f2f62011-05-15 07:14:44 +0000537 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000538
John McCall036f2f62011-05-15 07:14:44 +0000539 // If 'count' was a negative number, it's an overflow.
540 if (isSigned && count.isNegative())
541 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000542
John McCall036f2f62011-05-15 07:14:44 +0000543 // We want to do all this arithmetic in size_t. If numElements is
544 // wider than that, check whether it's already too big, and if so,
545 // overflow.
546 else if (numElementsWidth > sizeWidth &&
547 numElementsWidth - sizeWidth > count.countLeadingZeros())
548 hasAnyOverflow = true;
549
550 // Okay, compute a count at the right width.
551 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
552
553 // Scale numElements by that. This might overflow, but we don't
554 // care because it only overflows if allocationSize does, too, and
555 // if that overflows then we shouldn't use this.
556 numElements = llvm::ConstantInt::get(CGF.SizeTy,
557 adjustedCount * arraySizeMultiplier);
558
559 // Compute the size before cookie, and track whether it overflowed.
560 bool overflow;
561 llvm::APInt allocationSize
562 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
563 hasAnyOverflow |= overflow;
564
565 // Add in the cookie, and check whether it's overflowed.
566 if (cookieSize != 0) {
567 // Save the current size without a cookie. This shouldn't be
568 // used if there was overflow.
569 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
570
571 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
572 hasAnyOverflow |= overflow;
573 }
574
575 // On overflow, produce a -1 so operator new will fail.
576 if (hasAnyOverflow) {
577 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
578 } else {
579 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
580 }
581
582 // Otherwise, we might need to use the overflow intrinsics.
583 } else {
584 // There are up to four conditions we need to test for:
585 // 1) if isSigned, we need to check whether numElements is negative;
586 // 2) if numElementsWidth > sizeWidth, we need to check whether
587 // numElements is larger than something representable in size_t;
588 // 3) we need to compute
589 // sizeWithoutCookie := numElements * typeSizeMultiplier
590 // and check whether it overflows; and
591 // 4) if we need a cookie, we need to compute
592 // size := sizeWithoutCookie + cookieSize
593 // and check whether it overflows.
594
595 llvm::Value *hasOverflow = 0;
596
597 // If numElementsWidth > sizeWidth, then one way or another, we're
598 // going to have to do a comparison for (2), and this happens to
599 // take care of (1), too.
600 if (numElementsWidth > sizeWidth) {
601 llvm::APInt threshold(numElementsWidth, 1);
602 threshold <<= sizeWidth;
603
604 llvm::Value *thresholdV
605 = llvm::ConstantInt::get(numElementsType, threshold);
606
607 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
608 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
609
610 // Otherwise, if we're signed, we want to sext up to size_t.
611 } else if (isSigned) {
612 if (numElementsWidth < sizeWidth)
613 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
614
615 // If there's a non-1 type size multiplier, then we can do the
616 // signedness check at the same time as we do the multiply
617 // because a negative number times anything will cause an
618 // unsigned overflow. Otherwise, we have to do it here.
619 if (typeSizeMultiplier == 1)
620 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
621 llvm::ConstantInt::get(CGF.SizeTy, 0));
622
623 // Otherwise, zext up to size_t if necessary.
624 } else if (numElementsWidth < sizeWidth) {
625 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
626 }
627
628 assert(numElements->getType() == CGF.SizeTy);
629
630 size = numElements;
631
632 // Multiply by the type size if necessary. This multiplier
633 // includes all the factors for nested arrays.
634 //
635 // This step also causes numElements to be scaled up by the
636 // nested-array factor if necessary. Overflow on this computation
637 // can be ignored because the result shouldn't be used if
638 // allocation fails.
639 if (typeSizeMultiplier != 1) {
640 const llvm::Type *intrinsicTypes[] = { CGF.SizeTy };
641 llvm::Value *umul_with_overflow
642 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow,
643 intrinsicTypes, 1);
644
645 llvm::Value *tsmV =
646 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
647 llvm::Value *result =
648 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
649
650 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
651 if (hasOverflow)
652 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
653 else
654 hasOverflow = overflowed;
655
656 size = CGF.Builder.CreateExtractValue(result, 0);
657
658 // Also scale up numElements by the array size multiplier.
659 if (arraySizeMultiplier != 1) {
660 // If the base element type size is 1, then we can re-use the
661 // multiply we just did.
662 if (typeSize.isOne()) {
663 assert(arraySizeMultiplier == typeSizeMultiplier);
664 numElements = size;
665
666 // Otherwise we need a separate multiply.
667 } else {
668 llvm::Value *asmV =
669 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
670 numElements = CGF.Builder.CreateMul(numElements, asmV);
671 }
672 }
673 } else {
674 // numElements doesn't need to be scaled.
675 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000676 }
677
John McCall036f2f62011-05-15 07:14:44 +0000678 // Add in the cookie size if necessary.
679 if (cookieSize != 0) {
680 sizeWithoutCookie = size;
681
682 const llvm::Type *intrinsicTypes[] = { CGF.SizeTy };
683 llvm::Value *uadd_with_overflow
684 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow,
685 intrinsicTypes, 1);
686
687 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
688 llvm::Value *result =
689 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
690
691 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
692 if (hasOverflow)
693 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
694 else
695 hasOverflow = overflowed;
696
697 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000698 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000699
John McCall036f2f62011-05-15 07:14:44 +0000700 // If we had any possibility of dynamic overflow, make a select to
701 // overwrite 'size' with an all-ones value, which should cause
702 // operator new to throw.
703 if (hasOverflow)
704 size = CGF.Builder.CreateSelect(hasOverflow,
705 llvm::Constant::getAllOnesValue(CGF.SizeTy),
706 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000707 }
John McCall8ed55a52010-09-02 09:58:18 +0000708
John McCall036f2f62011-05-15 07:14:44 +0000709 if (cookieSize == 0)
710 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000711 else
John McCall036f2f62011-05-15 07:14:44 +0000712 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000713
John McCall036f2f62011-05-15 07:14:44 +0000714 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000715}
716
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000717static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
718 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000719
720 assert(E->getNumConstructorArgs() == 1 &&
721 "Can only have one argument to initializer of POD type.");
722
723 const Expr *Init = E->getConstructorArg(0);
724 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000725
726 unsigned Alignment =
727 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000728 if (!CGF.hasAggregateLLVMType(AllocType))
729 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000730 AllocType.isVolatileQualified(), Alignment,
731 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000732 else if (AllocType->isAnyComplexType())
733 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
734 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000735 else {
736 AggValueSlot Slot
737 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
738 CGF.EmitAggExpr(Init, Slot);
739 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000740}
741
742void
743CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
744 llvm::Value *NewPtr,
745 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000746 // We have a POD type.
747 if (E->getNumConstructorArgs() == 0)
748 return;
749
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000750 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
751
752 // Create a temporary for the loop index and initialize it with 0.
753 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
754 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
755 Builder.CreateStore(Zero, IndexPtr);
756
757 // Start the loop with a block that tests the condition.
758 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
759 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
760
761 EmitBlock(CondBlock);
762
763 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
764
765 // Generate: if (loop-index < number-of-elements fall to the loop body,
766 // otherwise, go to the block after the for-loop.
767 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
768 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
769 // If the condition is true, execute the body.
770 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
771
772 EmitBlock(ForBody);
773
774 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
775 // Inside the loop body, emit the constructor call on the array element.
776 Counter = Builder.CreateLoad(IndexPtr);
777 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
778 "arrayidx");
779 StoreAnyExprIntoOneUnit(*this, E, Address);
780
781 EmitBlock(ContinueBlock);
782
783 // Emit the increment of the loop counter.
784 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
785 Counter = Builder.CreateLoad(IndexPtr);
786 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
787 Builder.CreateStore(NextVal, IndexPtr);
788
789 // Finally, branch back up to the condition for the next iteration.
790 EmitBranch(CondBlock);
791
792 // Emit the fall-through block.
793 EmitBlock(AfterFor, true);
794}
795
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000796static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
797 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000798 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000799 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000800 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000801 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000802}
803
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000804static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
805 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000806 llvm::Value *NumElements,
807 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000808 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000809 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000810 bool RequiresZeroInitialization = false;
Alexis Huntf479f1b2011-05-09 18:22:59 +0000811 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000812 // If new expression did not specify value-initialization, then there
813 // is no initialization.
814 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
815 return;
816
John McCall614dbdc2010-08-22 21:01:12 +0000817 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000818 // Optimization: since zero initialization will just set the memory
819 // to all zeroes, generate a single memset to do it in one shot.
820 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
821 AllocSizeWithoutCookie);
822 return;
823 }
824
825 RequiresZeroInitialization = true;
826 }
827
828 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
829 E->constructor_arg_begin(),
830 E->constructor_arg_end(),
831 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000832 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000833 } else if (E->getNumConstructorArgs() == 1 &&
834 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
835 // Optimization: since zero initialization will just set the memory
836 // to all zeroes, generate a single memset to do it in one shot.
837 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
838 AllocSizeWithoutCookie);
839 return;
840 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000841 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
842 return;
843 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000844 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000845
846 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000847 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
848 // direct initialization. C++ [dcl.init]p5 requires that we
849 // zero-initialize storage if there are no user-declared constructors.
850 if (E->hasInitializer() &&
851 !Ctor->getParent()->hasUserDeclaredConstructor() &&
852 !Ctor->getParent()->isEmpty())
853 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
854
Douglas Gregore1823702010-07-07 23:37:33 +0000855 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
856 NewPtr, E->constructor_arg_begin(),
857 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000858
859 return;
860 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000861 // We have a POD type.
862 if (E->getNumConstructorArgs() == 0)
863 return;
864
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000865 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000866}
867
John McCall824c2f52010-09-14 07:57:04 +0000868namespace {
869 /// A cleanup to call the given 'operator delete' function upon
870 /// abnormal exit from a new expression.
871 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
872 size_t NumPlacementArgs;
873 const FunctionDecl *OperatorDelete;
874 llvm::Value *Ptr;
875 llvm::Value *AllocSize;
876
877 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
878
879 public:
880 static size_t getExtraSize(size_t NumPlacementArgs) {
881 return NumPlacementArgs * sizeof(RValue);
882 }
883
884 CallDeleteDuringNew(size_t NumPlacementArgs,
885 const FunctionDecl *OperatorDelete,
886 llvm::Value *Ptr,
887 llvm::Value *AllocSize)
888 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
889 Ptr(Ptr), AllocSize(AllocSize) {}
890
891 void setPlacementArg(unsigned I, RValue Arg) {
892 assert(I < NumPlacementArgs && "index out of range");
893 getPlacementArgs()[I] = Arg;
894 }
895
896 void Emit(CodeGenFunction &CGF, bool IsForEH) {
897 const FunctionProtoType *FPT
898 = OperatorDelete->getType()->getAs<FunctionProtoType>();
899 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000900 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000901
902 CallArgList DeleteArgs;
903
904 // The first argument is always a void*.
905 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000906 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000907
908 // A member 'operator delete' can take an extra 'size_t' argument.
909 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000910 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000911
912 // Pass the rest of the arguments, which must match exactly.
913 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000914 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000915
916 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000917 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +0000918 CGF.CGM.GetAddrOfFunction(OperatorDelete),
919 ReturnValueSlot(), DeleteArgs, OperatorDelete);
920 }
921 };
John McCall7f9c92a2010-09-17 00:50:28 +0000922
923 /// A cleanup to call the given 'operator delete' function upon
924 /// abnormal exit from a new expression when the new expression is
925 /// conditional.
926 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
927 size_t NumPlacementArgs;
928 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +0000929 DominatingValue<RValue>::saved_type Ptr;
930 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +0000931
John McCallcb5f77f2011-01-28 10:53:53 +0000932 DominatingValue<RValue>::saved_type *getPlacementArgs() {
933 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +0000934 }
935
936 public:
937 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +0000938 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +0000939 }
940
941 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
942 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +0000943 DominatingValue<RValue>::saved_type Ptr,
944 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +0000945 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
946 Ptr(Ptr), AllocSize(AllocSize) {}
947
John McCallcb5f77f2011-01-28 10:53:53 +0000948 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +0000949 assert(I < NumPlacementArgs && "index out of range");
950 getPlacementArgs()[I] = Arg;
951 }
952
953 void Emit(CodeGenFunction &CGF, bool IsForEH) {
954 const FunctionProtoType *FPT
955 = OperatorDelete->getType()->getAs<FunctionProtoType>();
956 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
957 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
958
959 CallArgList DeleteArgs;
960
961 // The first argument is always a void*.
962 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000963 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000964
965 // A member 'operator delete' can take an extra 'size_t' argument.
966 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +0000967 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +0000968 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000969 }
970
971 // Pass the rest of the arguments, which must match exactly.
972 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +0000973 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +0000974 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000975 }
976
977 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000978 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +0000979 CGF.CGM.GetAddrOfFunction(OperatorDelete),
980 ReturnValueSlot(), DeleteArgs, OperatorDelete);
981 }
982 };
983}
984
985/// Enter a cleanup to call 'operator delete' if the initializer in a
986/// new-expression throws.
987static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
988 const CXXNewExpr *E,
989 llvm::Value *NewPtr,
990 llvm::Value *AllocSize,
991 const CallArgList &NewArgs) {
992 // If we're not inside a conditional branch, then the cleanup will
993 // dominate and we can do the easier (and more efficient) thing.
994 if (!CGF.isInConditionalBranch()) {
995 CallDeleteDuringNew *Cleanup = CGF.EHStack
996 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
997 E->getNumPlacementArgs(),
998 E->getOperatorDelete(),
999 NewPtr, AllocSize);
1000 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001001 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001002
1003 return;
1004 }
1005
1006 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001007 DominatingValue<RValue>::saved_type SavedNewPtr =
1008 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1009 DominatingValue<RValue>::saved_type SavedAllocSize =
1010 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001011
1012 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1013 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
1014 E->getNumPlacementArgs(),
1015 E->getOperatorDelete(),
1016 SavedNewPtr,
1017 SavedAllocSize);
1018 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001019 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001020 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001021
1022 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +00001023}
1024
Anders Carlssoncc52f652009-09-22 22:53:17 +00001025llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001026 // The element type being allocated.
1027 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001028
John McCall75f94982011-03-07 03:12:35 +00001029 // 1. Build a call to the allocation function.
1030 FunctionDecl *allocator = E->getOperatorNew();
1031 const FunctionProtoType *allocatorType =
1032 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001033
John McCall75f94982011-03-07 03:12:35 +00001034 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001035
1036 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001037 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001038
John McCall75f94982011-03-07 03:12:35 +00001039 llvm::Value *numElements = 0;
1040 llvm::Value *allocSizeWithoutCookie = 0;
1041 llvm::Value *allocSize =
John McCall036f2f62011-05-15 07:14:44 +00001042 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001043
Eli Friedman43dca6a2011-05-02 17:57:46 +00001044 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001045
1046 // Emit the rest of the arguments.
1047 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001048 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001049
1050 // First, use the types from the function type.
1051 // We start at 1 here because the first argument (the allocation size)
1052 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001053 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1054 ++i, ++placementArg) {
1055 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001056
John McCall75f94982011-03-07 03:12:35 +00001057 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1058 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001059 "type mismatch in call argument!");
1060
John McCall32ea9692011-03-11 20:59:21 +00001061 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001062 }
1063
1064 // Either we've emitted all the call args, or we have a call to a
1065 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001066 assert((placementArg == E->placement_arg_end() ||
1067 allocatorType->isVariadic()) &&
1068 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001069
1070 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001071 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1072 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001073 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001074 }
1075
John McCall75f94982011-03-07 03:12:35 +00001076 // Emit the allocation call.
Anders Carlssoncc52f652009-09-22 22:53:17 +00001077 RValue RV =
John McCall75f94982011-03-07 03:12:35 +00001078 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1079 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1080 allocatorArgs, allocator);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001081
John McCall75f94982011-03-07 03:12:35 +00001082 // Emit a null check on the allocation result if the allocation
1083 // function is allowed to return null (because it has a non-throwing
1084 // exception spec; for this part, we inline
1085 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1086 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001087 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCall75f94982011-03-07 03:12:35 +00001088 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001089
John McCall75f94982011-03-07 03:12:35 +00001090 llvm::BasicBlock *nullCheckBB = 0;
1091 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001092
John McCall75f94982011-03-07 03:12:35 +00001093 llvm::Value *allocation = RV.getScalarVal();
1094 unsigned AS =
1095 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001096
John McCallf7dcf322011-03-07 01:52:56 +00001097 // The null-check means that the initializer is conditionally
1098 // evaluated.
1099 ConditionalEvaluation conditional(*this);
1100
John McCall75f94982011-03-07 03:12:35 +00001101 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001102 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001103
1104 nullCheckBB = Builder.GetInsertBlock();
1105 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1106 contBB = createBasicBlock("new.cont");
1107
1108 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1109 Builder.CreateCondBr(isNull, contBB, notNullBB);
1110 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001111 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001112
John McCall75f94982011-03-07 03:12:35 +00001113 assert((allocSize == allocSizeWithoutCookie) ==
John McCall8ed55a52010-09-02 09:58:18 +00001114 CalculateCookiePadding(*this, E).isZero());
John McCall75f94982011-03-07 03:12:35 +00001115 if (allocSize != allocSizeWithoutCookie) {
John McCall8ed55a52010-09-02 09:58:18 +00001116 assert(E->isArray());
John McCall75f94982011-03-07 03:12:35 +00001117 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1118 numElements,
1119 E, allocType);
John McCall8ed55a52010-09-02 09:58:18 +00001120 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001121
John McCall824c2f52010-09-14 07:57:04 +00001122 // If there's an operator delete, enter a cleanup to call it if an
1123 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001124 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall824c2f52010-09-14 07:57:04 +00001125 if (E->getOperatorDelete()) {
John McCall75f94982011-03-07 03:12:35 +00001126 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1127 operatorDeleteCleanup = EHStack.stable_begin();
John McCall824c2f52010-09-14 07:57:04 +00001128 }
1129
John McCall75f94982011-03-07 03:12:35 +00001130 const llvm::Type *elementPtrTy
1131 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1132 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001133
John McCall8ed55a52010-09-02 09:58:18 +00001134 if (E->isArray()) {
John McCall75f94982011-03-07 03:12:35 +00001135 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001136
1137 // NewPtr is a pointer to the base element type. If we're
1138 // allocating an array of arrays, we'll need to cast back to the
1139 // array pointer type.
John McCall75f94982011-03-07 03:12:35 +00001140 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1141 if (result->getType() != resultType)
1142 result = Builder.CreateBitCast(result, resultType);
John McCall8ed55a52010-09-02 09:58:18 +00001143 } else {
John McCall75f94982011-03-07 03:12:35 +00001144 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001145 }
John McCall824c2f52010-09-14 07:57:04 +00001146
1147 // Deactivate the 'operator delete' cleanup if we finished
1148 // initialization.
John McCall75f94982011-03-07 03:12:35 +00001149 if (operatorDeleteCleanup.isValid())
1150 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001151
John McCall75f94982011-03-07 03:12:35 +00001152 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001153 conditional.end(*this);
1154
John McCall75f94982011-03-07 03:12:35 +00001155 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1156 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001157
Jay Foad20c0f022011-03-30 11:28:58 +00001158 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001159 PHI->addIncoming(result, notNullBB);
1160 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1161 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001162
John McCall75f94982011-03-07 03:12:35 +00001163 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001164 }
John McCall8ed55a52010-09-02 09:58:18 +00001165
John McCall75f94982011-03-07 03:12:35 +00001166 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001167}
1168
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001169void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1170 llvm::Value *Ptr,
1171 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001172 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1173
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001174 const FunctionProtoType *DeleteFTy =
1175 DeleteFD->getType()->getAs<FunctionProtoType>();
1176
1177 CallArgList DeleteArgs;
1178
Anders Carlsson21122cf2009-12-13 20:04:38 +00001179 // Check if we need to pass the size to the delete operator.
1180 llvm::Value *Size = 0;
1181 QualType SizeTy;
1182 if (DeleteFTy->getNumArgs() == 2) {
1183 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001184 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1185 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1186 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001187 }
1188
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001189 QualType ArgTy = DeleteFTy->getArgType(0);
1190 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001191 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001192
Anders Carlsson21122cf2009-12-13 20:04:38 +00001193 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001194 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001195
1196 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001197 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001198 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001199 DeleteArgs, DeleteFD);
1200}
1201
John McCall8ed55a52010-09-02 09:58:18 +00001202namespace {
1203 /// Calls the given 'operator delete' on a single object.
1204 struct CallObjectDelete : EHScopeStack::Cleanup {
1205 llvm::Value *Ptr;
1206 const FunctionDecl *OperatorDelete;
1207 QualType ElementType;
1208
1209 CallObjectDelete(llvm::Value *Ptr,
1210 const FunctionDecl *OperatorDelete,
1211 QualType ElementType)
1212 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1213
1214 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1215 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1216 }
1217 };
1218}
1219
1220/// Emit the code for deleting a single object.
1221static void EmitObjectDelete(CodeGenFunction &CGF,
1222 const FunctionDecl *OperatorDelete,
1223 llvm::Value *Ptr,
1224 QualType ElementType) {
1225 // Find the destructor for the type, if applicable. If the
1226 // destructor is virtual, we'll just emit the vcall and return.
1227 const CXXDestructorDecl *Dtor = 0;
1228 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1229 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1230 if (!RD->hasTrivialDestructor()) {
1231 Dtor = RD->getDestructor();
1232
1233 if (Dtor->isVirtual()) {
1234 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001235 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1236 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001237 /*isVariadic=*/false);
1238
1239 llvm::Value *Callee
1240 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1241 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1242 0, 0);
1243
1244 // The dtor took care of deleting the object.
1245 return;
1246 }
1247 }
1248 }
1249
1250 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001251 // This doesn't have to a conditional cleanup because we're going
1252 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001253 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1254 Ptr, OperatorDelete, ElementType);
1255
1256 if (Dtor)
1257 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1258 /*ForVirtualBase=*/false, Ptr);
1259
1260 CGF.PopCleanupBlock();
1261}
1262
1263namespace {
1264 /// Calls the given 'operator delete' on an array of objects.
1265 struct CallArrayDelete : EHScopeStack::Cleanup {
1266 llvm::Value *Ptr;
1267 const FunctionDecl *OperatorDelete;
1268 llvm::Value *NumElements;
1269 QualType ElementType;
1270 CharUnits CookieSize;
1271
1272 CallArrayDelete(llvm::Value *Ptr,
1273 const FunctionDecl *OperatorDelete,
1274 llvm::Value *NumElements,
1275 QualType ElementType,
1276 CharUnits CookieSize)
1277 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1278 ElementType(ElementType), CookieSize(CookieSize) {}
1279
1280 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1281 const FunctionProtoType *DeleteFTy =
1282 OperatorDelete->getType()->getAs<FunctionProtoType>();
1283 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1284
1285 CallArgList Args;
1286
1287 // Pass the pointer as the first argument.
1288 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1289 llvm::Value *DeletePtr
1290 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001291 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001292
1293 // Pass the original requested size as the second argument.
1294 if (DeleteFTy->getNumArgs() == 2) {
1295 QualType size_t = DeleteFTy->getArgType(1);
1296 const llvm::IntegerType *SizeTy
1297 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1298
1299 CharUnits ElementTypeSize =
1300 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1301
1302 // The size of an element, multiplied by the number of elements.
1303 llvm::Value *Size
1304 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1305 Size = CGF.Builder.CreateMul(Size, NumElements);
1306
1307 // Plus the size of the cookie if applicable.
1308 if (!CookieSize.isZero()) {
1309 llvm::Value *CookieSizeV
1310 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1311 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1312 }
1313
Eli Friedman43dca6a2011-05-02 17:57:46 +00001314 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001315 }
1316
1317 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001318 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001319 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1320 ReturnValueSlot(), Args, OperatorDelete);
1321 }
1322 };
1323}
1324
1325/// Emit the code for deleting an array of objects.
1326static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001327 const CXXDeleteExpr *E,
John McCall8ed55a52010-09-02 09:58:18 +00001328 llvm::Value *Ptr,
1329 QualType ElementType) {
1330 llvm::Value *NumElements = 0;
1331 llvm::Value *AllocatedPtr = 0;
1332 CharUnits CookieSize;
John McCall284c48f2011-01-27 09:37:56 +00001333 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall8ed55a52010-09-02 09:58:18 +00001334 NumElements, AllocatedPtr, CookieSize);
1335
1336 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1337
1338 // Make sure that we call delete even if one of the dtors throws.
John McCall284c48f2011-01-27 09:37:56 +00001339 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001340 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1341 AllocatedPtr, OperatorDelete,
1342 NumElements, ElementType,
1343 CookieSize);
1344
1345 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1346 if (!RD->hasTrivialDestructor()) {
1347 assert(NumElements && "ReadArrayCookie didn't find element count"
1348 " for a class with destructor");
1349 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1350 }
1351 }
1352
1353 CGF.PopCleanupBlock();
1354}
1355
Anders Carlssoncc52f652009-09-22 22:53:17 +00001356void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001357
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001358 // Get at the argument before we performed the implicit conversion
1359 // to void*.
1360 const Expr *Arg = E->getArgument();
1361 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001362 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001363 ICE->getType()->isVoidPointerType())
1364 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001365 else
1366 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001367 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001368
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001369 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001370
1371 // Null check the pointer.
1372 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1373 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1374
Anders Carlsson98981b12011-04-11 00:30:07 +00001375 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001376
1377 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1378 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001379
John McCall8ed55a52010-09-02 09:58:18 +00001380 // We might be deleting a pointer to array. If so, GEP down to the
1381 // first non-array element.
1382 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1383 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1384 if (DeleteTy->isConstantArrayType()) {
1385 llvm::Value *Zero = Builder.getInt32(0);
1386 llvm::SmallVector<llvm::Value*,8> GEP;
1387
1388 GEP.push_back(Zero); // point at the outermost array
1389
1390 // For each layer of array type we're pointing at:
1391 while (const ConstantArrayType *Arr
1392 = getContext().getAsConstantArrayType(DeleteTy)) {
1393 // 1. Unpeel the array type.
1394 DeleteTy = Arr->getElementType();
1395
1396 // 2. GEP to the first element of the array.
1397 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001398 }
John McCall8ed55a52010-09-02 09:58:18 +00001399
1400 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001401 }
1402
Douglas Gregor04f36212010-09-02 17:38:50 +00001403 assert(ConvertTypeForMem(DeleteTy) ==
1404 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001405
1406 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001407 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001408 } else {
1409 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1410 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001411
Anders Carlssoncc52f652009-09-22 22:53:17 +00001412 EmitBlock(DeleteEnd);
1413}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001414
Anders Carlsson0c633502011-04-11 14:13:40 +00001415static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1416 // void __cxa_bad_typeid();
1417
1418 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1419 const llvm::FunctionType *FTy =
1420 llvm::FunctionType::get(VoidTy, false);
1421
1422 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1423}
1424
1425static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001426 llvm::Value *Fn = getBadTypeidFn(CGF);
1427 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001428 CGF.Builder.CreateUnreachable();
1429}
1430
Anders Carlsson940f02d2011-04-18 00:57:03 +00001431static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1432 const Expr *E,
1433 const llvm::Type *StdTypeInfoPtrTy) {
1434 // Get the vtable pointer.
1435 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1436
1437 // C++ [expr.typeid]p2:
1438 // If the glvalue expression is obtained by applying the unary * operator to
1439 // a pointer and the pointer is a null pointer value, the typeid expression
1440 // throws the std::bad_typeid exception.
1441 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1442 if (UO->getOpcode() == UO_Deref) {
1443 llvm::BasicBlock *BadTypeidBlock =
1444 CGF.createBasicBlock("typeid.bad_typeid");
1445 llvm::BasicBlock *EndBlock =
1446 CGF.createBasicBlock("typeid.end");
1447
1448 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1449 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1450
1451 CGF.EmitBlock(BadTypeidBlock);
1452 EmitBadTypeidCall(CGF);
1453 CGF.EmitBlock(EndBlock);
1454 }
1455 }
1456
1457 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1458 StdTypeInfoPtrTy->getPointerTo());
1459
1460 // Load the type info.
1461 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1462 return CGF.Builder.CreateLoad(Value);
1463}
1464
John McCalle4df6c82011-01-28 08:37:24 +00001465llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001466 const llvm::Type *StdTypeInfoPtrTy =
1467 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001468
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001469 if (E->isTypeOperand()) {
1470 llvm::Constant *TypeInfo =
1471 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001472 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001473 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001474
Anders Carlsson940f02d2011-04-18 00:57:03 +00001475 // C++ [expr.typeid]p2:
1476 // When typeid is applied to a glvalue expression whose type is a
1477 // polymorphic class type, the result refers to a std::type_info object
1478 // representing the type of the most derived object (that is, the dynamic
1479 // type) to which the glvalue refers.
1480 if (E->getExprOperand()->isGLValue()) {
1481 if (const RecordType *RT =
1482 E->getExprOperand()->getType()->getAs<RecordType>()) {
1483 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1484 if (RD->isPolymorphic())
1485 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1486 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001487 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001488 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001489
1490 QualType OperandTy = E->getExprOperand()->getType();
1491 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1492 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001493}
Mike Stump65511702009-11-16 06:50:58 +00001494
Anders Carlsson882d7902011-04-11 00:46:40 +00001495static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1496 // void *__dynamic_cast(const void *sub,
1497 // const abi::__class_type_info *src,
1498 // const abi::__class_type_info *dst,
1499 // std::ptrdiff_t src2dst_offset);
1500
1501 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1502 const llvm::Type *PtrDiffTy =
1503 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1504
1505 const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1506
1507 const llvm::FunctionType *FTy =
1508 llvm::FunctionType::get(Int8PtrTy, Args, false);
1509
1510 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1511}
1512
1513static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1514 // void __cxa_bad_cast();
1515
1516 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1517 const llvm::FunctionType *FTy =
1518 llvm::FunctionType::get(VoidTy, false);
1519
1520 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1521}
1522
Anders Carlssonc1c99712011-04-11 01:45:29 +00001523static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001524 llvm::Value *Fn = getBadCastFn(CGF);
1525 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001526 CGF.Builder.CreateUnreachable();
1527}
1528
Anders Carlsson882d7902011-04-11 00:46:40 +00001529static llvm::Value *
1530EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1531 QualType SrcTy, QualType DestTy,
1532 llvm::BasicBlock *CastEnd) {
1533 const llvm::Type *PtrDiffLTy =
1534 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1535 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1536
1537 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1538 if (PTy->getPointeeType()->isVoidType()) {
1539 // C++ [expr.dynamic.cast]p7:
1540 // If T is "pointer to cv void," then the result is a pointer to the
1541 // most derived object pointed to by v.
1542
1543 // Get the vtable pointer.
1544 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1545
1546 // Get the offset-to-top from the vtable.
1547 llvm::Value *OffsetToTop =
1548 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1549 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1550
1551 // Finally, add the offset to the pointer.
1552 Value = CGF.EmitCastToVoidPtr(Value);
1553 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1554
1555 return CGF.Builder.CreateBitCast(Value, DestLTy);
1556 }
1557 }
1558
1559 QualType SrcRecordTy;
1560 QualType DestRecordTy;
1561
1562 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1563 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1564 DestRecordTy = DestPTy->getPointeeType();
1565 } else {
1566 SrcRecordTy = SrcTy;
1567 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1568 }
1569
1570 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1571 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1572
1573 llvm::Value *SrcRTTI =
1574 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1575 llvm::Value *DestRTTI =
1576 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1577
1578 // FIXME: Actually compute a hint here.
1579 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1580
1581 // Emit the call to __dynamic_cast.
1582 Value = CGF.EmitCastToVoidPtr(Value);
1583 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1584 SrcRTTI, DestRTTI, OffsetHint);
1585 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1586
1587 /// C++ [expr.dynamic.cast]p9:
1588 /// A failed cast to reference type throws std::bad_cast
1589 if (DestTy->isReferenceType()) {
1590 llvm::BasicBlock *BadCastBlock =
1591 CGF.createBasicBlock("dynamic_cast.bad_cast");
1592
1593 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1594 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1595
1596 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001597 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001598 }
1599
1600 return Value;
1601}
1602
Anders Carlssonc1c99712011-04-11 01:45:29 +00001603static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1604 QualType DestTy) {
1605 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1606 if (DestTy->isPointerType())
1607 return llvm::Constant::getNullValue(DestLTy);
1608
1609 /// C++ [expr.dynamic.cast]p9:
1610 /// A failed cast to reference type throws std::bad_cast
1611 EmitBadCastCall(CGF);
1612
1613 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1614 return llvm::UndefValue::get(DestLTy);
1615}
1616
Anders Carlsson882d7902011-04-11 00:46:40 +00001617llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001618 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001619 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001620
Anders Carlssonc1c99712011-04-11 01:45:29 +00001621 if (DCE->isAlwaysNull())
1622 return EmitDynamicCastToNull(*this, DestTy);
1623
1624 QualType SrcTy = DCE->getSubExpr()->getType();
1625
Anders Carlsson882d7902011-04-11 00:46:40 +00001626 // C++ [expr.dynamic.cast]p4:
1627 // If the value of v is a null pointer value in the pointer case, the result
1628 // is the null pointer value of type T.
1629 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001630
Anders Carlsson882d7902011-04-11 00:46:40 +00001631 llvm::BasicBlock *CastNull = 0;
1632 llvm::BasicBlock *CastNotNull = 0;
1633 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001634
Anders Carlsson882d7902011-04-11 00:46:40 +00001635 if (ShouldNullCheckSrcValue) {
1636 CastNull = createBasicBlock("dynamic_cast.null");
1637 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1638
1639 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1640 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1641 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001642 }
1643
Anders Carlsson882d7902011-04-11 00:46:40 +00001644 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1645
1646 if (ShouldNullCheckSrcValue) {
1647 EmitBranch(CastEnd);
1648
1649 EmitBlock(CastNull);
1650 EmitBranch(CastEnd);
1651 }
1652
1653 EmitBlock(CastEnd);
1654
1655 if (ShouldNullCheckSrcValue) {
1656 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1657 PHI->addIncoming(Value, CastNotNull);
1658 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1659
1660 Value = PHI;
1661 }
1662
1663 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001664}