blob: 49aab66268c01112c446e64d124e2da5c41b14eb [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
John McCallf677a8e2011-07-13 06:10:41 +0000382 if (const ConstantArrayType *arrayType
383 = getContext().getAsConstantArrayType(E->getType())) {
384 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000385 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000386 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000387 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000388 bool ForVirtualBase = false;
389
390 switch (E->getConstructionKind()) {
391 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000392 // We should be emitting a constructor; GlobalDecl will assert this
393 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000394 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000395
Alexis Hunt271c3682011-05-03 20:19:28 +0000396 case CXXConstructExpr::CK_Complete:
397 Type = Ctor_Complete;
398 break;
399
400 case CXXConstructExpr::CK_VirtualBase:
401 ForVirtualBase = true;
402 // fall-through
403
404 case CXXConstructExpr::CK_NonVirtualBase:
405 Type = Ctor_Base;
406 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000407
Anders Carlsson27da15b2010-01-01 20:29:01 +0000408 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000409 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000410 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000411 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000412}
413
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000414void
415CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
416 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000417 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000418 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000419 Exp = E->getSubExpr();
420 assert(isa<CXXConstructExpr>(Exp) &&
421 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
422 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
423 const CXXConstructorDecl *CD = E->getConstructor();
424 RunCleanupsScope Scope(*this);
425
426 // If we require zero initialization before (or instead of) calling the
427 // constructor, as can be the case with a non-user-provided default
428 // constructor, emit the zero initialization now.
429 // FIXME. Do I still need this for a copy ctor synthesis?
430 if (E->requiresZeroInitialization())
431 EmitNullInitialization(Dest, E->getType());
432
Chandler Carruth99da11c2010-11-15 13:54:43 +0000433 assert(!getContext().getAsConstantArrayType(E->getType())
434 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000435 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
436 E->arg_begin(), E->arg_end());
437}
438
John McCall8ed55a52010-09-02 09:58:18 +0000439static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
440 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000441 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000442 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000443
John McCall7ec4b432011-05-16 01:05:12 +0000444 // No cookie is required if the operator new[] being used is the
445 // reserved placement operator new[].
446 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000447 return CharUnits::Zero();
448
John McCall284c48f2011-01-27 09:37:56 +0000449 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000450}
451
John McCall036f2f62011-05-15 07:14:44 +0000452static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
453 const CXXNewExpr *e,
454 llvm::Value *&numElements,
455 llvm::Value *&sizeWithoutCookie) {
456 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000457
John McCall036f2f62011-05-15 07:14:44 +0000458 if (!e->isArray()) {
459 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
460 sizeWithoutCookie
461 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
462 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000463 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000464
John McCall036f2f62011-05-15 07:14:44 +0000465 // The width of size_t.
466 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
467
John McCall8ed55a52010-09-02 09:58:18 +0000468 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000469 llvm::APInt cookieSize(sizeWidth,
470 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000471
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000472 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000473 // We multiply the size of all dimensions for NumElements.
474 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000475 numElements = CGF.EmitScalarExpr(e->getArraySize());
476 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000477
John McCall036f2f62011-05-15 07:14:44 +0000478 // The number of elements can be have an arbitrary integer type;
479 // essentially, we need to multiply it by a constant factor, add a
480 // cookie size, and verify that the result is representable as a
481 // size_t. That's just a gloss, though, and it's wrong in one
482 // important way: if the count is negative, it's an error even if
483 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000484 bool isSigned
485 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
John McCall036f2f62011-05-15 07:14:44 +0000486 const llvm::IntegerType *numElementsType
487 = cast<llvm::IntegerType>(numElements->getType());
488 unsigned numElementsWidth = numElementsType->getBitWidth();
489
490 // Compute the constant factor.
491 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000492 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000493 = CGF.getContext().getAsConstantArrayType(type)) {
494 type = CAT->getElementType();
495 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000496 }
497
John McCall036f2f62011-05-15 07:14:44 +0000498 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
499 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
500 typeSizeMultiplier *= arraySizeMultiplier;
501
502 // This will be a size_t.
503 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000504
Chris Lattner32ac5832010-07-20 21:55:52 +0000505 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
506 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000507 if (llvm::ConstantInt *numElementsC =
508 dyn_cast<llvm::ConstantInt>(numElements)) {
509 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000510
John McCall036f2f62011-05-15 07:14:44 +0000511 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000512
John McCall036f2f62011-05-15 07:14:44 +0000513 // If 'count' was a negative number, it's an overflow.
514 if (isSigned && count.isNegative())
515 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000516
John McCall036f2f62011-05-15 07:14:44 +0000517 // We want to do all this arithmetic in size_t. If numElements is
518 // wider than that, check whether it's already too big, and if so,
519 // overflow.
520 else if (numElementsWidth > sizeWidth &&
521 numElementsWidth - sizeWidth > count.countLeadingZeros())
522 hasAnyOverflow = true;
523
524 // Okay, compute a count at the right width.
525 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
526
527 // Scale numElements by that. This might overflow, but we don't
528 // care because it only overflows if allocationSize does, too, and
529 // if that overflows then we shouldn't use this.
530 numElements = llvm::ConstantInt::get(CGF.SizeTy,
531 adjustedCount * arraySizeMultiplier);
532
533 // Compute the size before cookie, and track whether it overflowed.
534 bool overflow;
535 llvm::APInt allocationSize
536 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
537 hasAnyOverflow |= overflow;
538
539 // Add in the cookie, and check whether it's overflowed.
540 if (cookieSize != 0) {
541 // Save the current size without a cookie. This shouldn't be
542 // used if there was overflow.
543 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
544
545 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
546 hasAnyOverflow |= overflow;
547 }
548
549 // On overflow, produce a -1 so operator new will fail.
550 if (hasAnyOverflow) {
551 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
552 } else {
553 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
554 }
555
556 // Otherwise, we might need to use the overflow intrinsics.
557 } else {
558 // There are up to four conditions we need to test for:
559 // 1) if isSigned, we need to check whether numElements is negative;
560 // 2) if numElementsWidth > sizeWidth, we need to check whether
561 // numElements is larger than something representable in size_t;
562 // 3) we need to compute
563 // sizeWithoutCookie := numElements * typeSizeMultiplier
564 // and check whether it overflows; and
565 // 4) if we need a cookie, we need to compute
566 // size := sizeWithoutCookie + cookieSize
567 // and check whether it overflows.
568
569 llvm::Value *hasOverflow = 0;
570
571 // If numElementsWidth > sizeWidth, then one way or another, we're
572 // going to have to do a comparison for (2), and this happens to
573 // take care of (1), too.
574 if (numElementsWidth > sizeWidth) {
575 llvm::APInt threshold(numElementsWidth, 1);
576 threshold <<= sizeWidth;
577
578 llvm::Value *thresholdV
579 = llvm::ConstantInt::get(numElementsType, threshold);
580
581 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
582 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
583
584 // Otherwise, if we're signed, we want to sext up to size_t.
585 } else if (isSigned) {
586 if (numElementsWidth < sizeWidth)
587 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
588
589 // If there's a non-1 type size multiplier, then we can do the
590 // signedness check at the same time as we do the multiply
591 // because a negative number times anything will cause an
592 // unsigned overflow. Otherwise, we have to do it here.
593 if (typeSizeMultiplier == 1)
594 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
595 llvm::ConstantInt::get(CGF.SizeTy, 0));
596
597 // Otherwise, zext up to size_t if necessary.
598 } else if (numElementsWidth < sizeWidth) {
599 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
600 }
601
602 assert(numElements->getType() == CGF.SizeTy);
603
604 size = numElements;
605
606 // Multiply by the type size if necessary. This multiplier
607 // includes all the factors for nested arrays.
608 //
609 // This step also causes numElements to be scaled up by the
610 // nested-array factor if necessary. Overflow on this computation
611 // can be ignored because the result shouldn't be used if
612 // allocation fails.
613 if (typeSizeMultiplier != 1) {
Chris Lattnera5f58b02011-07-09 17:41:47 +0000614 llvm::Type *intrinsicTypes[] = { CGF.SizeTy };
John McCall036f2f62011-05-15 07:14:44 +0000615 llvm::Value *umul_with_overflow
616 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow,
617 intrinsicTypes, 1);
618
619 llvm::Value *tsmV =
620 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
621 llvm::Value *result =
622 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
623
624 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
625 if (hasOverflow)
626 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
627 else
628 hasOverflow = overflowed;
629
630 size = CGF.Builder.CreateExtractValue(result, 0);
631
632 // Also scale up numElements by the array size multiplier.
633 if (arraySizeMultiplier != 1) {
634 // If the base element type size is 1, then we can re-use the
635 // multiply we just did.
636 if (typeSize.isOne()) {
637 assert(arraySizeMultiplier == typeSizeMultiplier);
638 numElements = size;
639
640 // Otherwise we need a separate multiply.
641 } else {
642 llvm::Value *asmV =
643 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
644 numElements = CGF.Builder.CreateMul(numElements, asmV);
645 }
646 }
647 } else {
648 // numElements doesn't need to be scaled.
649 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000650 }
651
John McCall036f2f62011-05-15 07:14:44 +0000652 // Add in the cookie size if necessary.
653 if (cookieSize != 0) {
654 sizeWithoutCookie = size;
655
Chris Lattnera5f58b02011-07-09 17:41:47 +0000656 llvm::Type *intrinsicTypes[] = { CGF.SizeTy };
John McCall036f2f62011-05-15 07:14:44 +0000657 llvm::Value *uadd_with_overflow
658 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow,
659 intrinsicTypes, 1);
660
661 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
662 llvm::Value *result =
663 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
664
665 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
666 if (hasOverflow)
667 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
668 else
669 hasOverflow = overflowed;
670
671 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000672 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000673
John McCall036f2f62011-05-15 07:14:44 +0000674 // If we had any possibility of dynamic overflow, make a select to
675 // overwrite 'size' with an all-ones value, which should cause
676 // operator new to throw.
677 if (hasOverflow)
678 size = CGF.Builder.CreateSelect(hasOverflow,
679 llvm::Constant::getAllOnesValue(CGF.SizeTy),
680 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000681 }
John McCall8ed55a52010-09-02 09:58:18 +0000682
John McCall036f2f62011-05-15 07:14:44 +0000683 if (cookieSize == 0)
684 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000685 else
John McCall036f2f62011-05-15 07:14:44 +0000686 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000687
John McCall036f2f62011-05-15 07:14:44 +0000688 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000689}
690
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000691static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
692 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000693
694 assert(E->getNumConstructorArgs() == 1 &&
695 "Can only have one argument to initializer of POD type.");
696
697 const Expr *Init = E->getConstructorArg(0);
698 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000699
700 unsigned Alignment =
701 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
John McCall1553b192011-06-16 04:16:24 +0000702 if (!CGF.hasAggregateLLVMType(AllocType))
703 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, Alignment),
704 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000705 else if (AllocType->isAnyComplexType())
706 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
707 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000708 else {
709 AggValueSlot Slot
John McCall31168b02011-06-15 23:02:42 +0000710 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), true);
John McCall7a626f62010-09-15 10:14:12 +0000711 CGF.EmitAggExpr(Init, Slot);
712 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000713}
714
715void
716CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
717 llvm::Value *NewPtr,
718 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000719 // We have a POD type.
720 if (E->getNumConstructorArgs() == 0)
721 return;
722
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000723 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
724
725 // Create a temporary for the loop index and initialize it with 0.
726 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
727 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
728 Builder.CreateStore(Zero, IndexPtr);
729
730 // Start the loop with a block that tests the condition.
731 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
732 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
733
734 EmitBlock(CondBlock);
735
736 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
737
738 // Generate: if (loop-index < number-of-elements fall to the loop body,
739 // otherwise, go to the block after the for-loop.
740 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
741 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
742 // If the condition is true, execute the body.
743 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
744
745 EmitBlock(ForBody);
746
747 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
748 // Inside the loop body, emit the constructor call on the array element.
749 Counter = Builder.CreateLoad(IndexPtr);
750 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
751 "arrayidx");
752 StoreAnyExprIntoOneUnit(*this, E, Address);
753
754 EmitBlock(ContinueBlock);
755
756 // Emit the increment of the loop counter.
757 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
758 Counter = Builder.CreateLoad(IndexPtr);
759 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
760 Builder.CreateStore(NextVal, IndexPtr);
761
762 // Finally, branch back up to the condition for the next iteration.
763 EmitBranch(CondBlock);
764
765 // Emit the fall-through block.
766 EmitBlock(AfterFor, true);
767}
768
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000769static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
770 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000771 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000772 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000773 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000774 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000775}
776
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000777static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
778 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000779 llvm::Value *NumElements,
780 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000781 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000782 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000783 bool RequiresZeroInitialization = false;
Alexis Huntf479f1b2011-05-09 18:22:59 +0000784 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000785 // If new expression did not specify value-initialization, then there
786 // is no initialization.
787 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
788 return;
789
John McCall614dbdc2010-08-22 21:01:12 +0000790 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000791 // Optimization: since zero initialization will just set the memory
792 // to all zeroes, generate a single memset to do it in one shot.
793 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
794 AllocSizeWithoutCookie);
795 return;
796 }
797
798 RequiresZeroInitialization = true;
799 }
John McCallf677a8e2011-07-13 06:10:41 +0000800
801 // It's legal for NumElements to be zero, but
802 // EmitCXXAggrConstructorCall doesn't handle that, so we need to.
803 llvm::BranchInst *br = 0;
804
805 // Optimize for a constant count.
806 llvm::ConstantInt *constantCount
807 = dyn_cast<llvm::ConstantInt>(NumElements);
808 if (constantCount) {
809 // Just skip out if the constant count is zero.
810 if (constantCount->isZero()) return;
811
812 // Otherwise, emit the check.
813 } else {
814 llvm::BasicBlock *loopBB = CGF.createBasicBlock("new.ctorloop");
815 llvm::Value *iszero = CGF.Builder.CreateIsNull(NumElements, "isempty");
816 br = CGF.Builder.CreateCondBr(iszero, loopBB, loopBB);
817 CGF.EmitBlock(loopBB);
818 }
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000819
820 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
821 E->constructor_arg_begin(),
822 E->constructor_arg_end(),
823 RequiresZeroInitialization);
John McCallf677a8e2011-07-13 06:10:41 +0000824
825 // Patch the earlier check to skip over the loop.
826 if (br) {
827 assert(CGF.Builder.GetInsertBlock()->empty());
828 br->setSuccessor(0, CGF.Builder.GetInsertBlock());
829 }
830
Anders Carlssond040e6b2010-05-03 15:09:17 +0000831 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000832 } else if (E->getNumConstructorArgs() == 1 &&
833 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
834 // Optimization: since zero initialization will just set the memory
835 // to all zeroes, generate a single memset to do it in one shot.
836 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
837 AllocSizeWithoutCookie);
838 return;
839 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000840 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
841 return;
842 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000843 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000844
845 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000846 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
847 // direct initialization. C++ [dcl.init]p5 requires that we
848 // zero-initialize storage if there are no user-declared constructors.
849 if (E->hasInitializer() &&
850 !Ctor->getParent()->hasUserDeclaredConstructor() &&
851 !Ctor->getParent()->isEmpty())
852 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
853
Douglas Gregore1823702010-07-07 23:37:33 +0000854 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
855 NewPtr, E->constructor_arg_begin(),
856 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000857
858 return;
859 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000860 // We have a POD type.
861 if (E->getNumConstructorArgs() == 0)
862 return;
863
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000864 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000865}
866
John McCall824c2f52010-09-14 07:57:04 +0000867namespace {
868 /// A cleanup to call the given 'operator delete' function upon
869 /// abnormal exit from a new expression.
870 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
871 size_t NumPlacementArgs;
872 const FunctionDecl *OperatorDelete;
873 llvm::Value *Ptr;
874 llvm::Value *AllocSize;
875
876 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
877
878 public:
879 static size_t getExtraSize(size_t NumPlacementArgs) {
880 return NumPlacementArgs * sizeof(RValue);
881 }
882
883 CallDeleteDuringNew(size_t NumPlacementArgs,
884 const FunctionDecl *OperatorDelete,
885 llvm::Value *Ptr,
886 llvm::Value *AllocSize)
887 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
888 Ptr(Ptr), AllocSize(AllocSize) {}
889
890 void setPlacementArg(unsigned I, RValue Arg) {
891 assert(I < NumPlacementArgs && "index out of range");
892 getPlacementArgs()[I] = Arg;
893 }
894
John McCall30317fd2011-07-12 20:27:29 +0000895 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +0000896 const FunctionProtoType *FPT
897 = OperatorDelete->getType()->getAs<FunctionProtoType>();
898 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000899 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000900
901 CallArgList DeleteArgs;
902
903 // The first argument is always a void*.
904 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000905 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000906
907 // A member 'operator delete' can take an extra 'size_t' argument.
908 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000909 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000910
911 // Pass the rest of the arguments, which must match exactly.
912 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000913 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000914
915 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000916 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +0000917 CGF.CGM.GetAddrOfFunction(OperatorDelete),
918 ReturnValueSlot(), DeleteArgs, OperatorDelete);
919 }
920 };
John McCall7f9c92a2010-09-17 00:50:28 +0000921
922 /// A cleanup to call the given 'operator delete' function upon
923 /// abnormal exit from a new expression when the new expression is
924 /// conditional.
925 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
926 size_t NumPlacementArgs;
927 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +0000928 DominatingValue<RValue>::saved_type Ptr;
929 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +0000930
John McCallcb5f77f2011-01-28 10:53:53 +0000931 DominatingValue<RValue>::saved_type *getPlacementArgs() {
932 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +0000933 }
934
935 public:
936 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +0000937 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +0000938 }
939
940 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
941 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +0000942 DominatingValue<RValue>::saved_type Ptr,
943 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +0000944 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
945 Ptr(Ptr), AllocSize(AllocSize) {}
946
John McCallcb5f77f2011-01-28 10:53:53 +0000947 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +0000948 assert(I < NumPlacementArgs && "index out of range");
949 getPlacementArgs()[I] = Arg;
950 }
951
John McCall30317fd2011-07-12 20:27:29 +0000952 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +0000953 const FunctionProtoType *FPT
954 = OperatorDelete->getType()->getAs<FunctionProtoType>();
955 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
956 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
957
958 CallArgList DeleteArgs;
959
960 // The first argument is always a void*.
961 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000962 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000963
964 // A member 'operator delete' can take an extra 'size_t' argument.
965 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +0000966 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +0000967 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000968 }
969
970 // Pass the rest of the arguments, which must match exactly.
971 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +0000972 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +0000973 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000974 }
975
976 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000977 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +0000978 CGF.CGM.GetAddrOfFunction(OperatorDelete),
979 ReturnValueSlot(), DeleteArgs, OperatorDelete);
980 }
981 };
982}
983
984/// Enter a cleanup to call 'operator delete' if the initializer in a
985/// new-expression throws.
986static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
987 const CXXNewExpr *E,
988 llvm::Value *NewPtr,
989 llvm::Value *AllocSize,
990 const CallArgList &NewArgs) {
991 // If we're not inside a conditional branch, then the cleanup will
992 // dominate and we can do the easier (and more efficient) thing.
993 if (!CGF.isInConditionalBranch()) {
994 CallDeleteDuringNew *Cleanup = CGF.EHStack
995 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
996 E->getNumPlacementArgs(),
997 E->getOperatorDelete(),
998 NewPtr, AllocSize);
999 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001000 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001001
1002 return;
1003 }
1004
1005 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001006 DominatingValue<RValue>::saved_type SavedNewPtr =
1007 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1008 DominatingValue<RValue>::saved_type SavedAllocSize =
1009 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001010
1011 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1012 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
1013 E->getNumPlacementArgs(),
1014 E->getOperatorDelete(),
1015 SavedNewPtr,
1016 SavedAllocSize);
1017 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001018 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001019 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001020
1021 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +00001022}
1023
Anders Carlssoncc52f652009-09-22 22:53:17 +00001024llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001025 // The element type being allocated.
1026 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001027
John McCall75f94982011-03-07 03:12:35 +00001028 // 1. Build a call to the allocation function.
1029 FunctionDecl *allocator = E->getOperatorNew();
1030 const FunctionProtoType *allocatorType =
1031 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001032
John McCall75f94982011-03-07 03:12:35 +00001033 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001034
1035 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001036 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001037
John McCall75f94982011-03-07 03:12:35 +00001038 llvm::Value *numElements = 0;
1039 llvm::Value *allocSizeWithoutCookie = 0;
1040 llvm::Value *allocSize =
John McCall036f2f62011-05-15 07:14:44 +00001041 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001042
Eli Friedman43dca6a2011-05-02 17:57:46 +00001043 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001044
1045 // Emit the rest of the arguments.
1046 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001047 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001048
1049 // First, use the types from the function type.
1050 // We start at 1 here because the first argument (the allocation size)
1051 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001052 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1053 ++i, ++placementArg) {
1054 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001055
John McCall75f94982011-03-07 03:12:35 +00001056 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1057 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001058 "type mismatch in call argument!");
1059
John McCall32ea9692011-03-11 20:59:21 +00001060 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001061 }
1062
1063 // Either we've emitted all the call args, or we have a call to a
1064 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001065 assert((placementArg == E->placement_arg_end() ||
1066 allocatorType->isVariadic()) &&
1067 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001068
1069 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001070 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1071 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001072 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001073 }
1074
John McCall7ec4b432011-05-16 01:05:12 +00001075 // Emit the allocation call. If the allocator is a global placement
1076 // operator, just "inline" it directly.
1077 RValue RV;
1078 if (allocator->isReservedGlobalPlacementOperator()) {
1079 assert(allocatorArgs.size() == 2);
1080 RV = allocatorArgs[1].RV;
1081 // TODO: kill any unnecessary computations done for the size
1082 // argument.
1083 } else {
1084 RV = EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1085 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1086 allocatorArgs, allocator);
1087 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001088
John McCall75f94982011-03-07 03:12:35 +00001089 // Emit a null check on the allocation result if the allocation
1090 // function is allowed to return null (because it has a non-throwing
1091 // exception spec; for this part, we inline
1092 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1093 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001094 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCall31168b02011-06-15 23:02:42 +00001095 !(allocType.isPODType(getContext()) && !E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001096
John McCall75f94982011-03-07 03:12:35 +00001097 llvm::BasicBlock *nullCheckBB = 0;
1098 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001099
John McCall75f94982011-03-07 03:12:35 +00001100 llvm::Value *allocation = RV.getScalarVal();
1101 unsigned AS =
1102 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001103
John McCallf7dcf322011-03-07 01:52:56 +00001104 // The null-check means that the initializer is conditionally
1105 // evaluated.
1106 ConditionalEvaluation conditional(*this);
1107
John McCall75f94982011-03-07 03:12:35 +00001108 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001109 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001110
1111 nullCheckBB = Builder.GetInsertBlock();
1112 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1113 contBB = createBasicBlock("new.cont");
1114
1115 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1116 Builder.CreateCondBr(isNull, contBB, notNullBB);
1117 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001118 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001119
John McCall75f94982011-03-07 03:12:35 +00001120 assert((allocSize == allocSizeWithoutCookie) ==
John McCall8ed55a52010-09-02 09:58:18 +00001121 CalculateCookiePadding(*this, E).isZero());
John McCall75f94982011-03-07 03:12:35 +00001122 if (allocSize != allocSizeWithoutCookie) {
John McCall8ed55a52010-09-02 09:58:18 +00001123 assert(E->isArray());
John McCall75f94982011-03-07 03:12:35 +00001124 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1125 numElements,
1126 E, allocType);
John McCall8ed55a52010-09-02 09:58:18 +00001127 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001128
John McCall824c2f52010-09-14 07:57:04 +00001129 // If there's an operator delete, enter a cleanup to call it if an
1130 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001131 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7ec4b432011-05-16 01:05:12 +00001132 if (E->getOperatorDelete() &&
1133 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001134 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1135 operatorDeleteCleanup = EHStack.stable_begin();
John McCall824c2f52010-09-14 07:57:04 +00001136 }
1137
John McCall75f94982011-03-07 03:12:35 +00001138 const llvm::Type *elementPtrTy
1139 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1140 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001141
John McCall8ed55a52010-09-02 09:58:18 +00001142 if (E->isArray()) {
John McCall75f94982011-03-07 03:12:35 +00001143 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001144
1145 // NewPtr is a pointer to the base element type. If we're
1146 // allocating an array of arrays, we'll need to cast back to the
1147 // array pointer type.
John McCall75f94982011-03-07 03:12:35 +00001148 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1149 if (result->getType() != resultType)
1150 result = Builder.CreateBitCast(result, resultType);
John McCall8ed55a52010-09-02 09:58:18 +00001151 } else {
John McCall75f94982011-03-07 03:12:35 +00001152 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001153 }
John McCall824c2f52010-09-14 07:57:04 +00001154
1155 // Deactivate the 'operator delete' cleanup if we finished
1156 // initialization.
John McCall75f94982011-03-07 03:12:35 +00001157 if (operatorDeleteCleanup.isValid())
1158 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001159
John McCall75f94982011-03-07 03:12:35 +00001160 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001161 conditional.end(*this);
1162
John McCall75f94982011-03-07 03:12:35 +00001163 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1164 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001165
Jay Foad20c0f022011-03-30 11:28:58 +00001166 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001167 PHI->addIncoming(result, notNullBB);
1168 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1169 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001170
John McCall75f94982011-03-07 03:12:35 +00001171 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001172 }
John McCall8ed55a52010-09-02 09:58:18 +00001173
John McCall75f94982011-03-07 03:12:35 +00001174 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001175}
1176
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001177void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1178 llvm::Value *Ptr,
1179 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001180 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1181
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001182 const FunctionProtoType *DeleteFTy =
1183 DeleteFD->getType()->getAs<FunctionProtoType>();
1184
1185 CallArgList DeleteArgs;
1186
Anders Carlsson21122cf2009-12-13 20:04:38 +00001187 // Check if we need to pass the size to the delete operator.
1188 llvm::Value *Size = 0;
1189 QualType SizeTy;
1190 if (DeleteFTy->getNumArgs() == 2) {
1191 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001192 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1193 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1194 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001195 }
1196
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001197 QualType ArgTy = DeleteFTy->getArgType(0);
1198 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001199 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001200
Anders Carlsson21122cf2009-12-13 20:04:38 +00001201 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001202 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001203
1204 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001205 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001206 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001207 DeleteArgs, DeleteFD);
1208}
1209
John McCall8ed55a52010-09-02 09:58:18 +00001210namespace {
1211 /// Calls the given 'operator delete' on a single object.
1212 struct CallObjectDelete : EHScopeStack::Cleanup {
1213 llvm::Value *Ptr;
1214 const FunctionDecl *OperatorDelete;
1215 QualType ElementType;
1216
1217 CallObjectDelete(llvm::Value *Ptr,
1218 const FunctionDecl *OperatorDelete,
1219 QualType ElementType)
1220 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1221
John McCall30317fd2011-07-12 20:27:29 +00001222 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001223 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1224 }
1225 };
1226}
1227
1228/// Emit the code for deleting a single object.
1229static void EmitObjectDelete(CodeGenFunction &CGF,
1230 const FunctionDecl *OperatorDelete,
1231 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001232 QualType ElementType,
1233 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001234 // Find the destructor for the type, if applicable. If the
1235 // destructor is virtual, we'll just emit the vcall and return.
1236 const CXXDestructorDecl *Dtor = 0;
1237 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1238 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1239 if (!RD->hasTrivialDestructor()) {
1240 Dtor = RD->getDestructor();
1241
1242 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001243 if (UseGlobalDelete) {
1244 // If we're supposed to call the global delete, make sure we do so
1245 // even if the destructor throws.
1246 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1247 Ptr, OperatorDelete,
1248 ElementType);
1249 }
1250
John McCall8ed55a52010-09-02 09:58:18 +00001251 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001252 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1253 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001254 /*isVariadic=*/false);
1255
1256 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001257 = CGF.BuildVirtualCall(Dtor,
1258 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1259 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001260 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1261 0, 0);
1262
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001263 if (UseGlobalDelete) {
1264 CGF.PopCleanupBlock();
1265 }
1266
John McCall8ed55a52010-09-02 09:58:18 +00001267 return;
1268 }
1269 }
1270 }
1271
1272 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001273 // This doesn't have to a conditional cleanup because we're going
1274 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001275 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1276 Ptr, OperatorDelete, ElementType);
1277
1278 if (Dtor)
1279 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1280 /*ForVirtualBase=*/false, Ptr);
John McCall31168b02011-06-15 23:02:42 +00001281 else if (CGF.getLangOptions().ObjCAutoRefCount &&
1282 ElementType->isObjCLifetimeType()) {
1283 switch (ElementType.getObjCLifetime()) {
1284 case Qualifiers::OCL_None:
1285 case Qualifiers::OCL_ExplicitNone:
1286 case Qualifiers::OCL_Autoreleasing:
1287 break;
John McCall8ed55a52010-09-02 09:58:18 +00001288
John McCall31168b02011-06-15 23:02:42 +00001289 case Qualifiers::OCL_Strong: {
1290 // Load the pointer value.
1291 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1292 ElementType.isVolatileQualified());
1293
1294 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1295 break;
1296 }
1297
1298 case Qualifiers::OCL_Weak:
1299 CGF.EmitARCDestroyWeak(Ptr);
1300 break;
1301 }
1302 }
1303
John McCall8ed55a52010-09-02 09:58:18 +00001304 CGF.PopCleanupBlock();
1305}
1306
1307namespace {
1308 /// Calls the given 'operator delete' on an array of objects.
1309 struct CallArrayDelete : EHScopeStack::Cleanup {
1310 llvm::Value *Ptr;
1311 const FunctionDecl *OperatorDelete;
1312 llvm::Value *NumElements;
1313 QualType ElementType;
1314 CharUnits CookieSize;
1315
1316 CallArrayDelete(llvm::Value *Ptr,
1317 const FunctionDecl *OperatorDelete,
1318 llvm::Value *NumElements,
1319 QualType ElementType,
1320 CharUnits CookieSize)
1321 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1322 ElementType(ElementType), CookieSize(CookieSize) {}
1323
John McCall30317fd2011-07-12 20:27:29 +00001324 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001325 const FunctionProtoType *DeleteFTy =
1326 OperatorDelete->getType()->getAs<FunctionProtoType>();
1327 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1328
1329 CallArgList Args;
1330
1331 // Pass the pointer as the first argument.
1332 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1333 llvm::Value *DeletePtr
1334 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001335 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001336
1337 // Pass the original requested size as the second argument.
1338 if (DeleteFTy->getNumArgs() == 2) {
1339 QualType size_t = DeleteFTy->getArgType(1);
1340 const llvm::IntegerType *SizeTy
1341 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1342
1343 CharUnits ElementTypeSize =
1344 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1345
1346 // The size of an element, multiplied by the number of elements.
1347 llvm::Value *Size
1348 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1349 Size = CGF.Builder.CreateMul(Size, NumElements);
1350
1351 // Plus the size of the cookie if applicable.
1352 if (!CookieSize.isZero()) {
1353 llvm::Value *CookieSizeV
1354 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1355 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1356 }
1357
Eli Friedman43dca6a2011-05-02 17:57:46 +00001358 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001359 }
1360
1361 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001362 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001363 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1364 ReturnValueSlot(), Args, OperatorDelete);
1365 }
1366 };
1367}
1368
1369/// Emit the code for deleting an array of objects.
1370static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001371 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001372 llvm::Value *deletedPtr,
1373 QualType elementType) {
1374 llvm::Value *numElements = 0;
1375 llvm::Value *allocatedPtr = 0;
1376 CharUnits cookieSize;
1377 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1378 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001379
John McCallca2c56f2011-07-13 01:41:37 +00001380 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001381
1382 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001383 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001384 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001385 allocatedPtr, operatorDelete,
1386 numElements, elementType,
1387 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001388
John McCallca2c56f2011-07-13 01:41:37 +00001389 // Destroy the elements.
1390 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1391 assert(numElements && "no element count for a type with a destructor!");
1392
1393 // It's legal to allocate a zero-length array, but emitArrayDestroy
1394 // won't handle that correctly, so we need to check that here.
1395 llvm::Value *iszero =
1396 CGF.Builder.CreateIsNull(numElements, "delete.isempty");
1397
1398 // We'll patch the 'true' successor of this to lead to the end of
1399 // the emitArrayDestroy loop.
1400 llvm::BasicBlock *destroyBB = CGF.createBasicBlock("delete.destroy");
1401 llvm::BranchInst *br =
1402 CGF.Builder.CreateCondBr(iszero, destroyBB, destroyBB);
1403 CGF.EmitBlock(destroyBB);
1404
1405 llvm::Value *arrayEnd =
1406 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
1407 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1408 CGF.getDestroyer(dtorKind),
1409 CGF.needsEHCleanup(dtorKind));
1410
1411 assert(CGF.Builder.GetInsertBlock()->empty());
1412 br->setSuccessor(0, CGF.Builder.GetInsertBlock());
John McCall8ed55a52010-09-02 09:58:18 +00001413 }
1414
John McCallca2c56f2011-07-13 01:41:37 +00001415 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001416 CGF.PopCleanupBlock();
1417}
1418
Anders Carlssoncc52f652009-09-22 22:53:17 +00001419void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001420
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001421 // Get at the argument before we performed the implicit conversion
1422 // to void*.
1423 const Expr *Arg = E->getArgument();
1424 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001425 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001426 ICE->getType()->isVoidPointerType())
1427 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001428 else
1429 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001430 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001431
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001432 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001433
1434 // Null check the pointer.
1435 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1436 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1437
Anders Carlsson98981b12011-04-11 00:30:07 +00001438 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001439
1440 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1441 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001442
John McCall8ed55a52010-09-02 09:58:18 +00001443 // We might be deleting a pointer to array. If so, GEP down to the
1444 // first non-array element.
1445 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1446 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1447 if (DeleteTy->isConstantArrayType()) {
1448 llvm::Value *Zero = Builder.getInt32(0);
1449 llvm::SmallVector<llvm::Value*,8> GEP;
1450
1451 GEP.push_back(Zero); // point at the outermost array
1452
1453 // For each layer of array type we're pointing at:
1454 while (const ConstantArrayType *Arr
1455 = getContext().getAsConstantArrayType(DeleteTy)) {
1456 // 1. Unpeel the array type.
1457 DeleteTy = Arr->getElementType();
1458
1459 // 2. GEP to the first element of the array.
1460 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001461 }
John McCall8ed55a52010-09-02 09:58:18 +00001462
1463 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001464 }
1465
Douglas Gregor04f36212010-09-02 17:38:50 +00001466 assert(ConvertTypeForMem(DeleteTy) ==
1467 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001468
1469 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001470 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001471 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001472 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1473 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001474 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001475
Anders Carlssoncc52f652009-09-22 22:53:17 +00001476 EmitBlock(DeleteEnd);
1477}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001478
Anders Carlsson0c633502011-04-11 14:13:40 +00001479static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1480 // void __cxa_bad_typeid();
1481
1482 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1483 const llvm::FunctionType *FTy =
1484 llvm::FunctionType::get(VoidTy, false);
1485
1486 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1487}
1488
1489static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001490 llvm::Value *Fn = getBadTypeidFn(CGF);
1491 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001492 CGF.Builder.CreateUnreachable();
1493}
1494
Anders Carlsson940f02d2011-04-18 00:57:03 +00001495static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1496 const Expr *E,
1497 const llvm::Type *StdTypeInfoPtrTy) {
1498 // Get the vtable pointer.
1499 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1500
1501 // C++ [expr.typeid]p2:
1502 // If the glvalue expression is obtained by applying the unary * operator to
1503 // a pointer and the pointer is a null pointer value, the typeid expression
1504 // throws the std::bad_typeid exception.
1505 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1506 if (UO->getOpcode() == UO_Deref) {
1507 llvm::BasicBlock *BadTypeidBlock =
1508 CGF.createBasicBlock("typeid.bad_typeid");
1509 llvm::BasicBlock *EndBlock =
1510 CGF.createBasicBlock("typeid.end");
1511
1512 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1513 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1514
1515 CGF.EmitBlock(BadTypeidBlock);
1516 EmitBadTypeidCall(CGF);
1517 CGF.EmitBlock(EndBlock);
1518 }
1519 }
1520
1521 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1522 StdTypeInfoPtrTy->getPointerTo());
1523
1524 // Load the type info.
1525 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1526 return CGF.Builder.CreateLoad(Value);
1527}
1528
John McCalle4df6c82011-01-28 08:37:24 +00001529llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001530 const llvm::Type *StdTypeInfoPtrTy =
1531 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001532
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001533 if (E->isTypeOperand()) {
1534 llvm::Constant *TypeInfo =
1535 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001536 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001537 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001538
Anders Carlsson940f02d2011-04-18 00:57:03 +00001539 // C++ [expr.typeid]p2:
1540 // When typeid is applied to a glvalue expression whose type is a
1541 // polymorphic class type, the result refers to a std::type_info object
1542 // representing the type of the most derived object (that is, the dynamic
1543 // type) to which the glvalue refers.
1544 if (E->getExprOperand()->isGLValue()) {
1545 if (const RecordType *RT =
1546 E->getExprOperand()->getType()->getAs<RecordType>()) {
1547 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1548 if (RD->isPolymorphic())
1549 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1550 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001551 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001552 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001553
1554 QualType OperandTy = E->getExprOperand()->getType();
1555 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1556 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001557}
Mike Stump65511702009-11-16 06:50:58 +00001558
Anders Carlsson882d7902011-04-11 00:46:40 +00001559static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1560 // void *__dynamic_cast(const void *sub,
1561 // const abi::__class_type_info *src,
1562 // const abi::__class_type_info *dst,
1563 // std::ptrdiff_t src2dst_offset);
1564
Chris Lattnera5f58b02011-07-09 17:41:47 +00001565 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1566 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001567 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1568
Chris Lattnera5f58b02011-07-09 17:41:47 +00001569 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001570
1571 const llvm::FunctionType *FTy =
1572 llvm::FunctionType::get(Int8PtrTy, Args, false);
1573
1574 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1575}
1576
1577static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1578 // void __cxa_bad_cast();
1579
1580 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1581 const llvm::FunctionType *FTy =
1582 llvm::FunctionType::get(VoidTy, false);
1583
1584 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1585}
1586
Anders Carlssonc1c99712011-04-11 01:45:29 +00001587static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001588 llvm::Value *Fn = getBadCastFn(CGF);
1589 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001590 CGF.Builder.CreateUnreachable();
1591}
1592
Anders Carlsson882d7902011-04-11 00:46:40 +00001593static llvm::Value *
1594EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1595 QualType SrcTy, QualType DestTy,
1596 llvm::BasicBlock *CastEnd) {
1597 const llvm::Type *PtrDiffLTy =
1598 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1599 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1600
1601 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1602 if (PTy->getPointeeType()->isVoidType()) {
1603 // C++ [expr.dynamic.cast]p7:
1604 // If T is "pointer to cv void," then the result is a pointer to the
1605 // most derived object pointed to by v.
1606
1607 // Get the vtable pointer.
1608 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1609
1610 // Get the offset-to-top from the vtable.
1611 llvm::Value *OffsetToTop =
1612 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1613 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1614
1615 // Finally, add the offset to the pointer.
1616 Value = CGF.EmitCastToVoidPtr(Value);
1617 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1618
1619 return CGF.Builder.CreateBitCast(Value, DestLTy);
1620 }
1621 }
1622
1623 QualType SrcRecordTy;
1624 QualType DestRecordTy;
1625
1626 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1627 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1628 DestRecordTy = DestPTy->getPointeeType();
1629 } else {
1630 SrcRecordTy = SrcTy;
1631 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1632 }
1633
1634 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1635 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1636
1637 llvm::Value *SrcRTTI =
1638 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1639 llvm::Value *DestRTTI =
1640 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1641
1642 // FIXME: Actually compute a hint here.
1643 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1644
1645 // Emit the call to __dynamic_cast.
1646 Value = CGF.EmitCastToVoidPtr(Value);
1647 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1648 SrcRTTI, DestRTTI, OffsetHint);
1649 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1650
1651 /// C++ [expr.dynamic.cast]p9:
1652 /// A failed cast to reference type throws std::bad_cast
1653 if (DestTy->isReferenceType()) {
1654 llvm::BasicBlock *BadCastBlock =
1655 CGF.createBasicBlock("dynamic_cast.bad_cast");
1656
1657 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1658 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1659
1660 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001661 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001662 }
1663
1664 return Value;
1665}
1666
Anders Carlssonc1c99712011-04-11 01:45:29 +00001667static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1668 QualType DestTy) {
1669 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1670 if (DestTy->isPointerType())
1671 return llvm::Constant::getNullValue(DestLTy);
1672
1673 /// C++ [expr.dynamic.cast]p9:
1674 /// A failed cast to reference type throws std::bad_cast
1675 EmitBadCastCall(CGF);
1676
1677 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1678 return llvm::UndefValue::get(DestLTy);
1679}
1680
Anders Carlsson882d7902011-04-11 00:46:40 +00001681llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001682 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001683 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001684
Anders Carlssonc1c99712011-04-11 01:45:29 +00001685 if (DCE->isAlwaysNull())
1686 return EmitDynamicCastToNull(*this, DestTy);
1687
1688 QualType SrcTy = DCE->getSubExpr()->getType();
1689
Anders Carlsson882d7902011-04-11 00:46:40 +00001690 // C++ [expr.dynamic.cast]p4:
1691 // If the value of v is a null pointer value in the pointer case, the result
1692 // is the null pointer value of type T.
1693 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001694
Anders Carlsson882d7902011-04-11 00:46:40 +00001695 llvm::BasicBlock *CastNull = 0;
1696 llvm::BasicBlock *CastNotNull = 0;
1697 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001698
Anders Carlsson882d7902011-04-11 00:46:40 +00001699 if (ShouldNullCheckSrcValue) {
1700 CastNull = createBasicBlock("dynamic_cast.null");
1701 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1702
1703 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1704 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1705 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001706 }
1707
Anders Carlsson882d7902011-04-11 00:46:40 +00001708 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1709
1710 if (ShouldNullCheckSrcValue) {
1711 EmitBranch(CastEnd);
1712
1713 EmitBlock(CastNull);
1714 EmitBranch(CastEnd);
1715 }
1716
1717 EmitBlock(CastEnd);
1718
1719 if (ShouldNullCheckSrcValue) {
1720 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1721 PHI->addIncoming(Value, CastNotNull);
1722 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1723
1724 Value = PHI;
1725 }
1726
1727 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001728}