blob: 548bbc9e617e8bee6b88e76ef8bffd84907ae7af [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelc69e1cf2010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlsson16d81b82009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson3b5ad222010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000031 CallExpr::const_arg_iterator ArgBeg,
32 CallExpr::const_arg_iterator ArgEnd) {
33 assert(MD->isInstance() &&
34 "Trying to emit a member call expr on a static method!");
35
Anders Carlsson3b5ad222010-01-01 20:29:01 +000036 CallArgList Args;
37
38 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000039 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000040
Anders Carlssonc997d422010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000044 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000045 }
John McCallde5d3c72012-02-17 03:33:10 +000046
47 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
48 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssonc997d422010-01-02 01:01:18 +000049
John McCallde5d3c72012-02-17 03:33:10 +000050 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
52
John McCallde5d3c72012-02-17 03:33:10 +000053 return EmitCall(CGM.getTypes().arrangeFunctionCall(FPT->getResultType(), Args,
54 FPT->getExtInfo(),
55 required),
Rafael Espindola264ba482010-03-30 20:24:48 +000056 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000057}
58
Anders Carlsson1679f5a2011-01-29 03:52:01 +000059static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000060 const Expr *E = Base;
61
62 while (true) {
63 E = E->IgnoreParens();
64 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
65 if (CE->getCastKind() == CK_DerivedToBase ||
66 CE->getCastKind() == CK_UncheckedDerivedToBase ||
67 CE->getCastKind() == CK_NoOp) {
68 E = CE->getSubExpr();
69 continue;
70 }
71 }
72
73 break;
74 }
75
76 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000077 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
78 DerivedType = PTy->getPointeeType();
79
80 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
81}
82
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000083// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
84// quite what we want.
85static const Expr *skipNoOpCastsAndParens(const Expr *E) {
86 while (true) {
87 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
88 E = PE->getSubExpr();
89 continue;
90 }
91
92 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
93 if (CE->getCastKind() == CK_NoOp) {
94 E = CE->getSubExpr();
95 continue;
96 }
97 }
98 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
99 if (UO->getOpcode() == UO_Extension) {
100 E = UO->getSubExpr();
101 continue;
102 }
103 }
104 return E;
105 }
106}
107
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000108/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
109/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000110static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
111 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000112 const CXXMethodDecl *MD) {
113
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000114 // When building with -fapple-kext, all calls must go through the vtable since
115 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000116 if (Context.getLangOptions().AppleKext)
117 return false;
118
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000119 // If the most derived class is marked final, we know that no subclass can
120 // override this member function and so we can devirtualize it. For example:
121 //
122 // struct A { virtual void f(); }
123 // struct B final : A { };
124 //
125 // void f(B *b) {
126 // b->f();
127 // }
128 //
129 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
130 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
131 return true;
132
Anders Carlssonf89e0422011-01-23 21:07:30 +0000133 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000134 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000135 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000136 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000137
Anders Carlssonf89e0422011-01-23 21:07:30 +0000138 // Similarly, if the class itself is marked 'final' it can't be overridden
139 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000140 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000141 return true;
142
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000143 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000144 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
145 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
146 // This is a record decl. We know the type and can devirtualize it.
147 return VD->getType()->isRecordType();
148 }
149
150 return false;
151 }
152
153 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000154 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000155 return true;
156
157 // And calls on bound temporaries.
158 if (isa<CXXBindTemporaryExpr>(Base))
159 return true;
160
161 // Check if this is a call expr that returns a record type.
162 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
163 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000164
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000165 // We can't devirtualize the call.
166 return false;
167}
168
Francois Pichetdbee3412011-01-18 05:04:39 +0000169// Note: This function also emit constructor calls to support a MSVC
170// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000171RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
172 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000173 const Expr *callee = CE->getCallee()->IgnoreParens();
174
175 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000176 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000177
178 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000179 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
180
Devang Patelc69e1cf2010-09-30 19:05:55 +0000181 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000182 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
183 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000184 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
185 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
186 DI->getOrCreateRecordType(PTy->getPointeeType(),
187 MD->getParent()->getLocation());
188 }
189 }
190
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000191 if (MD->isStatic()) {
192 // The method is static, emit it as we would a regular call.
193 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
194 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
195 ReturnValue, CE->arg_begin(), CE->arg_end());
196 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000197
John McCallfc400282010-09-03 01:26:39 +0000198 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000199 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000200 if (ME->isArrow())
201 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000202 else
203 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000204
John McCallfc400282010-09-03 01:26:39 +0000205 if (MD->isTrivial()) {
206 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000207 if (isa<CXXConstructorDecl>(MD) &&
208 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
209 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000210
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000211 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
212 // We don't like to generate the trivial copy/move assignment operator
213 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000214 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
215 EmitAggregateCopy(This, RHS, CE->getType());
216 return RValue::get(This);
217 }
218
219 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000220 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
221 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000222 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
223 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
224 CE->arg_begin(), CE->arg_end());
225 return RValue::get(This);
226 }
227 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000228 }
229
John McCallfc400282010-09-03 01:26:39 +0000230 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000231 const CGFunctionInfo *FInfo = 0;
232 if (isa<CXXDestructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000233 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
234 Dtor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000235 else if (isa<CXXConstructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000236 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
237 cast<CXXConstructorDecl>(MD),
238 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000239 else
John McCallde5d3c72012-02-17 03:33:10 +0000240 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCallfc400282010-09-03 01:26:39 +0000241
John McCallde5d3c72012-02-17 03:33:10 +0000242 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000243
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000244 // C++ [class.virtual]p12:
245 // Explicit qualification with the scope operator (5.1) suppresses the
246 // virtual call mechanism.
247 //
248 // We also don't emit a virtual call if the base expression has a record type
249 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000250 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000251 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
252 && !canDevirtualizeMemberFunctionCalls(getContext(),
253 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000254 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000255 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
256 if (UseVirtualCall) {
257 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000258 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000259 if (getContext().getLangOptions().AppleKext &&
260 MD->isVirtual() &&
261 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000262 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000263 else
264 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000265 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000266 } else if (const CXXConstructorDecl *Ctor =
267 dyn_cast<CXXConstructorDecl>(MD)) {
268 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000269 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000270 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000271 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000272 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000273 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000274 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000275 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000276 else
277 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000278 }
279
Anders Carlssonc997d422010-01-02 01:01:18 +0000280 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000281 CE->arg_begin(), CE->arg_end());
282}
283
284RValue
285CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
286 ReturnValueSlot ReturnValue) {
287 const BinaryOperator *BO =
288 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
289 const Expr *BaseExpr = BO->getLHS();
290 const Expr *MemFnExpr = BO->getRHS();
291
292 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000293 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000294
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000295 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000296 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000297 const CXXRecordDecl *RD =
298 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
299
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000300 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000301 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000302
303 // Emit the 'this' pointer.
304 llvm::Value *This;
305
John McCall2de56d12010-08-25 11:45:40 +0000306 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000307 This = EmitScalarExpr(BaseExpr);
308 else
309 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000310
John McCall93d557b2010-08-22 00:05:51 +0000311 // Ask the ABI to load the callee. Note that This is modified.
312 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000313 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000314
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000315 CallArgList Args;
316
317 QualType ThisType =
318 getContext().getPointerType(getContext().getTagDeclType(RD));
319
320 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000321 Args.add(RValue::get(This), ThisType);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000322
323 // And the rest of the call args
324 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallde5d3c72012-02-17 03:33:10 +0000325 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000326 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000327}
328
329RValue
330CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
331 const CXXMethodDecl *MD,
332 ReturnValueSlot ReturnValue) {
333 assert(MD->isInstance() &&
334 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000335 LValue LV = EmitLValue(E->getArg(0));
336 llvm::Value *This = LV.getAddress();
337
Douglas Gregorb2b56582011-09-06 16:26:56 +0000338 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
339 MD->isTrivial()) {
340 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
341 QualType Ty = E->getType();
342 EmitAggregateCopy(This, Src, Ty);
343 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344 }
345
Anders Carlssona2447e02011-05-08 20:32:23 +0000346 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000347 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000348 E->arg_begin() + 1, E->arg_end());
349}
350
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000351RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
352 ReturnValueSlot ReturnValue) {
353 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
354}
355
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000356static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
357 llvm::Value *DestPtr,
358 const CXXRecordDecl *Base) {
359 if (Base->isEmpty())
360 return;
361
362 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
363
364 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
365 CharUnits Size = Layout.getNonVirtualSize();
366 CharUnits Align = Layout.getNonVirtualAlign();
367
368 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
369
370 // If the type contains a pointer to data member we can't memset it to zero.
371 // Instead, create a null constant and copy it to the destination.
372 // TODO: there are other patterns besides zero that we can usefully memset,
373 // like -1, which happens to be the pattern used by member-pointers.
374 // TODO: isZeroInitializable can be over-conservative in the case where a
375 // virtual base contains a member pointer.
376 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
377 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
378
379 llvm::GlobalVariable *NullVariable =
380 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
381 /*isConstant=*/true,
382 llvm::GlobalVariable::PrivateLinkage,
383 NullConstant, Twine());
384 NullVariable->setAlignment(Align.getQuantity());
385 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
386
387 // Get and call the appropriate llvm.memcpy overload.
388 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
389 return;
390 }
391
392 // Otherwise, just memset the whole thing to zero. This is legal
393 // because in LLVM, all default initializers (other than the ones we just
394 // handled above) are guaranteed to have a bit pattern of all zeros.
395 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
396 Align.getQuantity());
397}
398
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000399void
John McCall558d2ab2010-09-15 10:14:12 +0000400CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
401 AggValueSlot Dest) {
402 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000403 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000404
405 // If we require zero initialization before (or instead of) calling the
406 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000407 // constructor, emit the zero initialization now, unless destination is
408 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000409 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
410 switch (E->getConstructionKind()) {
411 case CXXConstructExpr::CK_Delegating:
412 assert(0 && "Delegating constructor should not need zeroing");
413 case CXXConstructExpr::CK_Complete:
414 EmitNullInitialization(Dest.getAddr(), E->getType());
415 break;
416 case CXXConstructExpr::CK_VirtualBase:
417 case CXXConstructExpr::CK_NonVirtualBase:
418 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
419 break;
420 }
421 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000422
423 // If this is a call to a trivial default constructor, do nothing.
424 if (CD->isTrivial() && CD->isDefaultConstructor())
425 return;
426
John McCallfc1e6c72010-09-18 00:58:34 +0000427 // Elide the constructor if we're constructing from a temporary.
428 // The temporary check is required because Sema sets this on NRVO
429 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000430 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000431 assert(getContext().hasSameUnqualifiedType(E->getType(),
432 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000433 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
434 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000435 return;
436 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000437 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000438
John McCallc3c07662011-07-13 06:10:41 +0000439 if (const ConstantArrayType *arrayType
440 = getContext().getAsConstantArrayType(E->getType())) {
441 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000442 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000443 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000444 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000445 bool ForVirtualBase = false;
446
447 switch (E->getConstructionKind()) {
448 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000449 // We should be emitting a constructor; GlobalDecl will assert this
450 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000451 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000452
Sean Huntd49bd552011-05-03 20:19:28 +0000453 case CXXConstructExpr::CK_Complete:
454 Type = Ctor_Complete;
455 break;
456
457 case CXXConstructExpr::CK_VirtualBase:
458 ForVirtualBase = true;
459 // fall-through
460
461 case CXXConstructExpr::CK_NonVirtualBase:
462 Type = Ctor_Base;
463 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000464
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000465 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000466 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000467 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000468 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000469}
470
Fariborz Jahanian34999872010-11-13 21:53:34 +0000471void
472CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
473 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000474 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000475 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000476 Exp = E->getSubExpr();
477 assert(isa<CXXConstructExpr>(Exp) &&
478 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
479 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
480 const CXXConstructorDecl *CD = E->getConstructor();
481 RunCleanupsScope Scope(*this);
482
483 // If we require zero initialization before (or instead of) calling the
484 // constructor, as can be the case with a non-user-provided default
485 // constructor, emit the zero initialization now.
486 // FIXME. Do I still need this for a copy ctor synthesis?
487 if (E->requiresZeroInitialization())
488 EmitNullInitialization(Dest, E->getType());
489
Chandler Carruth858a5462010-11-15 13:54:43 +0000490 assert(!getContext().getAsConstantArrayType(E->getType())
491 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000492 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
493 E->arg_begin(), E->arg_end());
494}
495
John McCall1e7fe752010-09-02 09:58:18 +0000496static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
497 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000498 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000499 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000500
John McCallb1c98a32011-05-16 01:05:12 +0000501 // No cookie is required if the operator new[] being used is the
502 // reserved placement operator new[].
503 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000504 return CharUnits::Zero();
505
John McCall6ec278d2011-01-27 09:37:56 +0000506 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000507}
508
John McCall7d166272011-05-15 07:14:44 +0000509static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
510 const CXXNewExpr *e,
511 llvm::Value *&numElements,
512 llvm::Value *&sizeWithoutCookie) {
513 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000514
John McCall7d166272011-05-15 07:14:44 +0000515 if (!e->isArray()) {
516 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
517 sizeWithoutCookie
518 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
519 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000520 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000521
John McCall7d166272011-05-15 07:14:44 +0000522 // The width of size_t.
523 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
524
John McCall1e7fe752010-09-02 09:58:18 +0000525 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000526 llvm::APInt cookieSize(sizeWidth,
527 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000528
Anders Carlssona4d4c012009-09-23 16:07:23 +0000529 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000530 // We multiply the size of all dimensions for NumElements.
531 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000532 numElements = CGF.EmitScalarExpr(e->getArraySize());
533 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000534
John McCall7d166272011-05-15 07:14:44 +0000535 // The number of elements can be have an arbitrary integer type;
536 // essentially, we need to multiply it by a constant factor, add a
537 // cookie size, and verify that the result is representable as a
538 // size_t. That's just a gloss, though, and it's wrong in one
539 // important way: if the count is negative, it's an error even if
540 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000541 bool isSigned
542 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000543 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000544 = cast<llvm::IntegerType>(numElements->getType());
545 unsigned numElementsWidth = numElementsType->getBitWidth();
546
547 // Compute the constant factor.
548 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000549 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000550 = CGF.getContext().getAsConstantArrayType(type)) {
551 type = CAT->getElementType();
552 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000553 }
554
John McCall7d166272011-05-15 07:14:44 +0000555 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
556 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
557 typeSizeMultiplier *= arraySizeMultiplier;
558
559 // This will be a size_t.
560 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000561
Chris Lattner806941e2010-07-20 21:55:52 +0000562 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
563 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000564 if (llvm::ConstantInt *numElementsC =
565 dyn_cast<llvm::ConstantInt>(numElements)) {
566 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000567
John McCall7d166272011-05-15 07:14:44 +0000568 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000569
John McCall7d166272011-05-15 07:14:44 +0000570 // If 'count' was a negative number, it's an overflow.
571 if (isSigned && count.isNegative())
572 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000573
John McCall7d166272011-05-15 07:14:44 +0000574 // We want to do all this arithmetic in size_t. If numElements is
575 // wider than that, check whether it's already too big, and if so,
576 // overflow.
577 else if (numElementsWidth > sizeWidth &&
578 numElementsWidth - sizeWidth > count.countLeadingZeros())
579 hasAnyOverflow = true;
580
581 // Okay, compute a count at the right width.
582 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
583
584 // Scale numElements by that. This might overflow, but we don't
585 // care because it only overflows if allocationSize does, too, and
586 // if that overflows then we shouldn't use this.
587 numElements = llvm::ConstantInt::get(CGF.SizeTy,
588 adjustedCount * arraySizeMultiplier);
589
590 // Compute the size before cookie, and track whether it overflowed.
591 bool overflow;
592 llvm::APInt allocationSize
593 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
594 hasAnyOverflow |= overflow;
595
596 // Add in the cookie, and check whether it's overflowed.
597 if (cookieSize != 0) {
598 // Save the current size without a cookie. This shouldn't be
599 // used if there was overflow.
600 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
601
602 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
603 hasAnyOverflow |= overflow;
604 }
605
606 // On overflow, produce a -1 so operator new will fail.
607 if (hasAnyOverflow) {
608 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
609 } else {
610 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
611 }
612
613 // Otherwise, we might need to use the overflow intrinsics.
614 } else {
615 // There are up to four conditions we need to test for:
616 // 1) if isSigned, we need to check whether numElements is negative;
617 // 2) if numElementsWidth > sizeWidth, we need to check whether
618 // numElements is larger than something representable in size_t;
619 // 3) we need to compute
620 // sizeWithoutCookie := numElements * typeSizeMultiplier
621 // and check whether it overflows; and
622 // 4) if we need a cookie, we need to compute
623 // size := sizeWithoutCookie + cookieSize
624 // and check whether it overflows.
625
626 llvm::Value *hasOverflow = 0;
627
628 // If numElementsWidth > sizeWidth, then one way or another, we're
629 // going to have to do a comparison for (2), and this happens to
630 // take care of (1), too.
631 if (numElementsWidth > sizeWidth) {
632 llvm::APInt threshold(numElementsWidth, 1);
633 threshold <<= sizeWidth;
634
635 llvm::Value *thresholdV
636 = llvm::ConstantInt::get(numElementsType, threshold);
637
638 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
639 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
640
641 // Otherwise, if we're signed, we want to sext up to size_t.
642 } else if (isSigned) {
643 if (numElementsWidth < sizeWidth)
644 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
645
646 // If there's a non-1 type size multiplier, then we can do the
647 // signedness check at the same time as we do the multiply
648 // because a negative number times anything will cause an
649 // unsigned overflow. Otherwise, we have to do it here.
650 if (typeSizeMultiplier == 1)
651 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
652 llvm::ConstantInt::get(CGF.SizeTy, 0));
653
654 // Otherwise, zext up to size_t if necessary.
655 } else if (numElementsWidth < sizeWidth) {
656 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
657 }
658
659 assert(numElements->getType() == CGF.SizeTy);
660
661 size = numElements;
662
663 // Multiply by the type size if necessary. This multiplier
664 // includes all the factors for nested arrays.
665 //
666 // This step also causes numElements to be scaled up by the
667 // nested-array factor if necessary. Overflow on this computation
668 // can be ignored because the result shouldn't be used if
669 // allocation fails.
670 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000671 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000672 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000673
674 llvm::Value *tsmV =
675 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
676 llvm::Value *result =
677 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
678
679 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
680 if (hasOverflow)
681 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
682 else
683 hasOverflow = overflowed;
684
685 size = CGF.Builder.CreateExtractValue(result, 0);
686
687 // Also scale up numElements by the array size multiplier.
688 if (arraySizeMultiplier != 1) {
689 // If the base element type size is 1, then we can re-use the
690 // multiply we just did.
691 if (typeSize.isOne()) {
692 assert(arraySizeMultiplier == typeSizeMultiplier);
693 numElements = size;
694
695 // Otherwise we need a separate multiply.
696 } else {
697 llvm::Value *asmV =
698 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
699 numElements = CGF.Builder.CreateMul(numElements, asmV);
700 }
701 }
702 } else {
703 // numElements doesn't need to be scaled.
704 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000705 }
706
John McCall7d166272011-05-15 07:14:44 +0000707 // Add in the cookie size if necessary.
708 if (cookieSize != 0) {
709 sizeWithoutCookie = size;
710
John McCall7d166272011-05-15 07:14:44 +0000711 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000712 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000713
714 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
715 llvm::Value *result =
716 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
717
718 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
719 if (hasOverflow)
720 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
721 else
722 hasOverflow = overflowed;
723
724 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000725 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000726
John McCall7d166272011-05-15 07:14:44 +0000727 // If we had any possibility of dynamic overflow, make a select to
728 // overwrite 'size' with an all-ones value, which should cause
729 // operator new to throw.
730 if (hasOverflow)
731 size = CGF.Builder.CreateSelect(hasOverflow,
732 llvm::Constant::getAllOnesValue(CGF.SizeTy),
733 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000734 }
John McCall1e7fe752010-09-02 09:58:18 +0000735
John McCall7d166272011-05-15 07:14:44 +0000736 if (cookieSize == 0)
737 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000738 else
John McCall7d166272011-05-15 07:14:44 +0000739 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000740
John McCall7d166272011-05-15 07:14:44 +0000741 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000742}
743
Fariborz Jahanianef668722010-06-25 18:26:07 +0000744static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
745 llvm::Value *NewPtr) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000746
747 const Expr *Init = E->getInitializer();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000748 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000749
Eli Friedmand7722d92011-12-03 02:13:40 +0000750 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCalla07398e2011-06-16 04:16:24 +0000751 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedmand7722d92011-12-03 02:13:40 +0000752 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000753 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000754 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000755 else if (AllocType->isAnyComplexType())
756 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
757 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000758 else {
759 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000760 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000761 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000762 AggValueSlot::DoesNotNeedGCBarriers,
763 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000764 CGF.EmitAggExpr(Init, Slot);
765 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000766}
767
768void
769CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000770 QualType elementType,
771 llvm::Value *beginPtr,
772 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000773 if (!E->hasInitializer())
774 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000775
776 // Check if the number of elements is constant.
777 bool checkZero = true;
778 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
779 // If it's constant zero, skip the whole loop.
780 if (constNum->isZero()) return;
781
782 checkZero = false;
783 }
784
785 // Find the end of the array, hoisted out of the loop.
786 llvm::Value *endPtr =
787 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
788
789 // Create the continuation block.
790 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
791
792 // If we need to check for zero, do so now.
793 if (checkZero) {
794 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
795 llvm::Value *isEmpty = Builder.CreateICmpEQ(beginPtr, endPtr,
796 "array.isempty");
797 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
798 EmitBlock(nonEmptyBB);
799 }
800
801 // Enter the loop.
802 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
803 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
804
805 EmitBlock(loopBB);
806
807 // Set up the current-element phi.
808 llvm::PHINode *curPtr =
809 Builder.CreatePHI(beginPtr->getType(), 2, "array.cur");
810 curPtr->addIncoming(beginPtr, entryBB);
811
812 // Enter a partial-destruction cleanup if necessary.
813 QualType::DestructionKind dtorKind = elementType.isDestructedType();
814 EHScopeStack::stable_iterator cleanup;
John McCall6f103ba2011-11-10 10:43:54 +0000815 llvm::Instruction *cleanupDominator = 0;
John McCall19705672011-09-15 06:49:18 +0000816 if (needsEHCleanup(dtorKind)) {
817 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
818 getDestroyer(dtorKind));
819 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000820 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000821 }
822
823 // Emit the initializer into this element.
824 StoreAnyExprIntoOneUnit(*this, E, curPtr);
825
826 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000827 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000828 DeactivateCleanupBlock(cleanup, cleanupDominator);
829 cleanupDominator->eraseFromParent();
830 }
John McCall19705672011-09-15 06:49:18 +0000831
832 // Advance to the next element.
833 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
834
835 // Check whether we've gotten to the end of the array and, if so,
836 // exit the loop.
837 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
838 Builder.CreateCondBr(isEnd, contBB, loopBB);
839 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
840
841 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000842}
843
Douglas Gregor59174c02010-07-21 01:10:17 +0000844static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
845 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000846 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000847 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000848 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000849 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000850}
851
Anders Carlssona4d4c012009-09-23 16:07:23 +0000852static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000853 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000854 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000855 llvm::Value *NumElements,
856 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000857 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000858 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000859 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
860 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor59174c02010-07-21 01:10:17 +0000861 bool RequiresZeroInitialization = false;
Sean Hunt023df372011-05-09 18:22:59 +0000862 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000863 // If new expression did not specify value-initialization, then there
864 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000865 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000866 return;
867
John McCall19705672011-09-15 06:49:18 +0000868 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000869 // Optimization: since zero initialization will just set the memory
870 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000871 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000872 return;
873 }
874
875 RequiresZeroInitialization = true;
876 }
John McCallc3c07662011-07-13 06:10:41 +0000877
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000878 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
879 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor59174c02010-07-21 01:10:17 +0000880 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000881 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000882 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000883 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000884 // Optimization: since zero initialization will just set the memory
885 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000886 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
887 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +0000888 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000889 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
890 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000891 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000892
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000893 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000894 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000895
Fariborz Jahanianef668722010-06-25 18:26:07 +0000896 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000897}
898
John McCall7d8647f2010-09-14 07:57:04 +0000899namespace {
900 /// A cleanup to call the given 'operator delete' function upon
901 /// abnormal exit from a new expression.
902 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
903 size_t NumPlacementArgs;
904 const FunctionDecl *OperatorDelete;
905 llvm::Value *Ptr;
906 llvm::Value *AllocSize;
907
908 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
909
910 public:
911 static size_t getExtraSize(size_t NumPlacementArgs) {
912 return NumPlacementArgs * sizeof(RValue);
913 }
914
915 CallDeleteDuringNew(size_t NumPlacementArgs,
916 const FunctionDecl *OperatorDelete,
917 llvm::Value *Ptr,
918 llvm::Value *AllocSize)
919 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
920 Ptr(Ptr), AllocSize(AllocSize) {}
921
922 void setPlacementArg(unsigned I, RValue Arg) {
923 assert(I < NumPlacementArgs && "index out of range");
924 getPlacementArgs()[I] = Arg;
925 }
926
John McCallad346f42011-07-12 20:27:29 +0000927 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +0000928 const FunctionProtoType *FPT
929 = OperatorDelete->getType()->getAs<FunctionProtoType>();
930 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000931 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000932
933 CallArgList DeleteArgs;
934
935 // The first argument is always a void*.
936 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000937 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000938
939 // A member 'operator delete' can take an extra 'size_t' argument.
940 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +0000941 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000942
943 // Pass the rest of the arguments, which must match exactly.
944 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +0000945 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000946
947 // Call 'operator delete'.
John McCallde5d3c72012-02-17 03:33:10 +0000948 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000949 CGF.CGM.GetAddrOfFunction(OperatorDelete),
950 ReturnValueSlot(), DeleteArgs, OperatorDelete);
951 }
952 };
John McCall3019c442010-09-17 00:50:28 +0000953
954 /// A cleanup to call the given 'operator delete' function upon
955 /// abnormal exit from a new expression when the new expression is
956 /// conditional.
957 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
958 size_t NumPlacementArgs;
959 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000960 DominatingValue<RValue>::saved_type Ptr;
961 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000962
John McCall804b8072011-01-28 10:53:53 +0000963 DominatingValue<RValue>::saved_type *getPlacementArgs() {
964 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000965 }
966
967 public:
968 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000969 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000970 }
971
972 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
973 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000974 DominatingValue<RValue>::saved_type Ptr,
975 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000976 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
977 Ptr(Ptr), AllocSize(AllocSize) {}
978
John McCall804b8072011-01-28 10:53:53 +0000979 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000980 assert(I < NumPlacementArgs && "index out of range");
981 getPlacementArgs()[I] = Arg;
982 }
983
John McCallad346f42011-07-12 20:27:29 +0000984 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +0000985 const FunctionProtoType *FPT
986 = OperatorDelete->getType()->getAs<FunctionProtoType>();
987 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
988 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
989
990 CallArgList DeleteArgs;
991
992 // The first argument is always a void*.
993 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000994 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +0000995
996 // A member 'operator delete' can take an extra 'size_t' argument.
997 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000998 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000999 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001000 }
1001
1002 // Pass the rest of the arguments, which must match exactly.
1003 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001004 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001005 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001006 }
1007
1008 // Call 'operator delete'.
John McCallde5d3c72012-02-17 03:33:10 +00001009 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +00001010 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1011 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1012 }
1013 };
1014}
1015
1016/// Enter a cleanup to call 'operator delete' if the initializer in a
1017/// new-expression throws.
1018static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1019 const CXXNewExpr *E,
1020 llvm::Value *NewPtr,
1021 llvm::Value *AllocSize,
1022 const CallArgList &NewArgs) {
1023 // If we're not inside a conditional branch, then the cleanup will
1024 // dominate and we can do the easier (and more efficient) thing.
1025 if (!CGF.isInConditionalBranch()) {
1026 CallDeleteDuringNew *Cleanup = CGF.EHStack
1027 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1028 E->getNumPlacementArgs(),
1029 E->getOperatorDelete(),
1030 NewPtr, AllocSize);
1031 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001032 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001033
1034 return;
1035 }
1036
1037 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001038 DominatingValue<RValue>::saved_type SavedNewPtr =
1039 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1040 DominatingValue<RValue>::saved_type SavedAllocSize =
1041 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001042
1043 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001044 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001045 E->getNumPlacementArgs(),
1046 E->getOperatorDelete(),
1047 SavedNewPtr,
1048 SavedAllocSize);
1049 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001050 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001051 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001052
John McCall6f103ba2011-11-10 10:43:54 +00001053 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001054}
1055
Anders Carlsson16d81b82009-09-22 22:53:17 +00001056llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001057 // The element type being allocated.
1058 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001059
John McCallc2f3e7f2011-03-07 03:12:35 +00001060 // 1. Build a call to the allocation function.
1061 FunctionDecl *allocator = E->getOperatorNew();
1062 const FunctionProtoType *allocatorType =
1063 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001064
John McCallc2f3e7f2011-03-07 03:12:35 +00001065 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001066
1067 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001068 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001069
John McCallc2f3e7f2011-03-07 03:12:35 +00001070 llvm::Value *numElements = 0;
1071 llvm::Value *allocSizeWithoutCookie = 0;
1072 llvm::Value *allocSize =
John McCall7d166272011-05-15 07:14:44 +00001073 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001074
Eli Friedman04c9a492011-05-02 17:57:46 +00001075 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001076
1077 // Emit the rest of the arguments.
1078 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001079 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001080
1081 // First, use the types from the function type.
1082 // We start at 1 here because the first argument (the allocation size)
1083 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001084 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1085 ++i, ++placementArg) {
1086 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001087
John McCallc2f3e7f2011-03-07 03:12:35 +00001088 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1089 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001090 "type mismatch in call argument!");
1091
John McCall413ebdb2011-03-11 20:59:21 +00001092 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001093 }
1094
1095 // Either we've emitted all the call args, or we have a call to a
1096 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001097 assert((placementArg == E->placement_arg_end() ||
1098 allocatorType->isVariadic()) &&
1099 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001100
1101 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001102 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1103 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001104 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001105 }
1106
John McCallb1c98a32011-05-16 01:05:12 +00001107 // Emit the allocation call. If the allocator is a global placement
1108 // operator, just "inline" it directly.
1109 RValue RV;
1110 if (allocator->isReservedGlobalPlacementOperator()) {
1111 assert(allocatorArgs.size() == 2);
1112 RV = allocatorArgs[1].RV;
1113 // TODO: kill any unnecessary computations done for the size
1114 // argument.
1115 } else {
John McCallde5d3c72012-02-17 03:33:10 +00001116 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1117 allocatorType),
John McCallb1c98a32011-05-16 01:05:12 +00001118 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1119 allocatorArgs, allocator);
1120 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001121
John McCallc2f3e7f2011-03-07 03:12:35 +00001122 // Emit a null check on the allocation result if the allocation
1123 // function is allowed to return null (because it has a non-throwing
1124 // exception spec; for this part, we inline
1125 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1126 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001127 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001128 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001129
John McCallc2f3e7f2011-03-07 03:12:35 +00001130 llvm::BasicBlock *nullCheckBB = 0;
1131 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001132
John McCallc2f3e7f2011-03-07 03:12:35 +00001133 llvm::Value *allocation = RV.getScalarVal();
1134 unsigned AS =
1135 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001136
John McCalla7f633f2011-03-07 01:52:56 +00001137 // The null-check means that the initializer is conditionally
1138 // evaluated.
1139 ConditionalEvaluation conditional(*this);
1140
John McCallc2f3e7f2011-03-07 03:12:35 +00001141 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001142 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001143
1144 nullCheckBB = Builder.GetInsertBlock();
1145 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1146 contBB = createBasicBlock("new.cont");
1147
1148 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1149 Builder.CreateCondBr(isNull, contBB, notNullBB);
1150 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001151 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001152
John McCall7d8647f2010-09-14 07:57:04 +00001153 // If there's an operator delete, enter a cleanup to call it if an
1154 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001155 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001156 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001157 if (E->getOperatorDelete() &&
1158 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001159 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1160 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001161 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001162 }
1163
Eli Friedman576cf172011-09-06 18:53:03 +00001164 assert((allocSize == allocSizeWithoutCookie) ==
1165 CalculateCookiePadding(*this, E).isZero());
1166 if (allocSize != allocSizeWithoutCookie) {
1167 assert(E->isArray());
1168 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1169 numElements,
1170 E, allocType);
1171 }
1172
Chris Lattner2acc6e32011-07-18 04:24:23 +00001173 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001174 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1175 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001176
John McCall19705672011-09-15 06:49:18 +00001177 EmitNewInitializer(*this, E, allocType, result, numElements,
1178 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001179 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001180 // NewPtr is a pointer to the base element type. If we're
1181 // allocating an array of arrays, we'll need to cast back to the
1182 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001183 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001184 if (result->getType() != resultType)
1185 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001186 }
John McCall7d8647f2010-09-14 07:57:04 +00001187
1188 // Deactivate the 'operator delete' cleanup if we finished
1189 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001190 if (operatorDeleteCleanup.isValid()) {
1191 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1192 cleanupDominator->eraseFromParent();
1193 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001194
John McCallc2f3e7f2011-03-07 03:12:35 +00001195 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001196 conditional.end(*this);
1197
John McCallc2f3e7f2011-03-07 03:12:35 +00001198 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1199 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001200
Jay Foadbbf3bac2011-03-30 11:28:58 +00001201 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001202 PHI->addIncoming(result, notNullBB);
1203 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1204 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001205
John McCallc2f3e7f2011-03-07 03:12:35 +00001206 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001207 }
John McCall1e7fe752010-09-02 09:58:18 +00001208
John McCallc2f3e7f2011-03-07 03:12:35 +00001209 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001210}
1211
Eli Friedman5fe05982009-11-18 00:50:08 +00001212void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1213 llvm::Value *Ptr,
1214 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001215 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1216
Eli Friedman5fe05982009-11-18 00:50:08 +00001217 const FunctionProtoType *DeleteFTy =
1218 DeleteFD->getType()->getAs<FunctionProtoType>();
1219
1220 CallArgList DeleteArgs;
1221
Anders Carlsson871d0782009-12-13 20:04:38 +00001222 // Check if we need to pass the size to the delete operator.
1223 llvm::Value *Size = 0;
1224 QualType SizeTy;
1225 if (DeleteFTy->getNumArgs() == 2) {
1226 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001227 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1228 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1229 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001230 }
1231
Eli Friedman5fe05982009-11-18 00:50:08 +00001232 QualType ArgTy = DeleteFTy->getArgType(0);
1233 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001234 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001235
Anders Carlsson871d0782009-12-13 20:04:38 +00001236 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001237 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001238
1239 // Emit the call to delete.
John McCallde5d3c72012-02-17 03:33:10 +00001240 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001241 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001242 DeleteArgs, DeleteFD);
1243}
1244
John McCall1e7fe752010-09-02 09:58:18 +00001245namespace {
1246 /// Calls the given 'operator delete' on a single object.
1247 struct CallObjectDelete : EHScopeStack::Cleanup {
1248 llvm::Value *Ptr;
1249 const FunctionDecl *OperatorDelete;
1250 QualType ElementType;
1251
1252 CallObjectDelete(llvm::Value *Ptr,
1253 const FunctionDecl *OperatorDelete,
1254 QualType ElementType)
1255 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1256
John McCallad346f42011-07-12 20:27:29 +00001257 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001258 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1259 }
1260 };
1261}
1262
1263/// Emit the code for deleting a single object.
1264static void EmitObjectDelete(CodeGenFunction &CGF,
1265 const FunctionDecl *OperatorDelete,
1266 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001267 QualType ElementType,
1268 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001269 // Find the destructor for the type, if applicable. If the
1270 // destructor is virtual, we'll just emit the vcall and return.
1271 const CXXDestructorDecl *Dtor = 0;
1272 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1273 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001274 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001275 Dtor = RD->getDestructor();
1276
1277 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001278 if (UseGlobalDelete) {
1279 // If we're supposed to call the global delete, make sure we do so
1280 // even if the destructor throws.
1281 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1282 Ptr, OperatorDelete,
1283 ElementType);
1284 }
1285
Chris Lattner2acc6e32011-07-18 04:24:23 +00001286 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +00001287 CGF.getTypes().GetFunctionType(
1288 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall1e7fe752010-09-02 09:58:18 +00001289
1290 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001291 = CGF.BuildVirtualCall(Dtor,
1292 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1293 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001294 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1295 0, 0);
1296
Douglas Gregora8b20f72011-07-13 00:54:47 +00001297 if (UseGlobalDelete) {
1298 CGF.PopCleanupBlock();
1299 }
1300
John McCall1e7fe752010-09-02 09:58:18 +00001301 return;
1302 }
1303 }
1304 }
1305
1306 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001307 // This doesn't have to a conditional cleanup because we're going
1308 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001309 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1310 Ptr, OperatorDelete, ElementType);
1311
1312 if (Dtor)
1313 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1314 /*ForVirtualBase=*/false, Ptr);
John McCallf85e1932011-06-15 23:02:42 +00001315 else if (CGF.getLangOptions().ObjCAutoRefCount &&
1316 ElementType->isObjCLifetimeType()) {
1317 switch (ElementType.getObjCLifetime()) {
1318 case Qualifiers::OCL_None:
1319 case Qualifiers::OCL_ExplicitNone:
1320 case Qualifiers::OCL_Autoreleasing:
1321 break;
John McCall1e7fe752010-09-02 09:58:18 +00001322
John McCallf85e1932011-06-15 23:02:42 +00001323 case Qualifiers::OCL_Strong: {
1324 // Load the pointer value.
1325 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1326 ElementType.isVolatileQualified());
1327
1328 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1329 break;
1330 }
1331
1332 case Qualifiers::OCL_Weak:
1333 CGF.EmitARCDestroyWeak(Ptr);
1334 break;
1335 }
1336 }
1337
John McCall1e7fe752010-09-02 09:58:18 +00001338 CGF.PopCleanupBlock();
1339}
1340
1341namespace {
1342 /// Calls the given 'operator delete' on an array of objects.
1343 struct CallArrayDelete : EHScopeStack::Cleanup {
1344 llvm::Value *Ptr;
1345 const FunctionDecl *OperatorDelete;
1346 llvm::Value *NumElements;
1347 QualType ElementType;
1348 CharUnits CookieSize;
1349
1350 CallArrayDelete(llvm::Value *Ptr,
1351 const FunctionDecl *OperatorDelete,
1352 llvm::Value *NumElements,
1353 QualType ElementType,
1354 CharUnits CookieSize)
1355 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1356 ElementType(ElementType), CookieSize(CookieSize) {}
1357
John McCallad346f42011-07-12 20:27:29 +00001358 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001359 const FunctionProtoType *DeleteFTy =
1360 OperatorDelete->getType()->getAs<FunctionProtoType>();
1361 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1362
1363 CallArgList Args;
1364
1365 // Pass the pointer as the first argument.
1366 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1367 llvm::Value *DeletePtr
1368 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001369 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001370
1371 // Pass the original requested size as the second argument.
1372 if (DeleteFTy->getNumArgs() == 2) {
1373 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001374 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001375 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1376
1377 CharUnits ElementTypeSize =
1378 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1379
1380 // The size of an element, multiplied by the number of elements.
1381 llvm::Value *Size
1382 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1383 Size = CGF.Builder.CreateMul(Size, NumElements);
1384
1385 // Plus the size of the cookie if applicable.
1386 if (!CookieSize.isZero()) {
1387 llvm::Value *CookieSizeV
1388 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1389 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1390 }
1391
Eli Friedman04c9a492011-05-02 17:57:46 +00001392 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001393 }
1394
1395 // Emit the call to delete.
John McCallde5d3c72012-02-17 03:33:10 +00001396 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001397 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1398 ReturnValueSlot(), Args, OperatorDelete);
1399 }
1400 };
1401}
1402
1403/// Emit the code for deleting an array of objects.
1404static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001405 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001406 llvm::Value *deletedPtr,
1407 QualType elementType) {
1408 llvm::Value *numElements = 0;
1409 llvm::Value *allocatedPtr = 0;
1410 CharUnits cookieSize;
1411 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1412 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001413
John McCall7cfd76c2011-07-13 01:41:37 +00001414 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001415
1416 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001417 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001418 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001419 allocatedPtr, operatorDelete,
1420 numElements, elementType,
1421 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001422
John McCall7cfd76c2011-07-13 01:41:37 +00001423 // Destroy the elements.
1424 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1425 assert(numElements && "no element count for a type with a destructor!");
1426
John McCall7cfd76c2011-07-13 01:41:37 +00001427 llvm::Value *arrayEnd =
1428 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001429
1430 // Note that it is legal to allocate a zero-length array, and we
1431 // can never fold the check away because the length should always
1432 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001433 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1434 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001435 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001436 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001437 }
1438
John McCall7cfd76c2011-07-13 01:41:37 +00001439 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001440 CGF.PopCleanupBlock();
1441}
1442
Anders Carlsson16d81b82009-09-22 22:53:17 +00001443void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001444
Douglas Gregor90916562009-09-29 18:16:17 +00001445 // Get at the argument before we performed the implicit conversion
1446 // to void*.
1447 const Expr *Arg = E->getArgument();
1448 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001449 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001450 ICE->getType()->isVoidPointerType())
1451 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001452 else
1453 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001454 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001455
Douglas Gregor90916562009-09-29 18:16:17 +00001456 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001457
1458 // Null check the pointer.
1459 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1460 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1461
Anders Carlssonb9241242011-04-11 00:30:07 +00001462 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001463
1464 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1465 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001466
John McCall1e7fe752010-09-02 09:58:18 +00001467 // We might be deleting a pointer to array. If so, GEP down to the
1468 // first non-array element.
1469 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1470 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1471 if (DeleteTy->isConstantArrayType()) {
1472 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001473 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001474
1475 GEP.push_back(Zero); // point at the outermost array
1476
1477 // For each layer of array type we're pointing at:
1478 while (const ConstantArrayType *Arr
1479 = getContext().getAsConstantArrayType(DeleteTy)) {
1480 // 1. Unpeel the array type.
1481 DeleteTy = Arr->getElementType();
1482
1483 // 2. GEP to the first element of the array.
1484 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001485 }
John McCall1e7fe752010-09-02 09:58:18 +00001486
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001487 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001488 }
1489
Douglas Gregoreede61a2010-09-02 17:38:50 +00001490 assert(ConvertTypeForMem(DeleteTy) ==
1491 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001492
1493 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001494 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001495 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001496 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1497 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001498 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001499
Anders Carlsson16d81b82009-09-22 22:53:17 +00001500 EmitBlock(DeleteEnd);
1501}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001502
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001503static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1504 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001505 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001506
1507 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1508}
1509
1510static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001511 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001512 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001513 CGF.Builder.CreateUnreachable();
1514}
1515
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001516static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1517 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001518 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001519 // Get the vtable pointer.
1520 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1521
1522 // C++ [expr.typeid]p2:
1523 // If the glvalue expression is obtained by applying the unary * operator to
1524 // a pointer and the pointer is a null pointer value, the typeid expression
1525 // throws the std::bad_typeid exception.
1526 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1527 if (UO->getOpcode() == UO_Deref) {
1528 llvm::BasicBlock *BadTypeidBlock =
1529 CGF.createBasicBlock("typeid.bad_typeid");
1530 llvm::BasicBlock *EndBlock =
1531 CGF.createBasicBlock("typeid.end");
1532
1533 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1534 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1535
1536 CGF.EmitBlock(BadTypeidBlock);
1537 EmitBadTypeidCall(CGF);
1538 CGF.EmitBlock(EndBlock);
1539 }
1540 }
1541
1542 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1543 StdTypeInfoPtrTy->getPointerTo());
1544
1545 // Load the type info.
1546 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1547 return CGF.Builder.CreateLoad(Value);
1548}
1549
John McCall3ad32c82011-01-28 08:37:24 +00001550llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001551 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001552 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001553
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001554 if (E->isTypeOperand()) {
1555 llvm::Constant *TypeInfo =
1556 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001557 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001558 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001559
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001560 // C++ [expr.typeid]p2:
1561 // When typeid is applied to a glvalue expression whose type is a
1562 // polymorphic class type, the result refers to a std::type_info object
1563 // representing the type of the most derived object (that is, the dynamic
1564 // type) to which the glvalue refers.
1565 if (E->getExprOperand()->isGLValue()) {
1566 if (const RecordType *RT =
1567 E->getExprOperand()->getType()->getAs<RecordType>()) {
1568 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1569 if (RD->isPolymorphic())
1570 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1571 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001572 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001573 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001574
1575 QualType OperandTy = E->getExprOperand()->getType();
1576 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1577 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001578}
Mike Stumpc849c052009-11-16 06:50:58 +00001579
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001580static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1581 // void *__dynamic_cast(const void *sub,
1582 // const abi::__class_type_info *src,
1583 // const abi::__class_type_info *dst,
1584 // std::ptrdiff_t src2dst_offset);
1585
Chris Lattner8b418682012-02-07 00:39:47 +00001586 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001587 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001588 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1589
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001590 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001591
Chris Lattner2acc6e32011-07-18 04:24:23 +00001592 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001593 llvm::FunctionType::get(Int8PtrTy, Args, false);
1594
1595 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1596}
1597
1598static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1599 // void __cxa_bad_cast();
Chris Lattner8b418682012-02-07 00:39:47 +00001600 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001601 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1602}
1603
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001604static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001605 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001606 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001607 CGF.Builder.CreateUnreachable();
1608}
1609
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001610static llvm::Value *
1611EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1612 QualType SrcTy, QualType DestTy,
1613 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001614 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001615 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001616 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001617
1618 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1619 if (PTy->getPointeeType()->isVoidType()) {
1620 // C++ [expr.dynamic.cast]p7:
1621 // If T is "pointer to cv void," then the result is a pointer to the
1622 // most derived object pointed to by v.
1623
1624 // Get the vtable pointer.
1625 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1626
1627 // Get the offset-to-top from the vtable.
1628 llvm::Value *OffsetToTop =
1629 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1630 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1631
1632 // Finally, add the offset to the pointer.
1633 Value = CGF.EmitCastToVoidPtr(Value);
1634 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1635
1636 return CGF.Builder.CreateBitCast(Value, DestLTy);
1637 }
1638 }
1639
1640 QualType SrcRecordTy;
1641 QualType DestRecordTy;
1642
1643 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1644 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1645 DestRecordTy = DestPTy->getPointeeType();
1646 } else {
1647 SrcRecordTy = SrcTy;
1648 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1649 }
1650
1651 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1652 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1653
1654 llvm::Value *SrcRTTI =
1655 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1656 llvm::Value *DestRTTI =
1657 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1658
1659 // FIXME: Actually compute a hint here.
1660 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1661
1662 // Emit the call to __dynamic_cast.
1663 Value = CGF.EmitCastToVoidPtr(Value);
1664 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1665 SrcRTTI, DestRTTI, OffsetHint);
1666 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1667
1668 /// C++ [expr.dynamic.cast]p9:
1669 /// A failed cast to reference type throws std::bad_cast
1670 if (DestTy->isReferenceType()) {
1671 llvm::BasicBlock *BadCastBlock =
1672 CGF.createBasicBlock("dynamic_cast.bad_cast");
1673
1674 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1675 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1676
1677 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001678 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001679 }
1680
1681 return Value;
1682}
1683
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001684static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1685 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001686 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001687 if (DestTy->isPointerType())
1688 return llvm::Constant::getNullValue(DestLTy);
1689
1690 /// C++ [expr.dynamic.cast]p9:
1691 /// A failed cast to reference type throws std::bad_cast
1692 EmitBadCastCall(CGF);
1693
1694 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1695 return llvm::UndefValue::get(DestLTy);
1696}
1697
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001698llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001699 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001700 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001701
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001702 if (DCE->isAlwaysNull())
1703 return EmitDynamicCastToNull(*this, DestTy);
1704
1705 QualType SrcTy = DCE->getSubExpr()->getType();
1706
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001707 // C++ [expr.dynamic.cast]p4:
1708 // If the value of v is a null pointer value in the pointer case, the result
1709 // is the null pointer value of type T.
1710 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001711
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001712 llvm::BasicBlock *CastNull = 0;
1713 llvm::BasicBlock *CastNotNull = 0;
1714 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001715
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001716 if (ShouldNullCheckSrcValue) {
1717 CastNull = createBasicBlock("dynamic_cast.null");
1718 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1719
1720 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1721 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1722 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001723 }
1724
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001725 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1726
1727 if (ShouldNullCheckSrcValue) {
1728 EmitBranch(CastEnd);
1729
1730 EmitBlock(CastNull);
1731 EmitBranch(CastEnd);
1732 }
1733
1734 EmitBlock(CastEnd);
1735
1736 if (ShouldNullCheckSrcValue) {
1737 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1738 PHI->addIncoming(Value, CastNotNull);
1739 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1740
1741 Value = PHI;
1742 }
1743
1744 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001745}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001746
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001747void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001748 RunCleanupsScope Scope(*this);
1749
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001750 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1751 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1752 e = E->capture_init_end();
1753 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001754 // Emit initialization
1755 LValue LV = EmitLValueForFieldInitialization(Slot.getAddr(), *CurField, 0);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001756 ArrayRef<VarDecl *> ArrayIndexes;
1757 if (CurField->getType()->isArrayType())
1758 ArrayIndexes = E->getCaptureInitIndexVars(i);
1759 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001760 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001761}