blob: 43318a73d56e376fe39e16e50be99513f52823f6 [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
178 if (MD->isStatic()) {
179 // The method is static, emit it as we would a regular call.
180 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
181 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
182 ReturnValue, CE->arg_begin(), CE->arg_end());
183 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000184
John McCallfc400282010-09-03 01:26:39 +0000185 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000186 const Expr *Base = ME->getBase();
187 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000188
Rafael Espindolaea01d762012-06-28 14:28:57 +0000189 const CXXMethodDecl *DevirtualizedMethod = NULL;
190 if (CanUseVirtualCall &&
191 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
192 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
193 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
194 assert(DevirtualizedMethod);
195 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
196 const Expr *Inner = Base->ignoreParenBaseCasts();
197 if (getCXXRecord(Inner) == DevirtualizedClass)
198 // If the class of the Inner expression is where the dynamic method
199 // is defined, build the this pointer from it.
200 Base = Inner;
201 else if (getCXXRecord(Base) != DevirtualizedClass) {
202 // If the method is defined in a class that is not the best dynamic
203 // one or the one of the full expression, we would have to build
204 // a derived-to-base cast to compute the correct this pointer, but
205 // we don't have support for that yet, so do a virtual call.
206 DevirtualizedMethod = NULL;
207 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000208 // If the return types are not the same, this might be a case where more
209 // code needs to run to compensate for it. For example, the derived
210 // method might return a type that inherits form from the return
211 // type of MD and has a prefix.
212 // For now we just avoid devirtualizing these covariant cases.
213 if (DevirtualizedMethod &&
214 DevirtualizedMethod->getResultType().getCanonicalType() !=
215 MD->getResultType().getCanonicalType())
Rafael Espindola4a889e42012-06-28 15:11:39 +0000216 DevirtualizedMethod = NULL;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000217 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000218
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000219 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000220 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000221 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000222 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000223 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000224
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000225
John McCallfc400282010-09-03 01:26:39 +0000226 if (MD->isTrivial()) {
227 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000228 if (isa<CXXConstructorDecl>(MD) &&
229 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
230 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000231
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000232 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
233 // We don't like to generate the trivial copy/move assignment operator
234 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000235 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000236 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichetdbee3412011-01-18 05:04:39 +0000237 return RValue::get(This);
238 }
239
240 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000241 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
242 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000243 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
244 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
245 CE->arg_begin(), CE->arg_end());
246 return RValue::get(This);
247 }
248 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000249 }
250
John McCallfc400282010-09-03 01:26:39 +0000251 // Compute the function type we're calling.
Eli Friedman465e89e2012-10-25 00:12:49 +0000252 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Francois Pichetdbee3412011-01-18 05:04:39 +0000253 const CGFunctionInfo *FInfo = 0;
Eli Friedman465e89e2012-10-25 00:12:49 +0000254 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
255 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCallde5d3c72012-02-17 03:33:10 +0000256 Dtor_Complete);
Eli Friedman465e89e2012-10-25 00:12:49 +0000257 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
258 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
259 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000260 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000261 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000262
Reid Klecknera4130ba2013-07-22 13:51:44 +0000263 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000264
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000265 // C++ [class.virtual]p12:
266 // Explicit qualification with the scope operator (5.1) suppresses the
267 // virtual call mechanism.
268 //
269 // We also don't emit a virtual call if the base expression has a record type
270 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000271 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin3258abc2013-06-19 23:23:19 +0000272 llvm::Value *Callee;
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000273
John McCallfc400282010-09-03 01:26:39 +0000274 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000275 assert(CE->arg_begin() == CE->arg_end() &&
276 "Destructor shouldn't have explicit parameters");
277 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCallfc400282010-09-03 01:26:39 +0000278 if (UseVirtualCall) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000279 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
280 CE->getExprLoc(), This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000281 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000282 if (getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000283 MD->isVirtual() &&
284 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000285 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000286 else if (!DevirtualizedMethod)
Reid Klecknera4130ba2013-07-22 13:51:44 +0000287 Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000288 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000289 const CXXDestructorDecl *DDtor =
290 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000291 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
292 }
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000293 EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
294 /*ImplicitParam=*/0, QualType(), 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000295 }
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000296 return RValue::get(0);
297 }
298
299 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichetdbee3412011-01-18 05:04:39 +0000300 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000301 } else if (UseVirtualCall) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000302 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000303 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000304 if (getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000305 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000306 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000307 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000308 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000309 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000310 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000311 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000312 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313 }
314
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000315 if (MD->isVirtual())
316 This = CGM.getCXXABI().adjustThisArgumentForVirtualCall(*this, MD, This);
317
Richard Smith4def70d2012-10-09 19:52:38 +0000318 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000319 /*ImplicitParam=*/0, QualType(),
320 CE->arg_begin(), CE->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000321}
322
323RValue
324CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
325 ReturnValueSlot ReturnValue) {
326 const BinaryOperator *BO =
327 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
328 const Expr *BaseExpr = BO->getLHS();
329 const Expr *MemFnExpr = BO->getRHS();
330
331 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000332 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000333
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000334 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000335 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000336 const CXXRecordDecl *RD =
337 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
338
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000339 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000340 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000341
342 // Emit the 'this' pointer.
343 llvm::Value *This;
344
John McCall2de56d12010-08-25 11:45:40 +0000345 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000346 This = EmitScalarExpr(BaseExpr);
347 else
348 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000349
Richard Smith4def70d2012-10-09 19:52:38 +0000350 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
351 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000352
John McCall93d557b2010-08-22 00:05:51 +0000353 // Ask the ABI to load the callee. Note that This is modified.
354 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000355 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000356
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000357 CallArgList Args;
358
359 QualType ThisType =
360 getContext().getPointerType(getContext().getTagDeclType(RD));
361
362 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000363 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000364
365 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000366
367 // And the rest of the call args
368 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0f3d0972012-07-07 06:41:13 +0000369 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000370 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000371}
372
373RValue
374CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
375 const CXXMethodDecl *MD,
376 ReturnValueSlot ReturnValue) {
377 assert(MD->isInstance() &&
378 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000379 LValue LV = EmitLValue(E->getArg(0));
380 llvm::Value *This = LV.getAddress();
381
Douglas Gregorb2b56582011-09-06 16:26:56 +0000382 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
383 MD->isTrivial()) {
384 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
385 QualType Ty = E->getType();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000386 EmitAggregateAssign(This, Src, Ty);
Douglas Gregorb2b56582011-09-06 16:26:56 +0000387 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000388 }
389
Anders Carlssona2447e02011-05-08 20:32:23 +0000390 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smith4def70d2012-10-09 19:52:38 +0000391 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000392 /*ImplicitParam=*/0, QualType(),
393 E->arg_begin() + 1, E->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000394}
395
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000396RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
397 ReturnValueSlot ReturnValue) {
398 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
399}
400
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000401static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
402 llvm::Value *DestPtr,
403 const CXXRecordDecl *Base) {
404 if (Base->isEmpty())
405 return;
406
407 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
408
409 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
410 CharUnits Size = Layout.getNonVirtualSize();
411 CharUnits Align = Layout.getNonVirtualAlign();
412
413 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
414
415 // If the type contains a pointer to data member we can't memset it to zero.
416 // Instead, create a null constant and copy it to the destination.
417 // TODO: there are other patterns besides zero that we can usefully memset,
418 // like -1, which happens to be the pattern used by member-pointers.
419 // TODO: isZeroInitializable can be over-conservative in the case where a
420 // virtual base contains a member pointer.
421 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
422 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
423
424 llvm::GlobalVariable *NullVariable =
425 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
426 /*isConstant=*/true,
427 llvm::GlobalVariable::PrivateLinkage,
428 NullConstant, Twine());
429 NullVariable->setAlignment(Align.getQuantity());
430 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
431
432 // Get and call the appropriate llvm.memcpy overload.
433 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
434 return;
435 }
436
437 // Otherwise, just memset the whole thing to zero. This is legal
438 // because in LLVM, all default initializers (other than the ones we just
439 // handled above) are guaranteed to have a bit pattern of all zeros.
440 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
441 Align.getQuantity());
442}
443
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000444void
John McCall558d2ab2010-09-15 10:14:12 +0000445CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
446 AggValueSlot Dest) {
447 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000448 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000449
450 // If we require zero initialization before (or instead of) calling the
451 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000452 // constructor, emit the zero initialization now, unless destination is
453 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000454 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
455 switch (E->getConstructionKind()) {
456 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000457 case CXXConstructExpr::CK_Complete:
458 EmitNullInitialization(Dest.getAddr(), E->getType());
459 break;
460 case CXXConstructExpr::CK_VirtualBase:
461 case CXXConstructExpr::CK_NonVirtualBase:
462 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
463 break;
464 }
465 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000466
467 // If this is a call to a trivial default constructor, do nothing.
468 if (CD->isTrivial() && CD->isDefaultConstructor())
469 return;
470
John McCallfc1e6c72010-09-18 00:58:34 +0000471 // Elide the constructor if we're constructing from a temporary.
472 // The temporary check is required because Sema sets this on NRVO
473 // returns.
Richard Smith7edf9e32012-11-01 22:30:59 +0000474 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000475 assert(getContext().hasSameUnqualifiedType(E->getType(),
476 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000477 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
478 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000479 return;
480 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000481 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000482
John McCallc3c07662011-07-13 06:10:41 +0000483 if (const ConstantArrayType *arrayType
484 = getContext().getAsConstantArrayType(E->getType())) {
485 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000486 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000487 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000488 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000489 bool ForVirtualBase = false;
Douglas Gregor378e1e72013-01-31 05:50:40 +0000490 bool Delegating = false;
491
Sean Huntd49bd552011-05-03 20:19:28 +0000492 switch (E->getConstructionKind()) {
493 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000494 // We should be emitting a constructor; GlobalDecl will assert this
495 Type = CurGD.getCtorType();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000496 Delegating = true;
Sean Huntd49bd552011-05-03 20:19:28 +0000497 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000498
Sean Huntd49bd552011-05-03 20:19:28 +0000499 case CXXConstructExpr::CK_Complete:
500 Type = Ctor_Complete;
501 break;
502
503 case CXXConstructExpr::CK_VirtualBase:
504 ForVirtualBase = true;
505 // fall-through
506
507 case CXXConstructExpr::CK_NonVirtualBase:
508 Type = Ctor_Base;
509 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000510
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000511 // Call the constructor.
Douglas Gregor378e1e72013-01-31 05:50:40 +0000512 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000513 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000514 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000515}
516
Fariborz Jahanian34999872010-11-13 21:53:34 +0000517void
518CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
519 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000520 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000521 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000522 Exp = E->getSubExpr();
523 assert(isa<CXXConstructExpr>(Exp) &&
524 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
525 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
526 const CXXConstructorDecl *CD = E->getConstructor();
527 RunCleanupsScope Scope(*this);
528
529 // If we require zero initialization before (or instead of) calling the
530 // constructor, as can be the case with a non-user-provided default
531 // constructor, emit the zero initialization now.
532 // FIXME. Do I still need this for a copy ctor synthesis?
533 if (E->requiresZeroInitialization())
534 EmitNullInitialization(Dest, E->getType());
535
Chandler Carruth858a5462010-11-15 13:54:43 +0000536 assert(!getContext().getAsConstantArrayType(E->getType())
537 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000538 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
539 E->arg_begin(), E->arg_end());
540}
541
John McCall1e7fe752010-09-02 09:58:18 +0000542static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
543 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000544 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000545 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000546
John McCallb1c98a32011-05-16 01:05:12 +0000547 // No cookie is required if the operator new[] being used is the
548 // reserved placement operator new[].
549 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000550 return CharUnits::Zero();
551
John McCall6ec278d2011-01-27 09:37:56 +0000552 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000553}
554
John McCall7d166272011-05-15 07:14:44 +0000555static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
556 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000557 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000558 llvm::Value *&numElements,
559 llvm::Value *&sizeWithoutCookie) {
560 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000561
John McCall7d166272011-05-15 07:14:44 +0000562 if (!e->isArray()) {
563 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
564 sizeWithoutCookie
565 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
566 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000567 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000568
John McCall7d166272011-05-15 07:14:44 +0000569 // The width of size_t.
570 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
571
John McCall1e7fe752010-09-02 09:58:18 +0000572 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000573 llvm::APInt cookieSize(sizeWidth,
574 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000575
Anders Carlssona4d4c012009-09-23 16:07:23 +0000576 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000577 // We multiply the size of all dimensions for NumElements.
578 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000579 numElements = CGF.EmitScalarExpr(e->getArraySize());
580 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000581
John McCall7d166272011-05-15 07:14:44 +0000582 // The number of elements can be have an arbitrary integer type;
583 // essentially, we need to multiply it by a constant factor, add a
584 // cookie size, and verify that the result is representable as a
585 // size_t. That's just a gloss, though, and it's wrong in one
586 // important way: if the count is negative, it's an error even if
587 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000588 bool isSigned
589 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000590 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000591 = cast<llvm::IntegerType>(numElements->getType());
592 unsigned numElementsWidth = numElementsType->getBitWidth();
593
594 // Compute the constant factor.
595 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000596 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000597 = CGF.getContext().getAsConstantArrayType(type)) {
598 type = CAT->getElementType();
599 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000600 }
601
John McCall7d166272011-05-15 07:14:44 +0000602 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
603 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
604 typeSizeMultiplier *= arraySizeMultiplier;
605
606 // This will be a size_t.
607 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000608
Chris Lattner806941e2010-07-20 21:55:52 +0000609 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
610 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000611 if (llvm::ConstantInt *numElementsC =
612 dyn_cast<llvm::ConstantInt>(numElements)) {
613 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000614
John McCall7d166272011-05-15 07:14:44 +0000615 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000616
John McCall7d166272011-05-15 07:14:44 +0000617 // If 'count' was a negative number, it's an overflow.
618 if (isSigned && count.isNegative())
619 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000620
John McCall7d166272011-05-15 07:14:44 +0000621 // We want to do all this arithmetic in size_t. If numElements is
622 // wider than that, check whether it's already too big, and if so,
623 // overflow.
624 else if (numElementsWidth > sizeWidth &&
625 numElementsWidth - sizeWidth > count.countLeadingZeros())
626 hasAnyOverflow = true;
627
628 // Okay, compute a count at the right width.
629 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
630
Sebastian Redl92036472012-02-22 17:37:52 +0000631 // If there is a brace-initializer, we cannot allocate fewer elements than
632 // there are initializers. If we do, that's treated like an overflow.
633 if (adjustedCount.ult(minElements))
634 hasAnyOverflow = true;
635
John McCall7d166272011-05-15 07:14:44 +0000636 // Scale numElements by that. This might overflow, but we don't
637 // care because it only overflows if allocationSize does, too, and
638 // if that overflows then we shouldn't use this.
639 numElements = llvm::ConstantInt::get(CGF.SizeTy,
640 adjustedCount * arraySizeMultiplier);
641
642 // Compute the size before cookie, and track whether it overflowed.
643 bool overflow;
644 llvm::APInt allocationSize
645 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
646 hasAnyOverflow |= overflow;
647
648 // Add in the cookie, and check whether it's overflowed.
649 if (cookieSize != 0) {
650 // Save the current size without a cookie. This shouldn't be
651 // used if there was overflow.
652 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
653
654 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
655 hasAnyOverflow |= overflow;
656 }
657
658 // On overflow, produce a -1 so operator new will fail.
659 if (hasAnyOverflow) {
660 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
661 } else {
662 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
663 }
664
665 // Otherwise, we might need to use the overflow intrinsics.
666 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000667 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000668 // 1) if isSigned, we need to check whether numElements is negative;
669 // 2) if numElementsWidth > sizeWidth, we need to check whether
670 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000671 // 3) if minElements > 0, we need to check whether numElements is smaller
672 // than that.
673 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000674 // sizeWithoutCookie := numElements * typeSizeMultiplier
675 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000676 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000677 // size := sizeWithoutCookie + cookieSize
678 // and check whether it overflows.
679
680 llvm::Value *hasOverflow = 0;
681
682 // If numElementsWidth > sizeWidth, then one way or another, we're
683 // going to have to do a comparison for (2), and this happens to
684 // take care of (1), too.
685 if (numElementsWidth > sizeWidth) {
686 llvm::APInt threshold(numElementsWidth, 1);
687 threshold <<= sizeWidth;
688
689 llvm::Value *thresholdV
690 = llvm::ConstantInt::get(numElementsType, threshold);
691
692 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
693 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
694
695 // Otherwise, if we're signed, we want to sext up to size_t.
696 } else if (isSigned) {
697 if (numElementsWidth < sizeWidth)
698 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
699
700 // If there's a non-1 type size multiplier, then we can do the
701 // signedness check at the same time as we do the multiply
702 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000703 // unsigned overflow. Otherwise, we have to do it here. But at least
704 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000705 if (typeSizeMultiplier == 1)
706 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000707 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000708
709 // Otherwise, zext up to size_t if necessary.
710 } else if (numElementsWidth < sizeWidth) {
711 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
712 }
713
714 assert(numElements->getType() == CGF.SizeTy);
715
Sebastian Redl92036472012-02-22 17:37:52 +0000716 if (minElements) {
717 // Don't allow allocation of fewer elements than we have initializers.
718 if (!hasOverflow) {
719 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
720 llvm::ConstantInt::get(CGF.SizeTy, minElements));
721 } else if (numElementsWidth > sizeWidth) {
722 // The other existing overflow subsumes this check.
723 // We do an unsigned comparison, since any signed value < -1 is
724 // taken care of either above or below.
725 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
726 CGF.Builder.CreateICmpULT(numElements,
727 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
728 }
729 }
730
John McCall7d166272011-05-15 07:14:44 +0000731 size = numElements;
732
733 // Multiply by the type size if necessary. This multiplier
734 // includes all the factors for nested arrays.
735 //
736 // This step also causes numElements to be scaled up by the
737 // nested-array factor if necessary. Overflow on this computation
738 // can be ignored because the result shouldn't be used if
739 // allocation fails.
740 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000741 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000742 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000743
744 llvm::Value *tsmV =
745 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
746 llvm::Value *result =
747 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
748
749 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
750 if (hasOverflow)
751 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
752 else
753 hasOverflow = overflowed;
754
755 size = CGF.Builder.CreateExtractValue(result, 0);
756
757 // Also scale up numElements by the array size multiplier.
758 if (arraySizeMultiplier != 1) {
759 // If the base element type size is 1, then we can re-use the
760 // multiply we just did.
761 if (typeSize.isOne()) {
762 assert(arraySizeMultiplier == typeSizeMultiplier);
763 numElements = size;
764
765 // Otherwise we need a separate multiply.
766 } else {
767 llvm::Value *asmV =
768 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
769 numElements = CGF.Builder.CreateMul(numElements, asmV);
770 }
771 }
772 } else {
773 // numElements doesn't need to be scaled.
774 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000775 }
776
John McCall7d166272011-05-15 07:14:44 +0000777 // Add in the cookie size if necessary.
778 if (cookieSize != 0) {
779 sizeWithoutCookie = size;
780
John McCall7d166272011-05-15 07:14:44 +0000781 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000782 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000783
784 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
785 llvm::Value *result =
786 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
787
788 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
789 if (hasOverflow)
790 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
791 else
792 hasOverflow = overflowed;
793
794 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000795 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000796
John McCall7d166272011-05-15 07:14:44 +0000797 // If we had any possibility of dynamic overflow, make a select to
798 // overwrite 'size' with an all-ones value, which should cause
799 // operator new to throw.
800 if (hasOverflow)
801 size = CGF.Builder.CreateSelect(hasOverflow,
802 llvm::Constant::getAllOnesValue(CGF.SizeTy),
803 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000804 }
John McCall1e7fe752010-09-02 09:58:18 +0000805
John McCall7d166272011-05-15 07:14:44 +0000806 if (cookieSize == 0)
807 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000808 else
John McCall7d166272011-05-15 07:14:44 +0000809 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000810
John McCall7d166272011-05-15 07:14:44 +0000811 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000812}
813
Sebastian Redl92036472012-02-22 17:37:52 +0000814static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
815 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000816
Eli Friedmand7722d92011-12-03 02:13:40 +0000817 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall9d232c82013-03-07 21:37:08 +0000818 switch (CGF.getEvaluationKind(AllocType)) {
819 case TEK_Scalar:
Eli Friedmand7722d92011-12-03 02:13:40 +0000820 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000821 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000822 false);
John McCall9d232c82013-03-07 21:37:08 +0000823 return;
824 case TEK_Complex:
825 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
826 Alignment),
827 /*isInit*/ true);
828 return;
829 case TEK_Aggregate: {
John McCall558d2ab2010-09-15 10:14:12 +0000830 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000831 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000832 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000833 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000834 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000835 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000836 return;
John McCall558d2ab2010-09-15 10:14:12 +0000837 }
John McCall9d232c82013-03-07 21:37:08 +0000838 }
839 llvm_unreachable("bad evaluation kind");
Fariborz Jahanianef668722010-06-25 18:26:07 +0000840}
841
842void
843CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000844 QualType elementType,
845 llvm::Value *beginPtr,
846 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000847 if (!E->hasInitializer())
848 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000849
Sebastian Redl92036472012-02-22 17:37:52 +0000850 llvm::Value *explicitPtr = beginPtr;
John McCall19705672011-09-15 06:49:18 +0000851 // Find the end of the array, hoisted out of the loop.
852 llvm::Value *endPtr =
853 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
854
Sebastian Redl92036472012-02-22 17:37:52 +0000855 unsigned initializerElements = 0;
856
857 const Expr *Init = E->getInitializer();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000858 llvm::AllocaInst *endOfInit = 0;
859 QualType::DestructionKind dtorKind = elementType.isDestructedType();
860 EHScopeStack::stable_iterator cleanup;
861 llvm::Instruction *cleanupDominator = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000862 // If the initializer is an initializer list, first do the explicit elements.
863 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
864 initializerElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000865
866 // Enter a partial-destruction cleanup if necessary.
867 if (needsEHCleanup(dtorKind)) {
868 // In principle we could tell the cleanup where we are more
869 // directly, but the control flow can get so varied here that it
870 // would actually be quite complex. Therefore we go through an
871 // alloca.
872 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
873 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
874 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
875 getDestroyer(dtorKind));
876 cleanup = EHStack.stable_begin();
877 }
878
Sebastian Redl92036472012-02-22 17:37:52 +0000879 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000880 // Tell the cleanup that it needs to destroy up to this
881 // element. TODO: some of these stores can be trivially
882 // observed to be unnecessary.
883 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redl92036472012-02-22 17:37:52 +0000884 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
885 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
886 }
887
888 // The remaining elements are filled with the array filler expression.
889 Init = ILE->getArrayFiller();
890 }
891
John McCall19705672011-09-15 06:49:18 +0000892 // Create the continuation block.
893 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
894
Sebastian Redl92036472012-02-22 17:37:52 +0000895 // If the number of elements isn't constant, we have to now check if there is
896 // anything left to initialize.
897 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
898 // If all elements have already been initialized, skip the whole loop.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000899 if (constNum->getZExtValue() <= initializerElements) {
900 // If there was a cleanup, deactivate it.
901 if (cleanupDominator)
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +0000902 DeactivateCleanupBlock(cleanup, cleanupDominator);
Chad Rosier577fb5b2012-02-24 00:13:55 +0000903 return;
904 }
Sebastian Redl92036472012-02-22 17:37:52 +0000905 } else {
John McCall19705672011-09-15 06:49:18 +0000906 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redl92036472012-02-22 17:37:52 +0000907 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall19705672011-09-15 06:49:18 +0000908 "array.isempty");
909 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
910 EmitBlock(nonEmptyBB);
911 }
912
913 // Enter the loop.
914 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
915 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
916
917 EmitBlock(loopBB);
918
919 // Set up the current-element phi.
920 llvm::PHINode *curPtr =
Sebastian Redl92036472012-02-22 17:37:52 +0000921 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
922 curPtr->addIncoming(explicitPtr, entryBB);
John McCall19705672011-09-15 06:49:18 +0000923
Chad Rosier577fb5b2012-02-24 00:13:55 +0000924 // Store the new cleanup position for irregular cleanups.
925 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
926
John McCall19705672011-09-15 06:49:18 +0000927 // Enter a partial-destruction cleanup if necessary.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000928 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall19705672011-09-15 06:49:18 +0000929 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
930 getDestroyer(dtorKind));
931 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000932 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000933 }
934
935 // Emit the initializer into this element.
Sebastian Redl92036472012-02-22 17:37:52 +0000936 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall19705672011-09-15 06:49:18 +0000937
938 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000939 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000940 DeactivateCleanupBlock(cleanup, cleanupDominator);
941 cleanupDominator->eraseFromParent();
942 }
John McCall19705672011-09-15 06:49:18 +0000943
944 // Advance to the next element.
945 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
946
947 // Check whether we've gotten to the end of the array and, if so,
948 // exit the loop.
949 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
950 Builder.CreateCondBr(isEnd, contBB, loopBB);
951 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
952
953 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000954}
955
Douglas Gregor59174c02010-07-21 01:10:17 +0000956static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
957 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000958 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000959 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000960 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000961 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000962}
963
Anders Carlssona4d4c012009-09-23 16:07:23 +0000964static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000965 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000966 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000967 llvm::Value *NumElements,
968 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000969 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000970 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000971 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
972 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor887ddf32012-02-23 17:07:43 +0000973 if (Ctor->isTrivial()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000974 // If new expression did not specify value-initialization, then there
975 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000976 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000977 return;
978
John McCall19705672011-09-15 06:49:18 +0000979 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000980 // Optimization: since zero initialization will just set the memory
981 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000982 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000983 return;
984 }
Douglas Gregor59174c02010-07-21 01:10:17 +0000985 }
John McCallc3c07662011-07-13 06:10:41 +0000986
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000987 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
988 CCE->arg_begin(), CCE->arg_end(),
Eli Friedmanb41ba1a2012-08-25 07:11:29 +0000989 CCE->requiresZeroInitialization());
Anders Carlssone99bdb62010-05-03 15:09:17 +0000990 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000991 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000992 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000993 // Optimization: since zero initialization will just set the memory
994 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000995 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
996 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +0000997 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000998 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
999 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +00001000 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +00001001
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001002 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +00001003 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001004
Sebastian Redl92036472012-02-22 17:37:52 +00001005 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001006}
1007
Richard Smithddcff1b2013-07-21 23:12:18 +00001008/// Emit a call to an operator new or operator delete function, as implicitly
1009/// created by new-expressions and delete-expressions.
1010static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1011 const FunctionDecl *Callee,
1012 const FunctionProtoType *CalleeType,
1013 const CallArgList &Args) {
1014 llvm::Instruction *CallOrInvoke;
Richard Smith060cb4a2013-07-29 20:14:16 +00001015 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smithddcff1b2013-07-21 23:12:18 +00001016 RValue RV =
1017 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith060cb4a2013-07-29 20:14:16 +00001018 CalleeAddr, ReturnValueSlot(), Args,
Richard Smithddcff1b2013-07-21 23:12:18 +00001019 Callee, &CallOrInvoke);
1020
1021 /// C++1y [expr.new]p10:
1022 /// [In a new-expression,] an implementation is allowed to omit a call
1023 /// to a replaceable global allocation function.
1024 ///
1025 /// We model such elidable calls with the 'builtin' attribute.
Richard Smith060cb4a2013-07-29 20:14:16 +00001026 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
1027 if (Callee->isReplaceableGlobalAllocationFunction() &&
1028 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smithddcff1b2013-07-21 23:12:18 +00001029 // FIXME: Add addAttribute to CallSite.
1030 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1031 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1032 llvm::Attribute::Builtin);
1033 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1034 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1035 llvm::Attribute::Builtin);
1036 else
1037 llvm_unreachable("unexpected kind of call instruction");
1038 }
1039
1040 return RV;
1041}
1042
John McCall7d8647f2010-09-14 07:57:04 +00001043namespace {
1044 /// A cleanup to call the given 'operator delete' function upon
1045 /// abnormal exit from a new expression.
1046 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1047 size_t NumPlacementArgs;
1048 const FunctionDecl *OperatorDelete;
1049 llvm::Value *Ptr;
1050 llvm::Value *AllocSize;
1051
1052 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1053
1054 public:
1055 static size_t getExtraSize(size_t NumPlacementArgs) {
1056 return NumPlacementArgs * sizeof(RValue);
1057 }
1058
1059 CallDeleteDuringNew(size_t NumPlacementArgs,
1060 const FunctionDecl *OperatorDelete,
1061 llvm::Value *Ptr,
1062 llvm::Value *AllocSize)
1063 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1064 Ptr(Ptr), AllocSize(AllocSize) {}
1065
1066 void setPlacementArg(unsigned I, RValue Arg) {
1067 assert(I < NumPlacementArgs && "index out of range");
1068 getPlacementArgs()[I] = Arg;
1069 }
1070
John McCallad346f42011-07-12 20:27:29 +00001071 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +00001072 const FunctionProtoType *FPT
1073 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1074 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +00001075 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001076
1077 CallArgList DeleteArgs;
1078
1079 // The first argument is always a void*.
1080 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001081 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001082
1083 // A member 'operator delete' can take an extra 'size_t' argument.
1084 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001085 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001086
1087 // Pass the rest of the arguments, which must match exactly.
1088 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001089 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001090
1091 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001092 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7d8647f2010-09-14 07:57:04 +00001093 }
1094 };
John McCall3019c442010-09-17 00:50:28 +00001095
1096 /// A cleanup to call the given 'operator delete' function upon
1097 /// abnormal exit from a new expression when the new expression is
1098 /// conditional.
1099 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1100 size_t NumPlacementArgs;
1101 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001102 DominatingValue<RValue>::saved_type Ptr;
1103 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001104
John McCall804b8072011-01-28 10:53:53 +00001105 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1106 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001107 }
1108
1109 public:
1110 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001111 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001112 }
1113
1114 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1115 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001116 DominatingValue<RValue>::saved_type Ptr,
1117 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001118 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1119 Ptr(Ptr), AllocSize(AllocSize) {}
1120
John McCall804b8072011-01-28 10:53:53 +00001121 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001122 assert(I < NumPlacementArgs && "index out of range");
1123 getPlacementArgs()[I] = Arg;
1124 }
1125
John McCallad346f42011-07-12 20:27:29 +00001126 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +00001127 const FunctionProtoType *FPT
1128 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1129 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1130 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1131
1132 CallArgList DeleteArgs;
1133
1134 // The first argument is always a void*.
1135 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001136 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001137
1138 // A member 'operator delete' can take an extra 'size_t' argument.
1139 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001140 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001141 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001142 }
1143
1144 // Pass the rest of the arguments, which must match exactly.
1145 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001146 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001147 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001148 }
1149
1150 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001151 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall3019c442010-09-17 00:50:28 +00001152 }
1153 };
1154}
1155
1156/// Enter a cleanup to call 'operator delete' if the initializer in a
1157/// new-expression throws.
1158static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1159 const CXXNewExpr *E,
1160 llvm::Value *NewPtr,
1161 llvm::Value *AllocSize,
1162 const CallArgList &NewArgs) {
1163 // If we're not inside a conditional branch, then the cleanup will
1164 // dominate and we can do the easier (and more efficient) thing.
1165 if (!CGF.isInConditionalBranch()) {
1166 CallDeleteDuringNew *Cleanup = CGF.EHStack
1167 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1168 E->getNumPlacementArgs(),
1169 E->getOperatorDelete(),
1170 NewPtr, AllocSize);
1171 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001172 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001173
1174 return;
1175 }
1176
1177 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001178 DominatingValue<RValue>::saved_type SavedNewPtr =
1179 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1180 DominatingValue<RValue>::saved_type SavedAllocSize =
1181 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001182
1183 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001184 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001185 E->getNumPlacementArgs(),
1186 E->getOperatorDelete(),
1187 SavedNewPtr,
1188 SavedAllocSize);
1189 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001190 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001191 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001192
John McCall6f103ba2011-11-10 10:43:54 +00001193 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001194}
1195
Anders Carlsson16d81b82009-09-22 22:53:17 +00001196llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001197 // The element type being allocated.
1198 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001199
John McCallc2f3e7f2011-03-07 03:12:35 +00001200 // 1. Build a call to the allocation function.
1201 FunctionDecl *allocator = E->getOperatorNew();
1202 const FunctionProtoType *allocatorType =
1203 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001204
John McCallc2f3e7f2011-03-07 03:12:35 +00001205 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001206
1207 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001208 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001209
Sebastian Redl92036472012-02-22 17:37:52 +00001210 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1211 unsigned minElements = 0;
1212 if (E->isArray() && E->hasInitializer()) {
1213 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1214 minElements = ILE->getNumInits();
1215 }
1216
John McCallc2f3e7f2011-03-07 03:12:35 +00001217 llvm::Value *numElements = 0;
1218 llvm::Value *allocSizeWithoutCookie = 0;
1219 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001220 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1221 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001222
Eli Friedman04c9a492011-05-02 17:57:46 +00001223 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001224
1225 // Emit the rest of the arguments.
1226 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001227 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001228
1229 // First, use the types from the function type.
1230 // We start at 1 here because the first argument (the allocation size)
1231 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001232 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1233 ++i, ++placementArg) {
1234 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001235
John McCallc2f3e7f2011-03-07 03:12:35 +00001236 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1237 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001238 "type mismatch in call argument!");
1239
John McCall413ebdb2011-03-11 20:59:21 +00001240 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001241 }
1242
1243 // Either we've emitted all the call args, or we have a call to a
1244 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001245 assert((placementArg == E->placement_arg_end() ||
1246 allocatorType->isVariadic()) &&
1247 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001248
1249 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001250 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1251 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001252 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001253 }
1254
John McCallb1c98a32011-05-16 01:05:12 +00001255 // Emit the allocation call. If the allocator is a global placement
1256 // operator, just "inline" it directly.
1257 RValue RV;
1258 if (allocator->isReservedGlobalPlacementOperator()) {
1259 assert(allocatorArgs.size() == 2);
1260 RV = allocatorArgs[1].RV;
1261 // TODO: kill any unnecessary computations done for the size
1262 // argument.
1263 } else {
Richard Smithddcff1b2013-07-21 23:12:18 +00001264 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCallb1c98a32011-05-16 01:05:12 +00001265 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001266
John McCallc2f3e7f2011-03-07 03:12:35 +00001267 // Emit a null check on the allocation result if the allocation
1268 // function is allowed to return null (because it has a non-throwing
1269 // exception spec; for this part, we inline
1270 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1271 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001272 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001273 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001274
John McCallc2f3e7f2011-03-07 03:12:35 +00001275 llvm::BasicBlock *nullCheckBB = 0;
1276 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001277
John McCallc2f3e7f2011-03-07 03:12:35 +00001278 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001279 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001280
John McCalla7f633f2011-03-07 01:52:56 +00001281 // The null-check means that the initializer is conditionally
1282 // evaluated.
1283 ConditionalEvaluation conditional(*this);
1284
John McCallc2f3e7f2011-03-07 03:12:35 +00001285 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001286 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001287
1288 nullCheckBB = Builder.GetInsertBlock();
1289 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1290 contBB = createBasicBlock("new.cont");
1291
1292 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1293 Builder.CreateCondBr(isNull, contBB, notNullBB);
1294 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001295 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001296
John McCall7d8647f2010-09-14 07:57:04 +00001297 // If there's an operator delete, enter a cleanup to call it if an
1298 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001299 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001300 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001301 if (E->getOperatorDelete() &&
1302 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001303 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1304 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001305 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001306 }
1307
Eli Friedman576cf172011-09-06 18:53:03 +00001308 assert((allocSize == allocSizeWithoutCookie) ==
1309 CalculateCookiePadding(*this, E).isZero());
1310 if (allocSize != allocSizeWithoutCookie) {
1311 assert(E->isArray());
1312 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1313 numElements,
1314 E, allocType);
1315 }
1316
Chris Lattner2acc6e32011-07-18 04:24:23 +00001317 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001318 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1319 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001320
John McCall19705672011-09-15 06:49:18 +00001321 EmitNewInitializer(*this, E, allocType, result, numElements,
1322 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001323 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001324 // NewPtr is a pointer to the base element type. If we're
1325 // allocating an array of arrays, we'll need to cast back to the
1326 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001327 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001328 if (result->getType() != resultType)
1329 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001330 }
John McCall7d8647f2010-09-14 07:57:04 +00001331
1332 // Deactivate the 'operator delete' cleanup if we finished
1333 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001334 if (operatorDeleteCleanup.isValid()) {
1335 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1336 cleanupDominator->eraseFromParent();
1337 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001338
John McCallc2f3e7f2011-03-07 03:12:35 +00001339 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001340 conditional.end(*this);
1341
John McCallc2f3e7f2011-03-07 03:12:35 +00001342 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1343 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001344
Jay Foadbbf3bac2011-03-30 11:28:58 +00001345 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001346 PHI->addIncoming(result, notNullBB);
1347 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1348 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001349
John McCallc2f3e7f2011-03-07 03:12:35 +00001350 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001351 }
John McCall1e7fe752010-09-02 09:58:18 +00001352
John McCallc2f3e7f2011-03-07 03:12:35 +00001353 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001354}
1355
Eli Friedman5fe05982009-11-18 00:50:08 +00001356void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1357 llvm::Value *Ptr,
1358 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001359 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1360
Eli Friedman5fe05982009-11-18 00:50:08 +00001361 const FunctionProtoType *DeleteFTy =
1362 DeleteFD->getType()->getAs<FunctionProtoType>();
1363
1364 CallArgList DeleteArgs;
1365
Anders Carlsson871d0782009-12-13 20:04:38 +00001366 // Check if we need to pass the size to the delete operator.
1367 llvm::Value *Size = 0;
1368 QualType SizeTy;
1369 if (DeleteFTy->getNumArgs() == 2) {
1370 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001371 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1372 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1373 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001374 }
1375
Eli Friedman5fe05982009-11-18 00:50:08 +00001376 QualType ArgTy = DeleteFTy->getArgType(0);
1377 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001378 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001379
Anders Carlsson871d0782009-12-13 20:04:38 +00001380 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001381 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001382
1383 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001384 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedman5fe05982009-11-18 00:50:08 +00001385}
1386
John McCall1e7fe752010-09-02 09:58:18 +00001387namespace {
1388 /// Calls the given 'operator delete' on a single object.
1389 struct CallObjectDelete : EHScopeStack::Cleanup {
1390 llvm::Value *Ptr;
1391 const FunctionDecl *OperatorDelete;
1392 QualType ElementType;
1393
1394 CallObjectDelete(llvm::Value *Ptr,
1395 const FunctionDecl *OperatorDelete,
1396 QualType ElementType)
1397 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1398
John McCallad346f42011-07-12 20:27:29 +00001399 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001400 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1401 }
1402 };
1403}
1404
1405/// Emit the code for deleting a single object.
1406static void EmitObjectDelete(CodeGenFunction &CGF,
1407 const FunctionDecl *OperatorDelete,
1408 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001409 QualType ElementType,
1410 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001411 // Find the destructor for the type, if applicable. If the
1412 // destructor is virtual, we'll just emit the vcall and return.
1413 const CXXDestructorDecl *Dtor = 0;
1414 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1415 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001416 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001417 Dtor = RD->getDestructor();
1418
1419 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001420 if (UseGlobalDelete) {
1421 // If we're supposed to call the global delete, make sure we do so
1422 // even if the destructor throws.
John McCallecd03b42012-09-25 10:10:39 +00001423
1424 // Derive the complete-object pointer, which is what we need
1425 // to pass to the deallocation function.
1426 llvm::Value *completePtr =
1427 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1428
Douglas Gregora8b20f72011-07-13 00:54:47 +00001429 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCallecd03b42012-09-25 10:10:39 +00001430 completePtr, OperatorDelete,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001431 ElementType);
1432 }
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001433
Richard Smith4def70d2012-10-09 19:52:38 +00001434 // FIXME: Provide a source location here.
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001435 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1436 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType,
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001437 SourceLocation(), Ptr);
John McCall1e7fe752010-09-02 09:58:18 +00001438
Douglas Gregora8b20f72011-07-13 00:54:47 +00001439 if (UseGlobalDelete) {
1440 CGF.PopCleanupBlock();
1441 }
1442
John McCall1e7fe752010-09-02 09:58:18 +00001443 return;
1444 }
1445 }
1446 }
1447
1448 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001449 // This doesn't have to a conditional cleanup because we're going
1450 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001451 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1452 Ptr, OperatorDelete, ElementType);
1453
1454 if (Dtor)
1455 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001456 /*ForVirtualBase=*/false,
1457 /*Delegating=*/false,
1458 Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001459 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001460 ElementType->isObjCLifetimeType()) {
1461 switch (ElementType.getObjCLifetime()) {
1462 case Qualifiers::OCL_None:
1463 case Qualifiers::OCL_ExplicitNone:
1464 case Qualifiers::OCL_Autoreleasing:
1465 break;
John McCall1e7fe752010-09-02 09:58:18 +00001466
John McCallf85e1932011-06-15 23:02:42 +00001467 case Qualifiers::OCL_Strong: {
1468 // Load the pointer value.
1469 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1470 ElementType.isVolatileQualified());
1471
John McCall5b07e802013-03-13 03:10:54 +00001472 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001473 break;
1474 }
1475
1476 case Qualifiers::OCL_Weak:
1477 CGF.EmitARCDestroyWeak(Ptr);
1478 break;
1479 }
1480 }
1481
John McCall1e7fe752010-09-02 09:58:18 +00001482 CGF.PopCleanupBlock();
1483}
1484
1485namespace {
1486 /// Calls the given 'operator delete' on an array of objects.
1487 struct CallArrayDelete : EHScopeStack::Cleanup {
1488 llvm::Value *Ptr;
1489 const FunctionDecl *OperatorDelete;
1490 llvm::Value *NumElements;
1491 QualType ElementType;
1492 CharUnits CookieSize;
1493
1494 CallArrayDelete(llvm::Value *Ptr,
1495 const FunctionDecl *OperatorDelete,
1496 llvm::Value *NumElements,
1497 QualType ElementType,
1498 CharUnits CookieSize)
1499 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1500 ElementType(ElementType), CookieSize(CookieSize) {}
1501
John McCallad346f42011-07-12 20:27:29 +00001502 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001503 const FunctionProtoType *DeleteFTy =
1504 OperatorDelete->getType()->getAs<FunctionProtoType>();
1505 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1506
1507 CallArgList Args;
1508
1509 // Pass the pointer as the first argument.
1510 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1511 llvm::Value *DeletePtr
1512 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001513 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001514
1515 // Pass the original requested size as the second argument.
1516 if (DeleteFTy->getNumArgs() == 2) {
1517 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001518 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001519 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1520
1521 CharUnits ElementTypeSize =
1522 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1523
1524 // The size of an element, multiplied by the number of elements.
1525 llvm::Value *Size
1526 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1527 Size = CGF.Builder.CreateMul(Size, NumElements);
1528
1529 // Plus the size of the cookie if applicable.
1530 if (!CookieSize.isZero()) {
1531 llvm::Value *CookieSizeV
1532 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1533 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1534 }
1535
Eli Friedman04c9a492011-05-02 17:57:46 +00001536 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001537 }
1538
1539 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001540 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall1e7fe752010-09-02 09:58:18 +00001541 }
1542 };
1543}
1544
1545/// Emit the code for deleting an array of objects.
1546static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001547 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001548 llvm::Value *deletedPtr,
1549 QualType elementType) {
1550 llvm::Value *numElements = 0;
1551 llvm::Value *allocatedPtr = 0;
1552 CharUnits cookieSize;
1553 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1554 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001555
John McCall7cfd76c2011-07-13 01:41:37 +00001556 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001557
1558 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001559 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001560 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001561 allocatedPtr, operatorDelete,
1562 numElements, elementType,
1563 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001564
John McCall7cfd76c2011-07-13 01:41:37 +00001565 // Destroy the elements.
1566 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1567 assert(numElements && "no element count for a type with a destructor!");
1568
John McCall7cfd76c2011-07-13 01:41:37 +00001569 llvm::Value *arrayEnd =
1570 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001571
1572 // Note that it is legal to allocate a zero-length array, and we
1573 // can never fold the check away because the length should always
1574 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001575 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1576 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001577 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001578 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001579 }
1580
John McCall7cfd76c2011-07-13 01:41:37 +00001581 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001582 CGF.PopCleanupBlock();
1583}
1584
Anders Carlsson16d81b82009-09-22 22:53:17 +00001585void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001586 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001587 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001588
1589 // Null check the pointer.
1590 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1591 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1592
Anders Carlssonb9241242011-04-11 00:30:07 +00001593 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001594
1595 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1596 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001597
John McCall1e7fe752010-09-02 09:58:18 +00001598 // We might be deleting a pointer to array. If so, GEP down to the
1599 // first non-array element.
1600 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1601 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1602 if (DeleteTy->isConstantArrayType()) {
1603 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001604 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001605
1606 GEP.push_back(Zero); // point at the outermost array
1607
1608 // For each layer of array type we're pointing at:
1609 while (const ConstantArrayType *Arr
1610 = getContext().getAsConstantArrayType(DeleteTy)) {
1611 // 1. Unpeel the array type.
1612 DeleteTy = Arr->getElementType();
1613
1614 // 2. GEP to the first element of the array.
1615 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001616 }
John McCall1e7fe752010-09-02 09:58:18 +00001617
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001618 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001619 }
1620
Douglas Gregoreede61a2010-09-02 17:38:50 +00001621 assert(ConvertTypeForMem(DeleteTy) ==
1622 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001623
1624 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001625 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001626 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001627 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1628 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001629 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001630
Anders Carlsson16d81b82009-09-22 22:53:17 +00001631 EmitBlock(DeleteEnd);
1632}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001633
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001634static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1635 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001636 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001637
1638 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1639}
1640
1641static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001642 llvm::Value *Fn = getBadTypeidFn(CGF);
John McCallbd7370a2013-02-28 19:01:20 +00001643 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001644 CGF.Builder.CreateUnreachable();
1645}
1646
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001647static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1648 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001649 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001650 // Get the vtable pointer.
1651 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1652
1653 // C++ [expr.typeid]p2:
1654 // If the glvalue expression is obtained by applying the unary * operator to
1655 // a pointer and the pointer is a null pointer value, the typeid expression
1656 // throws the std::bad_typeid exception.
1657 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1658 if (UO->getOpcode() == UO_Deref) {
1659 llvm::BasicBlock *BadTypeidBlock =
1660 CGF.createBasicBlock("typeid.bad_typeid");
1661 llvm::BasicBlock *EndBlock =
1662 CGF.createBasicBlock("typeid.end");
1663
1664 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1665 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1666
1667 CGF.EmitBlock(BadTypeidBlock);
1668 EmitBadTypeidCall(CGF);
1669 CGF.EmitBlock(EndBlock);
1670 }
1671 }
1672
1673 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1674 StdTypeInfoPtrTy->getPointerTo());
1675
1676 // Load the type info.
1677 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1678 return CGF.Builder.CreateLoad(Value);
1679}
1680
John McCall3ad32c82011-01-28 08:37:24 +00001681llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001682 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001683 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001684
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001685 if (E->isTypeOperand()) {
1686 llvm::Constant *TypeInfo =
1687 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001688 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001689 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001690
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001691 // C++ [expr.typeid]p2:
1692 // When typeid is applied to a glvalue expression whose type is a
1693 // polymorphic class type, the result refers to a std::type_info object
1694 // representing the type of the most derived object (that is, the dynamic
1695 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001696 if (E->isPotentiallyEvaluated())
1697 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1698 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001699
1700 QualType OperandTy = E->getExprOperand()->getType();
1701 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1702 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001703}
Mike Stumpc849c052009-11-16 06:50:58 +00001704
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001705static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1706 // void *__dynamic_cast(const void *sub,
1707 // const abi::__class_type_info *src,
1708 // const abi::__class_type_info *dst,
1709 // std::ptrdiff_t src2dst_offset);
1710
Chris Lattner8b418682012-02-07 00:39:47 +00001711 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001712 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001713 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1714
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001715 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Benjamin Kramer21f6b392013-02-03 17:44:25 +00001716
1717 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1718
1719 // Mark the function as nounwind readonly.
1720 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1721 llvm::Attribute::ReadOnly };
1722 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1723 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1724
1725 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001726}
1727
1728static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1729 // void __cxa_bad_cast();
Chris Lattner8b418682012-02-07 00:39:47 +00001730 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001731 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1732}
1733
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001734static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001735 llvm::Value *Fn = getBadCastFn(CGF);
John McCallbd7370a2013-02-28 19:01:20 +00001736 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001737 CGF.Builder.CreateUnreachable();
1738}
1739
Benjamin Kramerae3f7602013-02-03 19:59:25 +00001740/// \brief Compute the src2dst_offset hint as described in the
1741/// Itanium C++ ABI [2.9.7]
1742static CharUnits computeOffsetHint(ASTContext &Context,
1743 const CXXRecordDecl *Src,
1744 const CXXRecordDecl *Dst) {
1745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1746 /*DetectVirtual=*/false);
1747
1748 // If Dst is not derived from Src we can skip the whole computation below and
1749 // return that Src is not a public base of Dst. Record all inheritance paths.
1750 if (!Dst->isDerivedFrom(Src, Paths))
1751 return CharUnits::fromQuantity(-2ULL);
1752
1753 unsigned NumPublicPaths = 0;
1754 CharUnits Offset;
1755
1756 // Now walk all possible inheritance paths.
1757 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
1758 I != E; ++I) {
1759 if (I->Access != AS_public) // Ignore non-public inheritance.
1760 continue;
1761
1762 ++NumPublicPaths;
1763
1764 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1765 // If the path contains a virtual base class we can't give any hint.
1766 // -1: no hint.
1767 if (J->Base->isVirtual())
1768 return CharUnits::fromQuantity(-1ULL);
1769
1770 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1771 continue;
1772
1773 // Accumulate the base class offsets.
1774 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1775 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1776 }
1777 }
1778
1779 // -2: Src is not a public base of Dst.
1780 if (NumPublicPaths == 0)
1781 return CharUnits::fromQuantity(-2ULL);
1782
1783 // -3: Src is a multiple public base type but never a virtual base type.
1784 if (NumPublicPaths > 1)
1785 return CharUnits::fromQuantity(-3ULL);
1786
1787 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1788 // Return the offset of Src from the origin of Dst.
1789 return Offset;
1790}
1791
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001792static llvm::Value *
1793EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1794 QualType SrcTy, QualType DestTy,
1795 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001796 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001797 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001798 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001799
1800 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1801 if (PTy->getPointeeType()->isVoidType()) {
1802 // C++ [expr.dynamic.cast]p7:
1803 // If T is "pointer to cv void," then the result is a pointer to the
1804 // most derived object pointed to by v.
1805
1806 // Get the vtable pointer.
1807 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1808
1809 // Get the offset-to-top from the vtable.
1810 llvm::Value *OffsetToTop =
1811 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1812 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1813
1814 // Finally, add the offset to the pointer.
1815 Value = CGF.EmitCastToVoidPtr(Value);
1816 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1817
1818 return CGF.Builder.CreateBitCast(Value, DestLTy);
1819 }
1820 }
1821
1822 QualType SrcRecordTy;
1823 QualType DestRecordTy;
1824
1825 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1826 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1827 DestRecordTy = DestPTy->getPointeeType();
1828 } else {
1829 SrcRecordTy = SrcTy;
1830 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1831 }
1832
1833 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1834 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1835
1836 llvm::Value *SrcRTTI =
1837 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1838 llvm::Value *DestRTTI =
1839 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1840
Benjamin Kramerae3f7602013-02-03 19:59:25 +00001841 // Compute the offset hint.
1842 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1843 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1844 llvm::Value *OffsetHint =
1845 llvm::ConstantInt::get(PtrDiffLTy,
1846 computeOffsetHint(CGF.getContext(), SrcDecl,
1847 DestDecl).getQuantity());
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001848
1849 // Emit the call to __dynamic_cast.
1850 Value = CGF.EmitCastToVoidPtr(Value);
John McCallbd7370a2013-02-28 19:01:20 +00001851
1852 llvm::Value *args[] = { Value, SrcRTTI, DestRTTI, OffsetHint };
1853 Value = CGF.EmitNounwindRuntimeCall(getDynamicCastFn(CGF), args);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001854 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1855
1856 /// C++ [expr.dynamic.cast]p9:
1857 /// A failed cast to reference type throws std::bad_cast
1858 if (DestTy->isReferenceType()) {
1859 llvm::BasicBlock *BadCastBlock =
1860 CGF.createBasicBlock("dynamic_cast.bad_cast");
1861
1862 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1863 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1864
1865 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001866 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001867 }
1868
1869 return Value;
1870}
1871
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001872static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1873 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001874 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001875 if (DestTy->isPointerType())
1876 return llvm::Constant::getNullValue(DestLTy);
1877
1878 /// C++ [expr.dynamic.cast]p9:
1879 /// A failed cast to reference type throws std::bad_cast
1880 EmitBadCastCall(CGF);
1881
1882 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1883 return llvm::UndefValue::get(DestLTy);
1884}
1885
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001886llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001887 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001888 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001889
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001890 if (DCE->isAlwaysNull())
1891 return EmitDynamicCastToNull(*this, DestTy);
1892
1893 QualType SrcTy = DCE->getSubExpr()->getType();
1894
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001895 // C++ [expr.dynamic.cast]p4:
1896 // If the value of v is a null pointer value in the pointer case, the result
1897 // is the null pointer value of type T.
1898 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001899
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001900 llvm::BasicBlock *CastNull = 0;
1901 llvm::BasicBlock *CastNotNull = 0;
1902 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001903
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001904 if (ShouldNullCheckSrcValue) {
1905 CastNull = createBasicBlock("dynamic_cast.null");
1906 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1907
1908 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1909 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1910 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001911 }
1912
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001913 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1914
1915 if (ShouldNullCheckSrcValue) {
1916 EmitBranch(CastEnd);
1917
1918 EmitBlock(CastNull);
1919 EmitBranch(CastEnd);
1920 }
1921
1922 EmitBlock(CastEnd);
1923
1924 if (ShouldNullCheckSrcValue) {
1925 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1926 PHI->addIncoming(Value, CastNotNull);
1927 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1928
1929 Value = PHI;
1930 }
1931
1932 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001933}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001934
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001935void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001936 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001937 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1938 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001939
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001940 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1941 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1942 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001943 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001944 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001945
David Blaikie581deb32012-06-06 20:45:41 +00001946 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001947 ArrayRef<VarDecl *> ArrayIndexes;
1948 if (CurField->getType()->isArrayType())
1949 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001950 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001951 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001952}