blob: 83c8ace98cd47f98a847eb917bb69a9f7e0f7316 [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
14#include "CodeGenFunction.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
19#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000020#include "llvm/IR/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,
Richard Smith4def70d2012-10-09 19:52:38 +000027 SourceLocation CallLoc,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000028 llvm::Value *Callee,
29 ReturnValueSlot ReturnValue,
30 llvm::Value *This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000031 llvm::Value *ImplicitParam,
32 QualType ImplicitParamTy,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000033 CallExpr::const_arg_iterator ArgBeg,
34 CallExpr::const_arg_iterator ArgEnd) {
35 assert(MD->isInstance() &&
36 "Trying to emit a member call expr on a static method!");
37
Richard Smith2c9f87c2012-08-24 00:54:33 +000038 // C++11 [class.mfct.non-static]p2:
39 // If a non-static member function of a class X is called for an object that
40 // is not of type X, or of a type derived from X, the behavior is undefined.
Richard Smith8e1cee62012-10-25 02:14:12 +000041 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
42 : TCK_MemberCall,
43 CallLoc, This, getContext().getRecordType(MD->getParent()));
Richard Smith2c9f87c2012-08-24 00:54:33 +000044
Anders Carlsson3b5ad222010-01-01 20:29:01 +000045 CallArgList Args;
46
47 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000048 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000049
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000050 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssonc997d422010-01-02 01:01:18 +000053 }
John McCallde5d3c72012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssonc997d422010-01-02 01:01:18 +000057
John McCallde5d3c72012-02-17 03:33:10 +000058 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000059 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
60
John McCall0f3d0972012-07-07 06:41:13 +000061 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000062 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000063}
64
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000065// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
66// quite what we want.
67static const Expr *skipNoOpCastsAndParens(const Expr *E) {
68 while (true) {
69 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
70 E = PE->getSubExpr();
71 continue;
72 }
73
74 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
75 if (CE->getCastKind() == CK_NoOp) {
76 E = CE->getSubExpr();
77 continue;
78 }
79 }
80 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
81 if (UO->getOpcode() == UO_Extension) {
82 E = UO->getSubExpr();
83 continue;
84 }
85 }
86 return E;
87 }
88}
89
Anders Carlsson3b5ad222010-01-01 20:29:01 +000090/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
91/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000092static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
93 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000094 const CXXMethodDecl *MD) {
95
Anders Carlsson1679f5a2011-01-29 03:52:01 +000096 // When building with -fapple-kext, all calls must go through the vtable since
97 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +000098 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000099 return false;
100
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000101 // If the most derived class is marked final, we know that no subclass can
102 // override this member function and so we can devirtualize it. For example:
103 //
104 // struct A { virtual void f(); }
105 // struct B final : A { };
106 //
107 // void f(B *b) {
108 // b->f();
109 // }
110 //
Rafael Espindola8d852e32012-06-27 18:18:05 +0000111 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000112 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
113 return true;
114
Anders Carlssonf89e0422011-01-23 21:07:30 +0000115 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000116 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000117 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000118 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000119
Anders Carlssonf89e0422011-01-23 21:07:30 +0000120 // Similarly, if the class itself is marked 'final' it can't be overridden
121 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000122 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000123 return true;
124
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000125 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000126 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
127 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
128 // This is a record decl. We know the type and can devirtualize it.
129 return VD->getType()->isRecordType();
130 }
131
132 return false;
133 }
Richard Smithac452932012-08-15 22:59:28 +0000134
135 // We can devirtualize calls on an object accessed by a class member access
136 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
137 // a derived class object constructed in the same location.
138 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
139 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
140 return VD->getType()->isRecordType();
141
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000143 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000144 return true;
145
146 // And calls on bound temporaries.
147 if (isa<CXXBindTemporaryExpr>(Base))
148 return true;
149
150 // Check if this is a call expr that returns a record type.
151 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
152 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000153
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000154 // We can't devirtualize the call.
155 return false;
156}
157
Rafael Espindolaea01d762012-06-28 14:28:57 +0000158static CXXRecordDecl *getCXXRecord(const Expr *E) {
159 QualType T = E->getType();
160 if (const PointerType *PTy = T->getAs<PointerType>())
161 T = PTy->getPointeeType();
162 const RecordType *Ty = T->castAs<RecordType>();
163 return cast<CXXRecordDecl>(Ty->getDecl());
164}
165
Francois Pichetdbee3412011-01-18 05:04:39 +0000166// Note: This function also emit constructor calls to support a MSVC
167// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
169 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000170 const Expr *callee = CE->getCallee()->IgnoreParens();
171
172 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000174
175 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
177
Devang Patelc69e1cf2010-09-30 19:05:55 +0000178 CGDebugInfo *DI = getDebugInfo();
Douglas Gregor4cdad312012-10-23 20:05:01 +0000179 if (DI &&
180 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo &&
181 !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-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 Carlsson3b5ad222010-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 Carlsson3b5ad222010-01-01 20:29:01 +0000195
John McCallfc400282010-09-03 01:26:39 +0000196 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000197 const Expr *Base = ME->getBase();
198 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000199
Rafael Espindolaea01d762012-06-28 14:28:57 +0000200 const CXXMethodDecl *DevirtualizedMethod = NULL;
201 if (CanUseVirtualCall &&
202 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
203 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
204 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
205 assert(DevirtualizedMethod);
206 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
207 const Expr *Inner = Base->ignoreParenBaseCasts();
208 if (getCXXRecord(Inner) == DevirtualizedClass)
209 // If the class of the Inner expression is where the dynamic method
210 // is defined, build the this pointer from it.
211 Base = Inner;
212 else if (getCXXRecord(Base) != DevirtualizedClass) {
213 // If the method is defined in a class that is not the best dynamic
214 // one or the one of the full expression, we would have to build
215 // a derived-to-base cast to compute the correct this pointer, but
216 // we don't have support for that yet, so do a virtual call.
217 DevirtualizedMethod = NULL;
218 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000219 // If the return types are not the same, this might be a case where more
220 // code needs to run to compensate for it. For example, the derived
221 // method might return a type that inherits form from the return
222 // type of MD and has a prefix.
223 // For now we just avoid devirtualizing these covariant cases.
224 if (DevirtualizedMethod &&
225 DevirtualizedMethod->getResultType().getCanonicalType() !=
226 MD->getResultType().getCanonicalType())
Rafael Espindola4a889e42012-06-28 15:11:39 +0000227 DevirtualizedMethod = NULL;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000228 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000229
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000230 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000231 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000232 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000233 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000234 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000235
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000236
John McCallfc400282010-09-03 01:26:39 +0000237 if (MD->isTrivial()) {
238 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000239 if (isa<CXXConstructorDecl>(MD) &&
240 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
241 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000242
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000243 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
244 // We don't like to generate the trivial copy/move assignment operator
245 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000246 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000247 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichetdbee3412011-01-18 05:04:39 +0000248 return RValue::get(This);
249 }
250
251 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000252 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
253 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000254 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
255 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
256 CE->arg_begin(), CE->arg_end());
257 return RValue::get(This);
258 }
259 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000260 }
261
John McCallfc400282010-09-03 01:26:39 +0000262 // Compute the function type we're calling.
Eli Friedman465e89e2012-10-25 00:12:49 +0000263 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Francois Pichetdbee3412011-01-18 05:04:39 +0000264 const CGFunctionInfo *FInfo = 0;
Eli Friedman465e89e2012-10-25 00:12:49 +0000265 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
266 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCallde5d3c72012-02-17 03:33:10 +0000267 Dtor_Complete);
Eli Friedman465e89e2012-10-25 00:12:49 +0000268 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
269 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
270 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000271 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000272 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000273
John McCallde5d3c72012-02-17 03:33:10 +0000274 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000275
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276 // C++ [class.virtual]p12:
277 // Explicit qualification with the scope operator (5.1) suppresses the
278 // virtual call mechanism.
279 //
280 // We also don't emit a virtual call if the base expression has a record type
281 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000282 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000283
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000285 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
286 if (UseVirtualCall) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000287 assert(CE->arg_begin() == CE->arg_end() &&
288 "Virtual destructor shouldn't have explicit parameters");
289 return CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor,
290 Dtor_Complete,
291 CE->getExprLoc(),
292 ReturnValue, This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000293 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000294 if (getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000295 MD->isVirtual() &&
296 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000297 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000298 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000299 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000300 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000301 const CXXDestructorDecl *DDtor =
302 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000303 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
304 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000305 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000306 } else if (const CXXConstructorDecl *Ctor =
307 dyn_cast<CXXConstructorDecl>(MD)) {
308 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000309 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000310 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000311 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000312 if (getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000313 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000314 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000315 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000316 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000317 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000318 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000319 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000320 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000321 }
322
Richard Smith4def70d2012-10-09 19:52:38 +0000323 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000324 /*ImplicitParam=*/0, QualType(),
325 CE->arg_begin(), CE->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326}
327
328RValue
329CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
330 ReturnValueSlot ReturnValue) {
331 const BinaryOperator *BO =
332 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
333 const Expr *BaseExpr = BO->getLHS();
334 const Expr *MemFnExpr = BO->getRHS();
335
336 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000337 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000338
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000339 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000340 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000341 const CXXRecordDecl *RD =
342 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
343
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000345 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000346
347 // Emit the 'this' pointer.
348 llvm::Value *This;
349
John McCall2de56d12010-08-25 11:45:40 +0000350 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000351 This = EmitScalarExpr(BaseExpr);
352 else
353 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000354
Richard Smith4def70d2012-10-09 19:52:38 +0000355 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
356 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000357
John McCall93d557b2010-08-22 00:05:51 +0000358 // Ask the ABI to load the callee. Note that This is modified.
359 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000360 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000361
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000362 CallArgList Args;
363
364 QualType ThisType =
365 getContext().getPointerType(getContext().getTagDeclType(RD));
366
367 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000368 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000369
370 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000371
372 // And the rest of the call args
373 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0f3d0972012-07-07 06:41:13 +0000374 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000375 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000376}
377
378RValue
379CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
380 const CXXMethodDecl *MD,
381 ReturnValueSlot ReturnValue) {
382 assert(MD->isInstance() &&
383 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000384 LValue LV = EmitLValue(E->getArg(0));
385 llvm::Value *This = LV.getAddress();
386
Douglas Gregorb2b56582011-09-06 16:26:56 +0000387 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
388 MD->isTrivial()) {
389 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
390 QualType Ty = E->getType();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000391 EmitAggregateAssign(This, Src, Ty);
Douglas Gregorb2b56582011-09-06 16:26:56 +0000392 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000393 }
394
Anders Carlssona2447e02011-05-08 20:32:23 +0000395 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smith4def70d2012-10-09 19:52:38 +0000396 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000397 /*ImplicitParam=*/0, QualType(),
398 E->arg_begin() + 1, E->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000399}
400
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000401RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
402 ReturnValueSlot ReturnValue) {
403 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
404}
405
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000406static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
407 llvm::Value *DestPtr,
408 const CXXRecordDecl *Base) {
409 if (Base->isEmpty())
410 return;
411
412 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
413
414 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
415 CharUnits Size = Layout.getNonVirtualSize();
416 CharUnits Align = Layout.getNonVirtualAlign();
417
418 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
419
420 // If the type contains a pointer to data member we can't memset it to zero.
421 // Instead, create a null constant and copy it to the destination.
422 // TODO: there are other patterns besides zero that we can usefully memset,
423 // like -1, which happens to be the pattern used by member-pointers.
424 // TODO: isZeroInitializable can be over-conservative in the case where a
425 // virtual base contains a member pointer.
426 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
427 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
428
429 llvm::GlobalVariable *NullVariable =
430 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
431 /*isConstant=*/true,
432 llvm::GlobalVariable::PrivateLinkage,
433 NullConstant, Twine());
434 NullVariable->setAlignment(Align.getQuantity());
435 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
436
437 // Get and call the appropriate llvm.memcpy overload.
438 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
439 return;
440 }
441
442 // Otherwise, just memset the whole thing to zero. This is legal
443 // because in LLVM, all default initializers (other than the ones we just
444 // handled above) are guaranteed to have a bit pattern of all zeros.
445 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
446 Align.getQuantity());
447}
448
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000449void
John McCall558d2ab2010-09-15 10:14:12 +0000450CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
451 AggValueSlot Dest) {
452 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000453 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000454
455 // If we require zero initialization before (or instead of) calling the
456 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000457 // constructor, emit the zero initialization now, unless destination is
458 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000459 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
460 switch (E->getConstructionKind()) {
461 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000462 case CXXConstructExpr::CK_Complete:
463 EmitNullInitialization(Dest.getAddr(), E->getType());
464 break;
465 case CXXConstructExpr::CK_VirtualBase:
466 case CXXConstructExpr::CK_NonVirtualBase:
467 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
468 break;
469 }
470 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000471
472 // If this is a call to a trivial default constructor, do nothing.
473 if (CD->isTrivial() && CD->isDefaultConstructor())
474 return;
475
John McCallfc1e6c72010-09-18 00:58:34 +0000476 // Elide the constructor if we're constructing from a temporary.
477 // The temporary check is required because Sema sets this on NRVO
478 // returns.
Richard Smith7edf9e32012-11-01 22:30:59 +0000479 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000480 assert(getContext().hasSameUnqualifiedType(E->getType(),
481 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000482 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
483 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000484 return;
485 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000486 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000487
John McCallc3c07662011-07-13 06:10:41 +0000488 if (const ConstantArrayType *arrayType
489 = getContext().getAsConstantArrayType(E->getType())) {
490 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000491 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000492 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000493 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000494 bool ForVirtualBase = false;
Douglas Gregor378e1e72013-01-31 05:50:40 +0000495 bool Delegating = false;
496
Sean Huntd49bd552011-05-03 20:19:28 +0000497 switch (E->getConstructionKind()) {
498 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000499 // We should be emitting a constructor; GlobalDecl will assert this
500 Type = CurGD.getCtorType();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000501 Delegating = true;
Sean Huntd49bd552011-05-03 20:19:28 +0000502 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000503
Sean Huntd49bd552011-05-03 20:19:28 +0000504 case CXXConstructExpr::CK_Complete:
505 Type = Ctor_Complete;
506 break;
507
508 case CXXConstructExpr::CK_VirtualBase:
509 ForVirtualBase = true;
510 // fall-through
511
512 case CXXConstructExpr::CK_NonVirtualBase:
513 Type = Ctor_Base;
514 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000515
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000516 // Call the constructor.
Douglas Gregor378e1e72013-01-31 05:50:40 +0000517 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000518 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000519 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000520}
521
Fariborz Jahanian34999872010-11-13 21:53:34 +0000522void
523CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
524 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000525 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000526 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000527 Exp = E->getSubExpr();
528 assert(isa<CXXConstructExpr>(Exp) &&
529 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
530 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
531 const CXXConstructorDecl *CD = E->getConstructor();
532 RunCleanupsScope Scope(*this);
533
534 // If we require zero initialization before (or instead of) calling the
535 // constructor, as can be the case with a non-user-provided default
536 // constructor, emit the zero initialization now.
537 // FIXME. Do I still need this for a copy ctor synthesis?
538 if (E->requiresZeroInitialization())
539 EmitNullInitialization(Dest, E->getType());
540
Chandler Carruth858a5462010-11-15 13:54:43 +0000541 assert(!getContext().getAsConstantArrayType(E->getType())
542 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000543 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
544 E->arg_begin(), E->arg_end());
545}
546
John McCall1e7fe752010-09-02 09:58:18 +0000547static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
548 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000549 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000550 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000551
John McCallb1c98a32011-05-16 01:05:12 +0000552 // No cookie is required if the operator new[] being used is the
553 // reserved placement operator new[].
554 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000555 return CharUnits::Zero();
556
John McCall6ec278d2011-01-27 09:37:56 +0000557 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000558}
559
John McCall7d166272011-05-15 07:14:44 +0000560static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
561 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000562 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000563 llvm::Value *&numElements,
564 llvm::Value *&sizeWithoutCookie) {
565 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000566
John McCall7d166272011-05-15 07:14:44 +0000567 if (!e->isArray()) {
568 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
569 sizeWithoutCookie
570 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
571 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000572 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000573
John McCall7d166272011-05-15 07:14:44 +0000574 // The width of size_t.
575 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
576
John McCall1e7fe752010-09-02 09:58:18 +0000577 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000578 llvm::APInt cookieSize(sizeWidth,
579 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000580
Anders Carlssona4d4c012009-09-23 16:07:23 +0000581 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000582 // We multiply the size of all dimensions for NumElements.
583 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000584 numElements = CGF.EmitScalarExpr(e->getArraySize());
585 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000586
John McCall7d166272011-05-15 07:14:44 +0000587 // The number of elements can be have an arbitrary integer type;
588 // essentially, we need to multiply it by a constant factor, add a
589 // cookie size, and verify that the result is representable as a
590 // size_t. That's just a gloss, though, and it's wrong in one
591 // important way: if the count is negative, it's an error even if
592 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000593 bool isSigned
594 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000595 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000596 = cast<llvm::IntegerType>(numElements->getType());
597 unsigned numElementsWidth = numElementsType->getBitWidth();
598
599 // Compute the constant factor.
600 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000601 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000602 = CGF.getContext().getAsConstantArrayType(type)) {
603 type = CAT->getElementType();
604 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000605 }
606
John McCall7d166272011-05-15 07:14:44 +0000607 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
608 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
609 typeSizeMultiplier *= arraySizeMultiplier;
610
611 // This will be a size_t.
612 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000613
Chris Lattner806941e2010-07-20 21:55:52 +0000614 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
615 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000616 if (llvm::ConstantInt *numElementsC =
617 dyn_cast<llvm::ConstantInt>(numElements)) {
618 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000619
John McCall7d166272011-05-15 07:14:44 +0000620 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000621
John McCall7d166272011-05-15 07:14:44 +0000622 // If 'count' was a negative number, it's an overflow.
623 if (isSigned && count.isNegative())
624 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000625
John McCall7d166272011-05-15 07:14:44 +0000626 // We want to do all this arithmetic in size_t. If numElements is
627 // wider than that, check whether it's already too big, and if so,
628 // overflow.
629 else if (numElementsWidth > sizeWidth &&
630 numElementsWidth - sizeWidth > count.countLeadingZeros())
631 hasAnyOverflow = true;
632
633 // Okay, compute a count at the right width.
634 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
635
Sebastian Redl92036472012-02-22 17:37:52 +0000636 // If there is a brace-initializer, we cannot allocate fewer elements than
637 // there are initializers. If we do, that's treated like an overflow.
638 if (adjustedCount.ult(minElements))
639 hasAnyOverflow = true;
640
John McCall7d166272011-05-15 07:14:44 +0000641 // Scale numElements by that. This might overflow, but we don't
642 // care because it only overflows if allocationSize does, too, and
643 // if that overflows then we shouldn't use this.
644 numElements = llvm::ConstantInt::get(CGF.SizeTy,
645 adjustedCount * arraySizeMultiplier);
646
647 // Compute the size before cookie, and track whether it overflowed.
648 bool overflow;
649 llvm::APInt allocationSize
650 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
651 hasAnyOverflow |= overflow;
652
653 // Add in the cookie, and check whether it's overflowed.
654 if (cookieSize != 0) {
655 // Save the current size without a cookie. This shouldn't be
656 // used if there was overflow.
657 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
658
659 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
660 hasAnyOverflow |= overflow;
661 }
662
663 // On overflow, produce a -1 so operator new will fail.
664 if (hasAnyOverflow) {
665 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
666 } else {
667 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
668 }
669
670 // Otherwise, we might need to use the overflow intrinsics.
671 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000672 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000673 // 1) if isSigned, we need to check whether numElements is negative;
674 // 2) if numElementsWidth > sizeWidth, we need to check whether
675 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000676 // 3) if minElements > 0, we need to check whether numElements is smaller
677 // than that.
678 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000679 // sizeWithoutCookie := numElements * typeSizeMultiplier
680 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000681 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000682 // size := sizeWithoutCookie + cookieSize
683 // and check whether it overflows.
684
685 llvm::Value *hasOverflow = 0;
686
687 // If numElementsWidth > sizeWidth, then one way or another, we're
688 // going to have to do a comparison for (2), and this happens to
689 // take care of (1), too.
690 if (numElementsWidth > sizeWidth) {
691 llvm::APInt threshold(numElementsWidth, 1);
692 threshold <<= sizeWidth;
693
694 llvm::Value *thresholdV
695 = llvm::ConstantInt::get(numElementsType, threshold);
696
697 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
698 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
699
700 // Otherwise, if we're signed, we want to sext up to size_t.
701 } else if (isSigned) {
702 if (numElementsWidth < sizeWidth)
703 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
704
705 // If there's a non-1 type size multiplier, then we can do the
706 // signedness check at the same time as we do the multiply
707 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000708 // unsigned overflow. Otherwise, we have to do it here. But at least
709 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000710 if (typeSizeMultiplier == 1)
711 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000712 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000713
714 // Otherwise, zext up to size_t if necessary.
715 } else if (numElementsWidth < sizeWidth) {
716 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
717 }
718
719 assert(numElements->getType() == CGF.SizeTy);
720
Sebastian Redl92036472012-02-22 17:37:52 +0000721 if (minElements) {
722 // Don't allow allocation of fewer elements than we have initializers.
723 if (!hasOverflow) {
724 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
725 llvm::ConstantInt::get(CGF.SizeTy, minElements));
726 } else if (numElementsWidth > sizeWidth) {
727 // The other existing overflow subsumes this check.
728 // We do an unsigned comparison, since any signed value < -1 is
729 // taken care of either above or below.
730 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
731 CGF.Builder.CreateICmpULT(numElements,
732 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
733 }
734 }
735
John McCall7d166272011-05-15 07:14:44 +0000736 size = numElements;
737
738 // Multiply by the type size if necessary. This multiplier
739 // includes all the factors for nested arrays.
740 //
741 // This step also causes numElements to be scaled up by the
742 // nested-array factor if necessary. Overflow on this computation
743 // can be ignored because the result shouldn't be used if
744 // allocation fails.
745 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000746 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000747 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000748
749 llvm::Value *tsmV =
750 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
751 llvm::Value *result =
752 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
753
754 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
755 if (hasOverflow)
756 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
757 else
758 hasOverflow = overflowed;
759
760 size = CGF.Builder.CreateExtractValue(result, 0);
761
762 // Also scale up numElements by the array size multiplier.
763 if (arraySizeMultiplier != 1) {
764 // If the base element type size is 1, then we can re-use the
765 // multiply we just did.
766 if (typeSize.isOne()) {
767 assert(arraySizeMultiplier == typeSizeMultiplier);
768 numElements = size;
769
770 // Otherwise we need a separate multiply.
771 } else {
772 llvm::Value *asmV =
773 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
774 numElements = CGF.Builder.CreateMul(numElements, asmV);
775 }
776 }
777 } else {
778 // numElements doesn't need to be scaled.
779 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000780 }
781
John McCall7d166272011-05-15 07:14:44 +0000782 // Add in the cookie size if necessary.
783 if (cookieSize != 0) {
784 sizeWithoutCookie = size;
785
John McCall7d166272011-05-15 07:14:44 +0000786 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000787 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000788
789 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
790 llvm::Value *result =
791 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
792
793 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
794 if (hasOverflow)
795 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
796 else
797 hasOverflow = overflowed;
798
799 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000800 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000801
John McCall7d166272011-05-15 07:14:44 +0000802 // If we had any possibility of dynamic overflow, make a select to
803 // overwrite 'size' with an all-ones value, which should cause
804 // operator new to throw.
805 if (hasOverflow)
806 size = CGF.Builder.CreateSelect(hasOverflow,
807 llvm::Constant::getAllOnesValue(CGF.SizeTy),
808 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000809 }
John McCall1e7fe752010-09-02 09:58:18 +0000810
John McCall7d166272011-05-15 07:14:44 +0000811 if (cookieSize == 0)
812 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000813 else
John McCall7d166272011-05-15 07:14:44 +0000814 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000815
John McCall7d166272011-05-15 07:14:44 +0000816 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000817}
818
Sebastian Redl92036472012-02-22 17:37:52 +0000819static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
820 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000821
Eli Friedmand7722d92011-12-03 02:13:40 +0000822 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall9d232c82013-03-07 21:37:08 +0000823 switch (CGF.getEvaluationKind(AllocType)) {
824 case TEK_Scalar:
Eli Friedmand7722d92011-12-03 02:13:40 +0000825 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000826 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000827 false);
John McCall9d232c82013-03-07 21:37:08 +0000828 return;
829 case TEK_Complex:
830 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
831 Alignment),
832 /*isInit*/ true);
833 return;
834 case TEK_Aggregate: {
John McCall558d2ab2010-09-15 10:14:12 +0000835 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000836 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000837 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000838 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000839 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000840 CGF.EmitAggExpr(Init, Slot);
Sebastian Redl972edf02012-02-19 16:03:09 +0000841
842 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall9d232c82013-03-07 21:37:08 +0000843 return;
John McCall558d2ab2010-09-15 10:14:12 +0000844 }
John McCall9d232c82013-03-07 21:37:08 +0000845 }
846 llvm_unreachable("bad evaluation kind");
Fariborz Jahanianef668722010-06-25 18:26:07 +0000847}
848
849void
850CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000851 QualType elementType,
852 llvm::Value *beginPtr,
853 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000854 if (!E->hasInitializer())
855 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000856
Sebastian Redl92036472012-02-22 17:37:52 +0000857 llvm::Value *explicitPtr = beginPtr;
John McCall19705672011-09-15 06:49:18 +0000858 // Find the end of the array, hoisted out of the loop.
859 llvm::Value *endPtr =
860 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
861
Sebastian Redl92036472012-02-22 17:37:52 +0000862 unsigned initializerElements = 0;
863
864 const Expr *Init = E->getInitializer();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000865 llvm::AllocaInst *endOfInit = 0;
866 QualType::DestructionKind dtorKind = elementType.isDestructedType();
867 EHScopeStack::stable_iterator cleanup;
868 llvm::Instruction *cleanupDominator = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000869 // If the initializer is an initializer list, first do the explicit elements.
870 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
871 initializerElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000872
873 // Enter a partial-destruction cleanup if necessary.
874 if (needsEHCleanup(dtorKind)) {
875 // In principle we could tell the cleanup where we are more
876 // directly, but the control flow can get so varied here that it
877 // would actually be quite complex. Therefore we go through an
878 // alloca.
879 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
880 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
881 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
882 getDestroyer(dtorKind));
883 cleanup = EHStack.stable_begin();
884 }
885
Sebastian Redl92036472012-02-22 17:37:52 +0000886 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000887 // Tell the cleanup that it needs to destroy up to this
888 // element. TODO: some of these stores can be trivially
889 // observed to be unnecessary.
890 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redl92036472012-02-22 17:37:52 +0000891 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
892 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
893 }
894
895 // The remaining elements are filled with the array filler expression.
896 Init = ILE->getArrayFiller();
897 }
898
John McCall19705672011-09-15 06:49:18 +0000899 // Create the continuation block.
900 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
901
Sebastian Redl92036472012-02-22 17:37:52 +0000902 // If the number of elements isn't constant, we have to now check if there is
903 // anything left to initialize.
904 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
905 // If all elements have already been initialized, skip the whole loop.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000906 if (constNum->getZExtValue() <= initializerElements) {
907 // If there was a cleanup, deactivate it.
908 if (cleanupDominator)
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +0000909 DeactivateCleanupBlock(cleanup, cleanupDominator);
Chad Rosier577fb5b2012-02-24 00:13:55 +0000910 return;
911 }
Sebastian Redl92036472012-02-22 17:37:52 +0000912 } else {
John McCall19705672011-09-15 06:49:18 +0000913 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redl92036472012-02-22 17:37:52 +0000914 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall19705672011-09-15 06:49:18 +0000915 "array.isempty");
916 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
917 EmitBlock(nonEmptyBB);
918 }
919
920 // Enter the loop.
921 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
922 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
923
924 EmitBlock(loopBB);
925
926 // Set up the current-element phi.
927 llvm::PHINode *curPtr =
Sebastian Redl92036472012-02-22 17:37:52 +0000928 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
929 curPtr->addIncoming(explicitPtr, entryBB);
John McCall19705672011-09-15 06:49:18 +0000930
Chad Rosier577fb5b2012-02-24 00:13:55 +0000931 // Store the new cleanup position for irregular cleanups.
932 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
933
John McCall19705672011-09-15 06:49:18 +0000934 // Enter a partial-destruction cleanup if necessary.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000935 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall19705672011-09-15 06:49:18 +0000936 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
937 getDestroyer(dtorKind));
938 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000939 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000940 }
941
942 // Emit the initializer into this element.
Sebastian Redl92036472012-02-22 17:37:52 +0000943 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall19705672011-09-15 06:49:18 +0000944
945 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000946 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000947 DeactivateCleanupBlock(cleanup, cleanupDominator);
948 cleanupDominator->eraseFromParent();
949 }
John McCall19705672011-09-15 06:49:18 +0000950
951 // Advance to the next element.
952 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
953
954 // Check whether we've gotten to the end of the array and, if so,
955 // exit the loop.
956 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
957 Builder.CreateCondBr(isEnd, contBB, loopBB);
958 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
959
960 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000961}
962
Douglas Gregor59174c02010-07-21 01:10:17 +0000963static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
964 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000965 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000966 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000967 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000968 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000969}
970
Anders Carlssona4d4c012009-09-23 16:07:23 +0000971static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000972 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000973 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000974 llvm::Value *NumElements,
975 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000976 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000977 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000978 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
979 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor887ddf32012-02-23 17:07:43 +0000980 if (Ctor->isTrivial()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000981 // If new expression did not specify value-initialization, then there
982 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000983 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000984 return;
985
John McCall19705672011-09-15 06:49:18 +0000986 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000987 // Optimization: since zero initialization will just set the memory
988 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000989 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000990 return;
991 }
Douglas Gregor59174c02010-07-21 01:10:17 +0000992 }
John McCallc3c07662011-07-13 06:10:41 +0000993
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000994 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
995 CCE->arg_begin(), CCE->arg_end(),
Eli Friedmanb41ba1a2012-08-25 07:11:29 +0000996 CCE->requiresZeroInitialization());
Anders Carlssone99bdb62010-05-03 15:09:17 +0000997 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000998 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000999 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +00001000 // Optimization: since zero initialization will just set the memory
1001 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +00001002 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
1003 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +00001004 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001005 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
1006 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +00001007 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +00001008
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001009 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +00001010 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001011
Sebastian Redl92036472012-02-22 17:37:52 +00001012 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001013}
1014
John McCall7d8647f2010-09-14 07:57:04 +00001015namespace {
1016 /// A cleanup to call the given 'operator delete' function upon
1017 /// abnormal exit from a new expression.
1018 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1019 size_t NumPlacementArgs;
1020 const FunctionDecl *OperatorDelete;
1021 llvm::Value *Ptr;
1022 llvm::Value *AllocSize;
1023
1024 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1025
1026 public:
1027 static size_t getExtraSize(size_t NumPlacementArgs) {
1028 return NumPlacementArgs * sizeof(RValue);
1029 }
1030
1031 CallDeleteDuringNew(size_t NumPlacementArgs,
1032 const FunctionDecl *OperatorDelete,
1033 llvm::Value *Ptr,
1034 llvm::Value *AllocSize)
1035 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1036 Ptr(Ptr), AllocSize(AllocSize) {}
1037
1038 void setPlacementArg(unsigned I, RValue Arg) {
1039 assert(I < NumPlacementArgs && "index out of range");
1040 getPlacementArgs()[I] = Arg;
1041 }
1042
John McCallad346f42011-07-12 20:27:29 +00001043 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +00001044 const FunctionProtoType *FPT
1045 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1046 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +00001047 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001048
1049 CallArgList DeleteArgs;
1050
1051 // The first argument is always a void*.
1052 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001053 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001054
1055 // A member 'operator delete' can take an extra 'size_t' argument.
1056 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001057 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001058
1059 // Pass the rest of the arguments, which must match exactly.
1060 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001061 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001062
1063 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001064 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +00001065 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1066 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1067 }
1068 };
John McCall3019c442010-09-17 00:50:28 +00001069
1070 /// A cleanup to call the given 'operator delete' function upon
1071 /// abnormal exit from a new expression when the new expression is
1072 /// conditional.
1073 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1074 size_t NumPlacementArgs;
1075 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001076 DominatingValue<RValue>::saved_type Ptr;
1077 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001078
John McCall804b8072011-01-28 10:53:53 +00001079 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1080 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001081 }
1082
1083 public:
1084 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001085 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001086 }
1087
1088 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1089 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001090 DominatingValue<RValue>::saved_type Ptr,
1091 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001092 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1093 Ptr(Ptr), AllocSize(AllocSize) {}
1094
John McCall804b8072011-01-28 10:53:53 +00001095 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001096 assert(I < NumPlacementArgs && "index out of range");
1097 getPlacementArgs()[I] = Arg;
1098 }
1099
John McCallad346f42011-07-12 20:27:29 +00001100 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +00001101 const FunctionProtoType *FPT
1102 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1103 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1104 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1105
1106 CallArgList DeleteArgs;
1107
1108 // The first argument is always a void*.
1109 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001110 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001111
1112 // A member 'operator delete' can take an extra 'size_t' argument.
1113 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001114 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001115 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001116 }
1117
1118 // Pass the rest of the arguments, which must match exactly.
1119 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001120 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001121 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001122 }
1123
1124 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001125 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +00001126 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1127 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1128 }
1129 };
1130}
1131
1132/// Enter a cleanup to call 'operator delete' if the initializer in a
1133/// new-expression throws.
1134static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1135 const CXXNewExpr *E,
1136 llvm::Value *NewPtr,
1137 llvm::Value *AllocSize,
1138 const CallArgList &NewArgs) {
1139 // If we're not inside a conditional branch, then the cleanup will
1140 // dominate and we can do the easier (and more efficient) thing.
1141 if (!CGF.isInConditionalBranch()) {
1142 CallDeleteDuringNew *Cleanup = CGF.EHStack
1143 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1144 E->getNumPlacementArgs(),
1145 E->getOperatorDelete(),
1146 NewPtr, AllocSize);
1147 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001148 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001149
1150 return;
1151 }
1152
1153 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001154 DominatingValue<RValue>::saved_type SavedNewPtr =
1155 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1156 DominatingValue<RValue>::saved_type SavedAllocSize =
1157 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001158
1159 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001160 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001161 E->getNumPlacementArgs(),
1162 E->getOperatorDelete(),
1163 SavedNewPtr,
1164 SavedAllocSize);
1165 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001166 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001167 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001168
John McCall6f103ba2011-11-10 10:43:54 +00001169 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001170}
1171
Anders Carlsson16d81b82009-09-22 22:53:17 +00001172llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001173 // The element type being allocated.
1174 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001175
John McCallc2f3e7f2011-03-07 03:12:35 +00001176 // 1. Build a call to the allocation function.
1177 FunctionDecl *allocator = E->getOperatorNew();
1178 const FunctionProtoType *allocatorType =
1179 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001180
John McCallc2f3e7f2011-03-07 03:12:35 +00001181 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001182
1183 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001184 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001185
Sebastian Redl92036472012-02-22 17:37:52 +00001186 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1187 unsigned minElements = 0;
1188 if (E->isArray() && E->hasInitializer()) {
1189 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1190 minElements = ILE->getNumInits();
1191 }
1192
John McCallc2f3e7f2011-03-07 03:12:35 +00001193 llvm::Value *numElements = 0;
1194 llvm::Value *allocSizeWithoutCookie = 0;
1195 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001196 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1197 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001198
Eli Friedman04c9a492011-05-02 17:57:46 +00001199 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001200
1201 // Emit the rest of the arguments.
1202 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001203 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001204
1205 // First, use the types from the function type.
1206 // We start at 1 here because the first argument (the allocation size)
1207 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001208 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1209 ++i, ++placementArg) {
1210 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001211
John McCallc2f3e7f2011-03-07 03:12:35 +00001212 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1213 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001214 "type mismatch in call argument!");
1215
John McCall413ebdb2011-03-11 20:59:21 +00001216 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001217 }
1218
1219 // Either we've emitted all the call args, or we have a call to a
1220 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001221 assert((placementArg == E->placement_arg_end() ||
1222 allocatorType->isVariadic()) &&
1223 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001224
1225 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001226 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1227 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001228 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001229 }
1230
John McCallb1c98a32011-05-16 01:05:12 +00001231 // Emit the allocation call. If the allocator is a global placement
1232 // operator, just "inline" it directly.
1233 RValue RV;
1234 if (allocator->isReservedGlobalPlacementOperator()) {
1235 assert(allocatorArgs.size() == 2);
1236 RV = allocatorArgs[1].RV;
1237 // TODO: kill any unnecessary computations done for the size
1238 // argument.
1239 } else {
John McCall0f3d0972012-07-07 06:41:13 +00001240 RV = EmitCall(CGM.getTypes().arrangeFreeFunctionCall(allocatorArgs,
1241 allocatorType),
John McCallb1c98a32011-05-16 01:05:12 +00001242 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1243 allocatorArgs, allocator);
1244 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001245
John McCallc2f3e7f2011-03-07 03:12:35 +00001246 // Emit a null check on the allocation result if the allocation
1247 // function is allowed to return null (because it has a non-throwing
1248 // exception spec; for this part, we inline
1249 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1250 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001251 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001252 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001253
John McCallc2f3e7f2011-03-07 03:12:35 +00001254 llvm::BasicBlock *nullCheckBB = 0;
1255 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001256
John McCallc2f3e7f2011-03-07 03:12:35 +00001257 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001258 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001259
John McCalla7f633f2011-03-07 01:52:56 +00001260 // The null-check means that the initializer is conditionally
1261 // evaluated.
1262 ConditionalEvaluation conditional(*this);
1263
John McCallc2f3e7f2011-03-07 03:12:35 +00001264 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001265 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001266
1267 nullCheckBB = Builder.GetInsertBlock();
1268 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1269 contBB = createBasicBlock("new.cont");
1270
1271 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1272 Builder.CreateCondBr(isNull, contBB, notNullBB);
1273 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001274 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001275
John McCall7d8647f2010-09-14 07:57:04 +00001276 // If there's an operator delete, enter a cleanup to call it if an
1277 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001278 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001279 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001280 if (E->getOperatorDelete() &&
1281 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001282 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1283 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001284 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001285 }
1286
Eli Friedman576cf172011-09-06 18:53:03 +00001287 assert((allocSize == allocSizeWithoutCookie) ==
1288 CalculateCookiePadding(*this, E).isZero());
1289 if (allocSize != allocSizeWithoutCookie) {
1290 assert(E->isArray());
1291 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1292 numElements,
1293 E, allocType);
1294 }
1295
Chris Lattner2acc6e32011-07-18 04:24:23 +00001296 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001297 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1298 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001299
John McCall19705672011-09-15 06:49:18 +00001300 EmitNewInitializer(*this, E, allocType, result, numElements,
1301 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001302 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001303 // NewPtr is a pointer to the base element type. If we're
1304 // allocating an array of arrays, we'll need to cast back to the
1305 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001306 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001307 if (result->getType() != resultType)
1308 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001309 }
John McCall7d8647f2010-09-14 07:57:04 +00001310
1311 // Deactivate the 'operator delete' cleanup if we finished
1312 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001313 if (operatorDeleteCleanup.isValid()) {
1314 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1315 cleanupDominator->eraseFromParent();
1316 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001317
John McCallc2f3e7f2011-03-07 03:12:35 +00001318 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001319 conditional.end(*this);
1320
John McCallc2f3e7f2011-03-07 03:12:35 +00001321 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1322 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001323
Jay Foadbbf3bac2011-03-30 11:28:58 +00001324 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001325 PHI->addIncoming(result, notNullBB);
1326 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1327 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001328
John McCallc2f3e7f2011-03-07 03:12:35 +00001329 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001330 }
John McCall1e7fe752010-09-02 09:58:18 +00001331
John McCallc2f3e7f2011-03-07 03:12:35 +00001332 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001333}
1334
Eli Friedman5fe05982009-11-18 00:50:08 +00001335void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1336 llvm::Value *Ptr,
1337 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001338 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1339
Eli Friedman5fe05982009-11-18 00:50:08 +00001340 const FunctionProtoType *DeleteFTy =
1341 DeleteFD->getType()->getAs<FunctionProtoType>();
1342
1343 CallArgList DeleteArgs;
1344
Anders Carlsson871d0782009-12-13 20:04:38 +00001345 // Check if we need to pass the size to the delete operator.
1346 llvm::Value *Size = 0;
1347 QualType SizeTy;
1348 if (DeleteFTy->getNumArgs() == 2) {
1349 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001350 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1351 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1352 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001353 }
1354
Eli Friedman5fe05982009-11-18 00:50:08 +00001355 QualType ArgTy = DeleteFTy->getArgType(0);
1356 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001357 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001358
Anders Carlsson871d0782009-12-13 20:04:38 +00001359 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001360 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001361
1362 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001363 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001364 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001365 DeleteArgs, DeleteFD);
1366}
1367
John McCall1e7fe752010-09-02 09:58:18 +00001368namespace {
1369 /// Calls the given 'operator delete' on a single object.
1370 struct CallObjectDelete : EHScopeStack::Cleanup {
1371 llvm::Value *Ptr;
1372 const FunctionDecl *OperatorDelete;
1373 QualType ElementType;
1374
1375 CallObjectDelete(llvm::Value *Ptr,
1376 const FunctionDecl *OperatorDelete,
1377 QualType ElementType)
1378 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1379
John McCallad346f42011-07-12 20:27:29 +00001380 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001381 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1382 }
1383 };
1384}
1385
1386/// Emit the code for deleting a single object.
1387static void EmitObjectDelete(CodeGenFunction &CGF,
1388 const FunctionDecl *OperatorDelete,
1389 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001390 QualType ElementType,
1391 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001392 // Find the destructor for the type, if applicable. If the
1393 // destructor is virtual, we'll just emit the vcall and return.
1394 const CXXDestructorDecl *Dtor = 0;
1395 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1396 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001397 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001398 Dtor = RD->getDestructor();
1399
1400 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001401 if (UseGlobalDelete) {
1402 // If we're supposed to call the global delete, make sure we do so
1403 // even if the destructor throws.
John McCallecd03b42012-09-25 10:10:39 +00001404
1405 // Derive the complete-object pointer, which is what we need
1406 // to pass to the deallocation function.
1407 llvm::Value *completePtr =
1408 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1409
Douglas Gregora8b20f72011-07-13 00:54:47 +00001410 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCallecd03b42012-09-25 10:10:39 +00001411 completePtr, OperatorDelete,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001412 ElementType);
1413 }
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001414
Richard Smith4def70d2012-10-09 19:52:38 +00001415 // FIXME: Provide a source location here.
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001416 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1417 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType,
1418 SourceLocation(),
1419 ReturnValueSlot(), Ptr);
John McCall1e7fe752010-09-02 09:58:18 +00001420
Douglas Gregora8b20f72011-07-13 00:54:47 +00001421 if (UseGlobalDelete) {
1422 CGF.PopCleanupBlock();
1423 }
1424
John McCall1e7fe752010-09-02 09:58:18 +00001425 return;
1426 }
1427 }
1428 }
1429
1430 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001431 // This doesn't have to a conditional cleanup because we're going
1432 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001433 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1434 Ptr, OperatorDelete, ElementType);
1435
1436 if (Dtor)
1437 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001438 /*ForVirtualBase=*/false,
1439 /*Delegating=*/false,
1440 Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001441 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001442 ElementType->isObjCLifetimeType()) {
1443 switch (ElementType.getObjCLifetime()) {
1444 case Qualifiers::OCL_None:
1445 case Qualifiers::OCL_ExplicitNone:
1446 case Qualifiers::OCL_Autoreleasing:
1447 break;
John McCall1e7fe752010-09-02 09:58:18 +00001448
John McCallf85e1932011-06-15 23:02:42 +00001449 case Qualifiers::OCL_Strong: {
1450 // Load the pointer value.
1451 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1452 ElementType.isVolatileQualified());
1453
John McCall5b07e802013-03-13 03:10:54 +00001454 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001455 break;
1456 }
1457
1458 case Qualifiers::OCL_Weak:
1459 CGF.EmitARCDestroyWeak(Ptr);
1460 break;
1461 }
1462 }
1463
John McCall1e7fe752010-09-02 09:58:18 +00001464 CGF.PopCleanupBlock();
1465}
1466
1467namespace {
1468 /// Calls the given 'operator delete' on an array of objects.
1469 struct CallArrayDelete : EHScopeStack::Cleanup {
1470 llvm::Value *Ptr;
1471 const FunctionDecl *OperatorDelete;
1472 llvm::Value *NumElements;
1473 QualType ElementType;
1474 CharUnits CookieSize;
1475
1476 CallArrayDelete(llvm::Value *Ptr,
1477 const FunctionDecl *OperatorDelete,
1478 llvm::Value *NumElements,
1479 QualType ElementType,
1480 CharUnits CookieSize)
1481 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1482 ElementType(ElementType), CookieSize(CookieSize) {}
1483
John McCallad346f42011-07-12 20:27:29 +00001484 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001485 const FunctionProtoType *DeleteFTy =
1486 OperatorDelete->getType()->getAs<FunctionProtoType>();
1487 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1488
1489 CallArgList Args;
1490
1491 // Pass the pointer as the first argument.
1492 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1493 llvm::Value *DeletePtr
1494 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001495 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001496
1497 // Pass the original requested size as the second argument.
1498 if (DeleteFTy->getNumArgs() == 2) {
1499 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001500 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001501 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1502
1503 CharUnits ElementTypeSize =
1504 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1505
1506 // The size of an element, multiplied by the number of elements.
1507 llvm::Value *Size
1508 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1509 Size = CGF.Builder.CreateMul(Size, NumElements);
1510
1511 // Plus the size of the cookie if applicable.
1512 if (!CookieSize.isZero()) {
1513 llvm::Value *CookieSizeV
1514 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1515 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1516 }
1517
Eli Friedman04c9a492011-05-02 17:57:46 +00001518 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001519 }
1520
1521 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001522 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001523 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1524 ReturnValueSlot(), Args, OperatorDelete);
1525 }
1526 };
1527}
1528
1529/// Emit the code for deleting an array of objects.
1530static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001531 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001532 llvm::Value *deletedPtr,
1533 QualType elementType) {
1534 llvm::Value *numElements = 0;
1535 llvm::Value *allocatedPtr = 0;
1536 CharUnits cookieSize;
1537 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1538 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001539
John McCall7cfd76c2011-07-13 01:41:37 +00001540 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001541
1542 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001543 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001544 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001545 allocatedPtr, operatorDelete,
1546 numElements, elementType,
1547 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001548
John McCall7cfd76c2011-07-13 01:41:37 +00001549 // Destroy the elements.
1550 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1551 assert(numElements && "no element count for a type with a destructor!");
1552
John McCall7cfd76c2011-07-13 01:41:37 +00001553 llvm::Value *arrayEnd =
1554 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001555
1556 // Note that it is legal to allocate a zero-length array, and we
1557 // can never fold the check away because the length should always
1558 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001559 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1560 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001561 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001562 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001563 }
1564
John McCall7cfd76c2011-07-13 01:41:37 +00001565 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001566 CGF.PopCleanupBlock();
1567}
1568
Anders Carlsson16d81b82009-09-22 22:53:17 +00001569void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001570 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001571 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001572
1573 // Null check the pointer.
1574 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1575 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1576
Anders Carlssonb9241242011-04-11 00:30:07 +00001577 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001578
1579 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1580 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001581
John McCall1e7fe752010-09-02 09:58:18 +00001582 // We might be deleting a pointer to array. If so, GEP down to the
1583 // first non-array element.
1584 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1585 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1586 if (DeleteTy->isConstantArrayType()) {
1587 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001588 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001589
1590 GEP.push_back(Zero); // point at the outermost array
1591
1592 // For each layer of array type we're pointing at:
1593 while (const ConstantArrayType *Arr
1594 = getContext().getAsConstantArrayType(DeleteTy)) {
1595 // 1. Unpeel the array type.
1596 DeleteTy = Arr->getElementType();
1597
1598 // 2. GEP to the first element of the array.
1599 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001600 }
John McCall1e7fe752010-09-02 09:58:18 +00001601
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001602 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001603 }
1604
Douglas Gregoreede61a2010-09-02 17:38:50 +00001605 assert(ConvertTypeForMem(DeleteTy) ==
1606 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001607
1608 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001609 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001610 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001611 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1612 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001613 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001614
Anders Carlsson16d81b82009-09-22 22:53:17 +00001615 EmitBlock(DeleteEnd);
1616}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001617
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001618static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1619 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001620 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001621
1622 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1623}
1624
1625static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001626 llvm::Value *Fn = getBadTypeidFn(CGF);
John McCallbd7370a2013-02-28 19:01:20 +00001627 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001628 CGF.Builder.CreateUnreachable();
1629}
1630
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001631static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1632 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001633 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001634 // Get the vtable pointer.
1635 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1636
1637 // C++ [expr.typeid]p2:
1638 // If the glvalue expression is obtained by applying the unary * operator to
1639 // a pointer and the pointer is a null pointer value, the typeid expression
1640 // throws the std::bad_typeid exception.
1641 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1642 if (UO->getOpcode() == UO_Deref) {
1643 llvm::BasicBlock *BadTypeidBlock =
1644 CGF.createBasicBlock("typeid.bad_typeid");
1645 llvm::BasicBlock *EndBlock =
1646 CGF.createBasicBlock("typeid.end");
1647
1648 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1649 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1650
1651 CGF.EmitBlock(BadTypeidBlock);
1652 EmitBadTypeidCall(CGF);
1653 CGF.EmitBlock(EndBlock);
1654 }
1655 }
1656
1657 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1658 StdTypeInfoPtrTy->getPointerTo());
1659
1660 // Load the type info.
1661 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1662 return CGF.Builder.CreateLoad(Value);
1663}
1664
John McCall3ad32c82011-01-28 08:37:24 +00001665llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001666 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001667 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001668
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001669 if (E->isTypeOperand()) {
1670 llvm::Constant *TypeInfo =
1671 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001672 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001673 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001674
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001675 // C++ [expr.typeid]p2:
1676 // When typeid is applied to a glvalue expression whose type is a
1677 // polymorphic class type, the result refers to a std::type_info object
1678 // representing the type of the most derived object (that is, the dynamic
1679 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001680 if (E->isPotentiallyEvaluated())
1681 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1682 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001683
1684 QualType OperandTy = E->getExprOperand()->getType();
1685 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1686 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001687}
Mike Stumpc849c052009-11-16 06:50:58 +00001688
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001689static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1690 // void *__dynamic_cast(const void *sub,
1691 // const abi::__class_type_info *src,
1692 // const abi::__class_type_info *dst,
1693 // std::ptrdiff_t src2dst_offset);
1694
Chris Lattner8b418682012-02-07 00:39:47 +00001695 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001696 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001697 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1698
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001699 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Benjamin Kramer21f6b392013-02-03 17:44:25 +00001700
1701 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1702
1703 // Mark the function as nounwind readonly.
1704 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1705 llvm::Attribute::ReadOnly };
1706 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1707 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1708
1709 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001710}
1711
1712static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1713 // void __cxa_bad_cast();
Chris Lattner8b418682012-02-07 00:39:47 +00001714 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001715 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1716}
1717
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001718static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001719 llvm::Value *Fn = getBadCastFn(CGF);
John McCallbd7370a2013-02-28 19:01:20 +00001720 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001721 CGF.Builder.CreateUnreachable();
1722}
1723
Benjamin Kramerae3f7602013-02-03 19:59:25 +00001724/// \brief Compute the src2dst_offset hint as described in the
1725/// Itanium C++ ABI [2.9.7]
1726static CharUnits computeOffsetHint(ASTContext &Context,
1727 const CXXRecordDecl *Src,
1728 const CXXRecordDecl *Dst) {
1729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1730 /*DetectVirtual=*/false);
1731
1732 // If Dst is not derived from Src we can skip the whole computation below and
1733 // return that Src is not a public base of Dst. Record all inheritance paths.
1734 if (!Dst->isDerivedFrom(Src, Paths))
1735 return CharUnits::fromQuantity(-2ULL);
1736
1737 unsigned NumPublicPaths = 0;
1738 CharUnits Offset;
1739
1740 // Now walk all possible inheritance paths.
1741 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
1742 I != E; ++I) {
1743 if (I->Access != AS_public) // Ignore non-public inheritance.
1744 continue;
1745
1746 ++NumPublicPaths;
1747
1748 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1749 // If the path contains a virtual base class we can't give any hint.
1750 // -1: no hint.
1751 if (J->Base->isVirtual())
1752 return CharUnits::fromQuantity(-1ULL);
1753
1754 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1755 continue;
1756
1757 // Accumulate the base class offsets.
1758 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1759 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1760 }
1761 }
1762
1763 // -2: Src is not a public base of Dst.
1764 if (NumPublicPaths == 0)
1765 return CharUnits::fromQuantity(-2ULL);
1766
1767 // -3: Src is a multiple public base type but never a virtual base type.
1768 if (NumPublicPaths > 1)
1769 return CharUnits::fromQuantity(-3ULL);
1770
1771 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1772 // Return the offset of Src from the origin of Dst.
1773 return Offset;
1774}
1775
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001776static llvm::Value *
1777EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1778 QualType SrcTy, QualType DestTy,
1779 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001780 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001781 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001782 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001783
1784 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1785 if (PTy->getPointeeType()->isVoidType()) {
1786 // C++ [expr.dynamic.cast]p7:
1787 // If T is "pointer to cv void," then the result is a pointer to the
1788 // most derived object pointed to by v.
1789
1790 // Get the vtable pointer.
1791 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1792
1793 // Get the offset-to-top from the vtable.
1794 llvm::Value *OffsetToTop =
1795 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1796 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1797
1798 // Finally, add the offset to the pointer.
1799 Value = CGF.EmitCastToVoidPtr(Value);
1800 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1801
1802 return CGF.Builder.CreateBitCast(Value, DestLTy);
1803 }
1804 }
1805
1806 QualType SrcRecordTy;
1807 QualType DestRecordTy;
1808
1809 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1810 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1811 DestRecordTy = DestPTy->getPointeeType();
1812 } else {
1813 SrcRecordTy = SrcTy;
1814 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1815 }
1816
1817 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1818 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1819
1820 llvm::Value *SrcRTTI =
1821 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1822 llvm::Value *DestRTTI =
1823 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1824
Benjamin Kramerae3f7602013-02-03 19:59:25 +00001825 // Compute the offset hint.
1826 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1827 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1828 llvm::Value *OffsetHint =
1829 llvm::ConstantInt::get(PtrDiffLTy,
1830 computeOffsetHint(CGF.getContext(), SrcDecl,
1831 DestDecl).getQuantity());
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001832
1833 // Emit the call to __dynamic_cast.
1834 Value = CGF.EmitCastToVoidPtr(Value);
John McCallbd7370a2013-02-28 19:01:20 +00001835
1836 llvm::Value *args[] = { Value, SrcRTTI, DestRTTI, OffsetHint };
1837 Value = CGF.EmitNounwindRuntimeCall(getDynamicCastFn(CGF), args);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001838 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1839
1840 /// C++ [expr.dynamic.cast]p9:
1841 /// A failed cast to reference type throws std::bad_cast
1842 if (DestTy->isReferenceType()) {
1843 llvm::BasicBlock *BadCastBlock =
1844 CGF.createBasicBlock("dynamic_cast.bad_cast");
1845
1846 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1847 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1848
1849 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001850 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001851 }
1852
1853 return Value;
1854}
1855
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001856static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1857 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001858 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001859 if (DestTy->isPointerType())
1860 return llvm::Constant::getNullValue(DestLTy);
1861
1862 /// C++ [expr.dynamic.cast]p9:
1863 /// A failed cast to reference type throws std::bad_cast
1864 EmitBadCastCall(CGF);
1865
1866 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1867 return llvm::UndefValue::get(DestLTy);
1868}
1869
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001870llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001871 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001872 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001873
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001874 if (DCE->isAlwaysNull())
1875 return EmitDynamicCastToNull(*this, DestTy);
1876
1877 QualType SrcTy = DCE->getSubExpr()->getType();
1878
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001879 // C++ [expr.dynamic.cast]p4:
1880 // If the value of v is a null pointer value in the pointer case, the result
1881 // is the null pointer value of type T.
1882 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001883
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001884 llvm::BasicBlock *CastNull = 0;
1885 llvm::BasicBlock *CastNotNull = 0;
1886 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001887
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001888 if (ShouldNullCheckSrcValue) {
1889 CastNull = createBasicBlock("dynamic_cast.null");
1890 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1891
1892 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1893 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1894 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001895 }
1896
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001897 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1898
1899 if (ShouldNullCheckSrcValue) {
1900 EmitBranch(CastEnd);
1901
1902 EmitBlock(CastNull);
1903 EmitBranch(CastEnd);
1904 }
1905
1906 EmitBlock(CastEnd);
1907
1908 if (ShouldNullCheckSrcValue) {
1909 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1910 PHI->addIncoming(Value, CastNotNull);
1911 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1912
1913 Value = PHI;
1914 }
1915
1916 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001917}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001918
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001919void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001920 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001921 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1922 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001923
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001924 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1925 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1926 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001927 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001928 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001929
David Blaikie581deb32012-06-06 20:45:41 +00001930 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001931 ArrayRef<VarDecl *> ArrayIndexes;
1932 if (CurField->getType()->isArrayType())
1933 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001934 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001935 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001936}