blob: 425a968c13a6c0673925e3caeb3ce384ae25f3a4 [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"
Mark Lacey8b549992013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070021#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000023
Anders Carlsson16d81b82009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Stephen Hines176edba2014-12-01 14:53:08 -080027static RequiredArgs commonEmitCXXMemberOrOperatorCall(
28 CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
29 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
31 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Stephen Hines176edba2014-12-01 14:53:08 -080034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +000035
Richard Smith2c9f87c2012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Stephen Hines176edba2014-12-01 14:53:08 -080039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
42 CGF.EmitTypeCheck(
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000046
47 // Push the this ptr.
Stephen Hines176edba2014-12-01 14:53:08 -080048 Args.add(RValue::get(This), MD->getThisType(CGF.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 Carlsson3b5ad222010-01-01 20:29:01 +000057
Stephen Hines176edba2014-12-01 14:53:08 -080058 // And the rest of the call args.
59 if (CE) {
60 // Special case: skip first argument of CXXOperatorCall (it is "this").
61 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
62 CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
63 CE->getDirectCallee());
64 } else {
65 assert(
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
68 }
69 return required;
70}
71
72RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
73 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
75 const CallExpr *CE) {
76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77 CallArgList Args;
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79 *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
80 Args);
John McCall0f3d0972012-07-07 06:41:13 +000081 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000082 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000083}
84
Stephen Hines176edba2014-12-01 14:53:08 -080085RValue CodeGenFunction::EmitCXXStructorCall(
86 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
87 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
88 const CallExpr *CE, StructorType Type) {
89 CallArgList Args;
90 commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
91 ImplicitParam, ImplicitParamTy, CE, Args);
92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
93 Callee, ReturnValue, Args, MD);
94}
95
Rafael Espindolaea01d762012-06-28 14:28:57 +000096static CXXRecordDecl *getCXXRecord(const Expr *E) {
97 QualType T = E->getType();
98 if (const PointerType *PTy = T->getAs<PointerType>())
99 T = PTy->getPointeeType();
100 const RecordType *Ty = T->castAs<RecordType>();
101 return cast<CXXRecordDecl>(Ty->getDecl());
102}
103
Francois Pichetdbee3412011-01-18 05:04:39 +0000104// Note: This function also emit constructor calls to support a MSVC
105// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000106RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000108 const Expr *callee = CE->getCallee()->IgnoreParens();
109
110 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000112
113 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
115
116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Stephen Hines176edba2014-12-01 14:53:08 -0800119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
120 ReturnValue);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000121 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000122
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700123 bool HasQualifier = ME->hasQualifier();
124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125 bool IsArrow = ME->isArrow();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000126 const Expr *Base = ME->getBase();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700127
128 return EmitCXXMemberOrOperatorMemberCallExpr(
129 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
130}
131
132RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
133 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
134 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
135 const Expr *Base) {
136 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
137
138 // Compute the object pointer.
139 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000140
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700141 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer9581ed02013-08-25 22:46:27 +0000142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000143 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
144 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
145 assert(DevirtualizedMethod);
146 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
147 const Expr *Inner = Base->ignoreParenBaseCasts();
Stephen Hines176edba2014-12-01 14:53:08 -0800148 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
149 MD->getReturnType().getCanonicalType())
150 // If the return types are not the same, this might be a case where more
151 // code needs to run to compensate for it. For example, the derived
152 // method might return a type that inherits form from the return
153 // type of MD and has a prefix.
154 // For now we just avoid devirtualizing these covariant cases.
155 DevirtualizedMethod = nullptr;
156 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindolaea01d762012-06-28 14:28:57 +0000157 // If the class of the Inner expression is where the dynamic method
158 // is defined, build the this pointer from it.
159 Base = Inner;
160 else if (getCXXRecord(Base) != DevirtualizedClass) {
161 // If the method is defined in a class that is not the best dynamic
162 // one or the one of the full expression, we would have to build
163 // a derived-to-base cast to compute the correct this pointer, but
164 // we don't have support for that yet, so do a virtual call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700165 DevirtualizedMethod = nullptr;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000166 }
167 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000168
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000169 llvm::Value *This;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700170 if (IsArrow)
Rafael Espindolaea01d762012-06-28 14:28:57 +0000171 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000172 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000173 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000174
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000175
John McCallfc400282010-09-03 01:26:39 +0000176 if (MD->isTrivial()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichetdbee3412011-01-18 05:04:39 +0000178 if (isa<CXXConstructorDecl>(MD) &&
179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700180 return RValue::get(nullptr);
John McCallfc400282010-09-03 01:26:39 +0000181
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700182 if (!MD->getParent()->mayInsertExtraPadding()) {
183 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
184 // We don't like to generate the trivial copy/move assignment operator
185 // when it isn't necessary; just produce the proper effect here.
186 // Special case: skip first argument of CXXOperatorCall (it is "this").
187 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
188 llvm::Value *RHS =
189 EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
190 EmitAggregateAssign(This, RHS, CE->getType());
191 return RValue::get(This);
192 }
Stephen Hines176edba2014-12-01 14:53:08 -0800193
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700194 if (isa<CXXConstructorDecl>(MD) &&
195 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
196 // Trivial move and copy ctor are the same.
197 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
198 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
199 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
200 return RValue::get(This);
201 }
202 llvm_unreachable("unknown trivial member function");
Francois Pichetdbee3412011-01-18 05:04:39 +0000203 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000204 }
205
John McCallfc400282010-09-03 01:26:39 +0000206 // Compute the function type we're calling.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700207 const CXXMethodDecl *CalleeDecl =
208 DevirtualizedMethod ? DevirtualizedMethod : MD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700209 const CGFunctionInfo *FInfo = nullptr;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700210 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Stephen Hines176edba2014-12-01 14:53:08 -0800211 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
212 Dtor, StructorType::Complete);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700213 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Stephen Hines176edba2014-12-01 14:53:08 -0800214 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
215 Ctor, StructorType::Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000216 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000217 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000218
Reid Klecknera4130ba2013-07-22 13:51:44 +0000219 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000220
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000221 // C++ [class.virtual]p12:
222 // Explicit qualification with the scope operator (5.1) suppresses the
223 // virtual call mechanism.
224 //
225 // We also don't emit a virtual call if the base expression has a record type
226 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000227 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin3258abc2013-06-19 23:23:19 +0000228 llvm::Value *Callee;
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000229
John McCallfc400282010-09-03 01:26:39 +0000230 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000231 assert(CE->arg_begin() == CE->arg_end() &&
232 "Destructor shouldn't have explicit parameters");
233 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCallfc400282010-09-03 01:26:39 +0000234 if (UseVirtualCall) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700235 CGM.getCXXABI().EmitVirtualDestructorCall(
236 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000237 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700238 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
239 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000240 else if (!DevirtualizedMethod)
Stephen Hines176edba2014-12-01 14:53:08 -0800241 Callee =
242 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000243 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000244 const CXXDestructorDecl *DDtor =
245 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000246 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
247 }
Stephen Hines176edba2014-12-01 14:53:08 -0800248 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
249 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000250 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700251 return RValue::get(nullptr);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000252 }
253
254 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichetdbee3412011-01-18 05:04:39 +0000255 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000256 } else if (UseVirtualCall) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000257 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000258 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700259 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
260 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000261 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000262 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000263 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000264 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000265 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000266 }
267
Stephen Hines651f13c2014-04-23 16:59:28 -0700268 if (MD->isVirtual()) {
269 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
270 *this, MD, This, UseVirtualCall);
271 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000272
Stephen Hines176edba2014-12-01 14:53:08 -0800273 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
274 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000275}
276
277RValue
278CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
279 ReturnValueSlot ReturnValue) {
280 const BinaryOperator *BO =
281 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
282 const Expr *BaseExpr = BO->getLHS();
283 const Expr *MemFnExpr = BO->getRHS();
284
285 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000286 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000287
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000288 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000289 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000290 const CXXRecordDecl *RD =
291 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
292
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000293 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000294 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000295
296 // Emit the 'this' pointer.
297 llvm::Value *This;
298
John McCall2de56d12010-08-25 11:45:40 +0000299 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000300 This = EmitScalarExpr(BaseExpr);
301 else
302 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000303
Richard Smith4def70d2012-10-09 19:52:38 +0000304 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
305 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000306
John McCall93d557b2010-08-22 00:05:51 +0000307 // Ask the ABI to load the callee. Note that This is modified.
308 llvm::Value *Callee =
Stephen Hines651f13c2014-04-23 16:59:28 -0700309 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000310
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000311 CallArgList Args;
312
313 QualType ThisType =
314 getContext().getPointerType(getContext().getTagDeclType(RD));
315
316 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000317 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000318
319 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000320
321 // And the rest of the call args
Stephen Hines176edba2014-12-01 14:53:08 -0800322 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5d4a7552013-10-01 21:51:38 +0000323 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
324 Callee, ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000325}
326
327RValue
328CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
329 const CXXMethodDecl *MD,
330 ReturnValueSlot ReturnValue) {
331 assert(MD->isInstance() &&
332 "Trying to emit a member call expr on a static method!");
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700333 return EmitCXXMemberOrOperatorMemberCallExpr(
334 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
335 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000336}
337
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000338RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
339 ReturnValueSlot ReturnValue) {
340 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
341}
342
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000343static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
344 llvm::Value *DestPtr,
345 const CXXRecordDecl *Base) {
346 if (Base->isEmpty())
347 return;
348
349 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
350
351 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
352 CharUnits Size = Layout.getNonVirtualSize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700353 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000354
355 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
356
357 // If the type contains a pointer to data member we can't memset it to zero.
358 // Instead, create a null constant and copy it to the destination.
359 // TODO: there are other patterns besides zero that we can usefully memset,
360 // like -1, which happens to be the pattern used by member-pointers.
361 // TODO: isZeroInitializable can be over-conservative in the case where a
362 // virtual base contains a member pointer.
363 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
364 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
365
366 llvm::GlobalVariable *NullVariable =
367 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
368 /*isConstant=*/true,
369 llvm::GlobalVariable::PrivateLinkage,
370 NullConstant, Twine());
371 NullVariable->setAlignment(Align.getQuantity());
372 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
373
374 // Get and call the appropriate llvm.memcpy overload.
375 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
376 return;
377 }
378
379 // Otherwise, just memset the whole thing to zero. This is legal
380 // because in LLVM, all default initializers (other than the ones we just
381 // handled above) are guaranteed to have a bit pattern of all zeros.
382 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
383 Align.getQuantity());
384}
385
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000386void
John McCall558d2ab2010-09-15 10:14:12 +0000387CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
388 AggValueSlot Dest) {
389 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000390 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000391
392 // If we require zero initialization before (or instead of) calling the
393 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000394 // constructor, emit the zero initialization now, unless destination is
395 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000396 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
397 switch (E->getConstructionKind()) {
398 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000399 case CXXConstructExpr::CK_Complete:
400 EmitNullInitialization(Dest.getAddr(), E->getType());
401 break;
402 case CXXConstructExpr::CK_VirtualBase:
403 case CXXConstructExpr::CK_NonVirtualBase:
404 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
405 break;
406 }
407 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000408
409 // If this is a call to a trivial default constructor, do nothing.
410 if (CD->isTrivial() && CD->isDefaultConstructor())
411 return;
412
John McCallfc1e6c72010-09-18 00:58:34 +0000413 // Elide the constructor if we're constructing from a temporary.
414 // The temporary check is required because Sema sets this on NRVO
415 // returns.
Richard Smith7edf9e32012-11-01 22:30:59 +0000416 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000417 assert(getContext().hasSameUnqualifiedType(E->getType(),
418 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000419 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
420 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000421 return;
422 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000423 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000424
John McCallc3c07662011-07-13 06:10:41 +0000425 if (const ConstantArrayType *arrayType
426 = getContext().getAsConstantArrayType(E->getType())) {
Stephen Hines176edba2014-12-01 14:53:08 -0800427 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallc3c07662011-07-13 06:10:41 +0000428 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000429 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000430 bool ForVirtualBase = false;
Douglas Gregor378e1e72013-01-31 05:50:40 +0000431 bool Delegating = false;
432
Sean Huntd49bd552011-05-03 20:19:28 +0000433 switch (E->getConstructionKind()) {
434 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000435 // We should be emitting a constructor; GlobalDecl will assert this
436 Type = CurGD.getCtorType();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000437 Delegating = true;
Sean Huntd49bd552011-05-03 20:19:28 +0000438 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000439
Sean Huntd49bd552011-05-03 20:19:28 +0000440 case CXXConstructExpr::CK_Complete:
441 Type = Ctor_Complete;
442 break;
443
444 case CXXConstructExpr::CK_VirtualBase:
445 ForVirtualBase = true;
446 // fall-through
447
448 case CXXConstructExpr::CK_NonVirtualBase:
449 Type = Ctor_Base;
450 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000451
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000452 // Call the constructor.
Douglas Gregor378e1e72013-01-31 05:50:40 +0000453 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Stephen Hines176edba2014-12-01 14:53:08 -0800454 E);
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000455 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000456}
457
Fariborz Jahanian34999872010-11-13 21:53:34 +0000458void
459CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
460 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000461 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000462 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000463 Exp = E->getSubExpr();
464 assert(isa<CXXConstructExpr>(Exp) &&
465 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
466 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
467 const CXXConstructorDecl *CD = E->getConstructor();
468 RunCleanupsScope Scope(*this);
469
470 // If we require zero initialization before (or instead of) calling the
471 // constructor, as can be the case with a non-user-provided default
472 // constructor, emit the zero initialization now.
473 // FIXME. Do I still need this for a copy ctor synthesis?
474 if (E->requiresZeroInitialization())
475 EmitNullInitialization(Dest, E->getType());
476
Chandler Carruth858a5462010-11-15 13:54:43 +0000477 assert(!getContext().getAsConstantArrayType(E->getType())
478 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Stephen Hines176edba2014-12-01 14:53:08 -0800479 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahanian34999872010-11-13 21:53:34 +0000480}
481
John McCall1e7fe752010-09-02 09:58:18 +0000482static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
483 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000484 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000485 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000486
John McCallb1c98a32011-05-16 01:05:12 +0000487 // No cookie is required if the operator new[] being used is the
488 // reserved placement operator new[].
489 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000490 return CharUnits::Zero();
491
John McCall6ec278d2011-01-27 09:37:56 +0000492 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000493}
494
John McCall7d166272011-05-15 07:14:44 +0000495static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
496 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000497 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000498 llvm::Value *&numElements,
499 llvm::Value *&sizeWithoutCookie) {
500 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000501
John McCall7d166272011-05-15 07:14:44 +0000502 if (!e->isArray()) {
503 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
504 sizeWithoutCookie
505 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
506 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000507 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000508
John McCall7d166272011-05-15 07:14:44 +0000509 // The width of size_t.
510 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
511
John McCall1e7fe752010-09-02 09:58:18 +0000512 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000513 llvm::APInt cookieSize(sizeWidth,
514 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000515
Anders Carlssona4d4c012009-09-23 16:07:23 +0000516 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000517 // We multiply the size of all dimensions for NumElements.
518 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000519 numElements = CGF.EmitScalarExpr(e->getArraySize());
520 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000521
John McCall7d166272011-05-15 07:14:44 +0000522 // The number of elements can be have an arbitrary integer type;
523 // essentially, we need to multiply it by a constant factor, add a
524 // cookie size, and verify that the result is representable as a
525 // size_t. That's just a gloss, though, and it's wrong in one
526 // important way: if the count is negative, it's an error even if
527 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000528 bool isSigned
529 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000530 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000531 = cast<llvm::IntegerType>(numElements->getType());
532 unsigned numElementsWidth = numElementsType->getBitWidth();
533
534 // Compute the constant factor.
535 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000536 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000537 = CGF.getContext().getAsConstantArrayType(type)) {
538 type = CAT->getElementType();
539 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000540 }
541
John McCall7d166272011-05-15 07:14:44 +0000542 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
543 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
544 typeSizeMultiplier *= arraySizeMultiplier;
545
546 // This will be a size_t.
547 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000548
Chris Lattner806941e2010-07-20 21:55:52 +0000549 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
550 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000551 if (llvm::ConstantInt *numElementsC =
552 dyn_cast<llvm::ConstantInt>(numElements)) {
553 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000554
John McCall7d166272011-05-15 07:14:44 +0000555 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000556
John McCall7d166272011-05-15 07:14:44 +0000557 // If 'count' was a negative number, it's an overflow.
558 if (isSigned && count.isNegative())
559 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000560
John McCall7d166272011-05-15 07:14:44 +0000561 // We want to do all this arithmetic in size_t. If numElements is
562 // wider than that, check whether it's already too big, and if so,
563 // overflow.
564 else if (numElementsWidth > sizeWidth &&
565 numElementsWidth - sizeWidth > count.countLeadingZeros())
566 hasAnyOverflow = true;
567
568 // Okay, compute a count at the right width.
569 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
570
Sebastian Redl92036472012-02-22 17:37:52 +0000571 // If there is a brace-initializer, we cannot allocate fewer elements than
572 // there are initializers. If we do, that's treated like an overflow.
573 if (adjustedCount.ult(minElements))
574 hasAnyOverflow = true;
575
John McCall7d166272011-05-15 07:14:44 +0000576 // Scale numElements by that. This might overflow, but we don't
577 // care because it only overflows if allocationSize does, too, and
578 // if that overflows then we shouldn't use this.
579 numElements = llvm::ConstantInt::get(CGF.SizeTy,
580 adjustedCount * arraySizeMultiplier);
581
582 // Compute the size before cookie, and track whether it overflowed.
583 bool overflow;
584 llvm::APInt allocationSize
585 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
586 hasAnyOverflow |= overflow;
587
588 // Add in the cookie, and check whether it's overflowed.
589 if (cookieSize != 0) {
590 // Save the current size without a cookie. This shouldn't be
591 // used if there was overflow.
592 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
593
594 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
595 hasAnyOverflow |= overflow;
596 }
597
598 // On overflow, produce a -1 so operator new will fail.
599 if (hasAnyOverflow) {
600 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
601 } else {
602 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
603 }
604
605 // Otherwise, we might need to use the overflow intrinsics.
606 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000607 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000608 // 1) if isSigned, we need to check whether numElements is negative;
609 // 2) if numElementsWidth > sizeWidth, we need to check whether
610 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000611 // 3) if minElements > 0, we need to check whether numElements is smaller
612 // than that.
613 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000614 // sizeWithoutCookie := numElements * typeSizeMultiplier
615 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000616 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000617 // size := sizeWithoutCookie + cookieSize
618 // and check whether it overflows.
619
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700620 llvm::Value *hasOverflow = nullptr;
John McCall7d166272011-05-15 07:14:44 +0000621
622 // If numElementsWidth > sizeWidth, then one way or another, we're
623 // going to have to do a comparison for (2), and this happens to
624 // take care of (1), too.
625 if (numElementsWidth > sizeWidth) {
626 llvm::APInt threshold(numElementsWidth, 1);
627 threshold <<= sizeWidth;
628
629 llvm::Value *thresholdV
630 = llvm::ConstantInt::get(numElementsType, threshold);
631
632 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
633 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
634
635 // Otherwise, if we're signed, we want to sext up to size_t.
636 } else if (isSigned) {
637 if (numElementsWidth < sizeWidth)
638 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
639
640 // If there's a non-1 type size multiplier, then we can do the
641 // signedness check at the same time as we do the multiply
642 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000643 // unsigned overflow. Otherwise, we have to do it here. But at least
644 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000645 if (typeSizeMultiplier == 1)
646 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000647 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000648
649 // Otherwise, zext up to size_t if necessary.
650 } else if (numElementsWidth < sizeWidth) {
651 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
652 }
653
654 assert(numElements->getType() == CGF.SizeTy);
655
Sebastian Redl92036472012-02-22 17:37:52 +0000656 if (minElements) {
657 // Don't allow allocation of fewer elements than we have initializers.
658 if (!hasOverflow) {
659 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
660 llvm::ConstantInt::get(CGF.SizeTy, minElements));
661 } else if (numElementsWidth > sizeWidth) {
662 // The other existing overflow subsumes this check.
663 // We do an unsigned comparison, since any signed value < -1 is
664 // taken care of either above or below.
665 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
666 CGF.Builder.CreateICmpULT(numElements,
667 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
668 }
669 }
670
John McCall7d166272011-05-15 07:14:44 +0000671 size = numElements;
672
673 // Multiply by the type size if necessary. This multiplier
674 // includes all the factors for nested arrays.
675 //
676 // This step also causes numElements to be scaled up by the
677 // nested-array factor if necessary. Overflow on this computation
678 // can be ignored because the result shouldn't be used if
679 // allocation fails.
680 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000681 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000682 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000683
684 llvm::Value *tsmV =
685 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
686 llvm::Value *result =
687 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
688
689 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
690 if (hasOverflow)
691 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
692 else
693 hasOverflow = overflowed;
694
695 size = CGF.Builder.CreateExtractValue(result, 0);
696
697 // Also scale up numElements by the array size multiplier.
698 if (arraySizeMultiplier != 1) {
699 // If the base element type size is 1, then we can re-use the
700 // multiply we just did.
701 if (typeSize.isOne()) {
702 assert(arraySizeMultiplier == typeSizeMultiplier);
703 numElements = size;
704
705 // Otherwise we need a separate multiply.
706 } else {
707 llvm::Value *asmV =
708 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
709 numElements = CGF.Builder.CreateMul(numElements, asmV);
710 }
711 }
712 } else {
713 // numElements doesn't need to be scaled.
714 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000715 }
716
John McCall7d166272011-05-15 07:14:44 +0000717 // Add in the cookie size if necessary.
718 if (cookieSize != 0) {
719 sizeWithoutCookie = size;
720
John McCall7d166272011-05-15 07:14:44 +0000721 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000722 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000723
724 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
725 llvm::Value *result =
726 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
727
728 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
729 if (hasOverflow)
730 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
731 else
732 hasOverflow = overflowed;
733
734 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000735 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000736
John McCall7d166272011-05-15 07:14:44 +0000737 // If we had any possibility of dynamic overflow, make a select to
738 // overwrite 'size' with an all-ones value, which should cause
739 // operator new to throw.
740 if (hasOverflow)
741 size = CGF.Builder.CreateSelect(hasOverflow,
742 llvm::Constant::getAllOnesValue(CGF.SizeTy),
743 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000744 }
John McCall1e7fe752010-09-02 09:58:18 +0000745
John McCall7d166272011-05-15 07:14:44 +0000746 if (cookieSize == 0)
747 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000748 else
John McCall7d166272011-05-15 07:14:44 +0000749 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000750
John McCall7d166272011-05-15 07:14:44 +0000751 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000752}
753
Sebastian Redl92036472012-02-22 17:37:52 +0000754static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
755 QualType AllocType, llvm::Value *NewPtr) {
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000756 // FIXME: Refactor with EmitExprAsInit.
Eli Friedmand7722d92011-12-03 02:13:40 +0000757 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall9d232c82013-03-07 21:37:08 +0000758 switch (CGF.getEvaluationKind(AllocType)) {
759 case TEK_Scalar:
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700760 CGF.EmitScalarInit(Init, nullptr,
761 CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
John McCall9d232c82013-03-07 21:37:08 +0000762 return;
763 case TEK_Complex:
764 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
765 Alignment),
766 /*isInit*/ true);
767 return;
768 case TEK_Aggregate: {
John McCall558d2ab2010-09-15 10:14:12 +0000769 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000770 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000771 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000772 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000773 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000774 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000775 return;
John McCall558d2ab2010-09-15 10:14:12 +0000776 }
John McCall9d232c82013-03-07 21:37:08 +0000777 }
778 llvm_unreachable("bad evaluation kind");
Fariborz Jahanianef668722010-06-25 18:26:07 +0000779}
780
781void
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700782CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
783 QualType ElementType,
784 llvm::Value *BeginPtr,
785 llvm::Value *NumElements,
786 llvm::Value *AllocSizeWithoutCookie) {
787 // If we have a type with trivial initialization and no initializer,
788 // there's nothing to do.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000789 if (!E->hasInitializer())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700790 return;
John McCall19705672011-09-15 06:49:18 +0000791
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700792 llvm::Value *CurPtr = BeginPtr;
John McCall19705672011-09-15 06:49:18 +0000793
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700794 unsigned InitListElements = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000795
796 const Expr *Init = E->getInitializer();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700797 llvm::AllocaInst *EndOfInit = nullptr;
798 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
799 EHScopeStack::stable_iterator Cleanup;
800 llvm::Instruction *CleanupDominator = nullptr;
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000801
Sebastian Redl92036472012-02-22 17:37:52 +0000802 // If the initializer is an initializer list, first do the explicit elements.
803 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700804 InitListElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000805
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000806 // If this is a multi-dimensional array new, we will initialize multiple
807 // elements with each init list element.
808 QualType AllocType = E->getAllocatedType();
809 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
810 AllocType->getAsArrayTypeUnsafe())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700811 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000812 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700813 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
814 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000815 }
816
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700817 // Enter a partial-destruction Cleanup if necessary.
818 if (needsEHCleanup(DtorKind)) {
819 // In principle we could tell the Cleanup where we are more
Chad Rosier577fb5b2012-02-24 00:13:55 +0000820 // directly, but the control flow can get so varied here that it
821 // would actually be quite complex. Therefore we go through an
822 // alloca.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700823 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
824 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
825 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
826 getDestroyer(DtorKind));
827 Cleanup = EHStack.stable_begin();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000828 }
829
Sebastian Redl92036472012-02-22 17:37:52 +0000830 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000831 // Tell the cleanup that it needs to destroy up to this
832 // element. TODO: some of these stores can be trivially
833 // observed to be unnecessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700834 if (EndOfInit)
835 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
836 EndOfInit);
837 // FIXME: If the last initializer is an incomplete initializer list for
838 // an array, and we have an array filler, we can fold together the two
839 // initialization loops.
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000840 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700841 ILE->getInit(i)->getType(), CurPtr);
842 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redl92036472012-02-22 17:37:52 +0000843 }
844
845 // The remaining elements are filled with the array filler expression.
846 Init = ILE->getArrayFiller();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000847
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700848 // Extract the initializer for the individual array elements by pulling
849 // out the array filler from all the nested initializer lists. This avoids
850 // generating a nested loop for the initialization.
851 while (Init && Init->getType()->isConstantArrayType()) {
852 auto *SubILE = dyn_cast<InitListExpr>(Init);
853 if (!SubILE)
854 break;
855 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
856 Init = SubILE->getArrayFiller();
857 }
858
859 // Switch back to initializing one base element at a time.
860 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redl92036472012-02-22 17:37:52 +0000861 }
862
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700863 // Attempt to perform zero-initialization using memset.
864 auto TryMemsetInitialization = [&]() -> bool {
865 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
866 // we can initialize with a memset to -1.
867 if (!CGM.getTypes().isZeroInitializable(ElementType))
868 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700869
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700870 // Optimization: since zero initialization will just set the memory
871 // to all zeroes, generate a single memset to do it in one shot.
872
873 // Subtract out the size of any elements we've already initialized.
874 auto *RemainingSize = AllocSizeWithoutCookie;
875 if (InitListElements) {
876 // We know this can't overflow; we check this when doing the allocation.
877 auto *InitializedSize = llvm::ConstantInt::get(
878 RemainingSize->getType(),
879 getContext().getTypeSizeInChars(ElementType).getQuantity() *
880 InitListElements);
881 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
882 }
883
884 // Create the memset.
885 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
886 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
887 Alignment.getQuantity(), false);
888 return true;
889 };
890
891 // If all elements have already been initialized, skip any further
892 // initialization.
893 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
894 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
895 // If there was a Cleanup, deactivate it.
896 if (CleanupDominator)
897 DeactivateCleanupBlock(Cleanup, CleanupDominator);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700898 return;
899 }
900
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700901 assert(Init && "have trailing elements to initialize but no initializer");
902
903 // If this is a constructor call, try to optimize it out, and failing that
904 // emit a single loop to initialize all remaining elements.
905 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
906 CXXConstructorDecl *Ctor = CCE->getConstructor();
907 if (Ctor->isTrivial()) {
908 // If new expression did not specify value-initialization, then there
909 // is no initialization.
910 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
911 return;
912
913 if (TryMemsetInitialization())
914 return;
915 }
916
917 // Store the new Cleanup position for irregular Cleanups.
918 //
919 // FIXME: Share this cleanup with the constructor call emission rather than
920 // having it create a cleanup of its own.
921 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
922
923 // Emit a constructor call loop to initialize the remaining elements.
924 if (InitListElements)
925 NumElements = Builder.CreateSub(
926 NumElements,
927 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Stephen Hines176edba2014-12-01 14:53:08 -0800928 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700929 CCE->requiresZeroInitialization());
930 return;
931 }
932
933 // If this is value-initialization, we can usually use memset.
934 ImplicitValueInitExpr IVIE(ElementType);
935 if (isa<ImplicitValueInitExpr>(Init)) {
936 if (TryMemsetInitialization())
937 return;
938
939 // Switch to an ImplicitValueInitExpr for the element type. This handles
940 // only one case: multidimensional array new of pointers to members. In
941 // all other cases, we already have an initializer for the array element.
942 Init = &IVIE;
943 }
944
945 // At this point we should have found an initializer for the individual
946 // elements of the array.
947 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
948 "got wrong type of element to initialize");
949
950 // If we have an empty initializer list, we can usually use memset.
951 if (auto *ILE = dyn_cast<InitListExpr>(Init))
952 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
953 return;
954
955 // Create the loop blocks.
956 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
957 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
958 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
959
960 // Find the end of the array, hoisted out of the loop.
961 llvm::Value *EndPtr =
962 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall19705672011-09-15 06:49:18 +0000963
Sebastian Redl92036472012-02-22 17:37:52 +0000964 // If the number of elements isn't constant, we have to now check if there is
965 // anything left to initialize.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700966 if (!ConstNum) {
967 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall19705672011-09-15 06:49:18 +0000968 "array.isempty");
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700969 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall19705672011-09-15 06:49:18 +0000970 }
971
972 // Enter the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700973 EmitBlock(LoopBB);
John McCall19705672011-09-15 06:49:18 +0000974
975 // Set up the current-element phi.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700976 llvm::PHINode *CurPtrPhi =
977 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
978 CurPtrPhi->addIncoming(CurPtr, EntryBB);
979 CurPtr = CurPtrPhi;
John McCall19705672011-09-15 06:49:18 +0000980
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700981 // Store the new Cleanup position for irregular Cleanups.
982 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosier577fb5b2012-02-24 00:13:55 +0000983
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700984 // Enter a partial-destruction Cleanup if necessary.
985 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
986 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
987 getDestroyer(DtorKind));
988 Cleanup = EHStack.stable_begin();
989 CleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000990 }
991
992 // Emit the initializer into this element.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700993 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall19705672011-09-15 06:49:18 +0000994
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700995 // Leave the Cleanup if we entered one.
996 if (CleanupDominator) {
997 DeactivateCleanupBlock(Cleanup, CleanupDominator);
998 CleanupDominator->eraseFromParent();
John McCall6f103ba2011-11-10 10:43:54 +0000999 }
John McCall19705672011-09-15 06:49:18 +00001000
Stephen Hines651f13c2014-04-23 16:59:28 -07001001 // Advance to the next element by adjusting the pointer type as necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001002 llvm::Value *NextPtr =
1003 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
1004
John McCall19705672011-09-15 06:49:18 +00001005 // Check whether we've gotten to the end of the array and, if so,
1006 // exit the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001007 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1008 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1009 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall19705672011-09-15 06:49:18 +00001010
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001011 EmitBlock(ContBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +00001012}
1013
Anders Carlssona4d4c012009-09-23 16:07:23 +00001014static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +00001015 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +00001016 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +00001017 llvm::Value *NumElements,
1018 llvm::Value *AllocSizeWithoutCookie) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001019 ApplyDebugLocation DL(CGF, E);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001020 if (E->isArray())
1021 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
1022 AllocSizeWithoutCookie);
1023 else if (const Expr *Init = E->getInitializer())
1024 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001025}
1026
Richard Smithddcff1b2013-07-21 23:12:18 +00001027/// Emit a call to an operator new or operator delete function, as implicitly
1028/// created by new-expressions and delete-expressions.
1029static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1030 const FunctionDecl *Callee,
1031 const FunctionProtoType *CalleeType,
1032 const CallArgList &Args) {
1033 llvm::Instruction *CallOrInvoke;
Richard Smith060cb4a2013-07-29 20:14:16 +00001034 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smithddcff1b2013-07-21 23:12:18 +00001035 RValue RV =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001036 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1037 Args, CalleeType, /*chainCall=*/false),
1038 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
Richard Smithddcff1b2013-07-21 23:12:18 +00001039
1040 /// C++1y [expr.new]p10:
1041 /// [In a new-expression,] an implementation is allowed to omit a call
1042 /// to a replaceable global allocation function.
1043 ///
1044 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola87017a72013-10-22 14:23:09 +00001045 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith060cb4a2013-07-29 20:14:16 +00001046 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola87017a72013-10-22 14:23:09 +00001047 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smithddcff1b2013-07-21 23:12:18 +00001048 // FIXME: Add addAttribute to CallSite.
1049 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1050 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1051 llvm::Attribute::Builtin);
1052 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1053 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1054 llvm::Attribute::Builtin);
1055 else
1056 llvm_unreachable("unexpected kind of call instruction");
1057 }
1058
1059 return RV;
1060}
1061
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001062RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1063 const Expr *Arg,
1064 bool IsDelete) {
1065 CallArgList Args;
1066 const Stmt *ArgS = Arg;
1067 EmitCallArgs(Args, *Type->param_type_begin(),
1068 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1069 // Find the allocation or deallocation function that we're calling.
1070 ASTContext &Ctx = getContext();
1071 DeclarationName Name = Ctx.DeclarationNames
1072 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1073 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1074 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1075 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1076 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1077 llvm_unreachable("predeclared global operator new/delete is missing");
1078}
1079
John McCall7d8647f2010-09-14 07:57:04 +00001080namespace {
1081 /// A cleanup to call the given 'operator delete' function upon
1082 /// abnormal exit from a new expression.
1083 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1084 size_t NumPlacementArgs;
1085 const FunctionDecl *OperatorDelete;
1086 llvm::Value *Ptr;
1087 llvm::Value *AllocSize;
1088
1089 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1090
1091 public:
1092 static size_t getExtraSize(size_t NumPlacementArgs) {
1093 return NumPlacementArgs * sizeof(RValue);
1094 }
1095
1096 CallDeleteDuringNew(size_t NumPlacementArgs,
1097 const FunctionDecl *OperatorDelete,
1098 llvm::Value *Ptr,
1099 llvm::Value *AllocSize)
1100 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1101 Ptr(Ptr), AllocSize(AllocSize) {}
1102
1103 void setPlacementArg(unsigned I, RValue Arg) {
1104 assert(I < NumPlacementArgs && "index out of range");
1105 getPlacementArgs()[I] = Arg;
1106 }
1107
Stephen Hines651f13c2014-04-23 16:59:28 -07001108 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7d8647f2010-09-14 07:57:04 +00001109 const FunctionProtoType *FPT
1110 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001111 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1112 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001113
1114 CallArgList DeleteArgs;
1115
1116 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001117 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001118 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001119
1120 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001121 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001122 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001123
1124 // Pass the rest of the arguments, which must match exactly.
1125 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001126 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001127
1128 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001129 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7d8647f2010-09-14 07:57:04 +00001130 }
1131 };
John McCall3019c442010-09-17 00:50:28 +00001132
1133 /// A cleanup to call the given 'operator delete' function upon
1134 /// abnormal exit from a new expression when the new expression is
1135 /// conditional.
1136 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1137 size_t NumPlacementArgs;
1138 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001139 DominatingValue<RValue>::saved_type Ptr;
1140 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001141
John McCall804b8072011-01-28 10:53:53 +00001142 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1143 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001144 }
1145
1146 public:
1147 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001148 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001149 }
1150
1151 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1152 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001153 DominatingValue<RValue>::saved_type Ptr,
1154 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001155 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1156 Ptr(Ptr), AllocSize(AllocSize) {}
1157
John McCall804b8072011-01-28 10:53:53 +00001158 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001159 assert(I < NumPlacementArgs && "index out of range");
1160 getPlacementArgs()[I] = Arg;
1161 }
1162
Stephen Hines651f13c2014-04-23 16:59:28 -07001163 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall3019c442010-09-17 00:50:28 +00001164 const FunctionProtoType *FPT
1165 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001166 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1167 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall3019c442010-09-17 00:50:28 +00001168
1169 CallArgList DeleteArgs;
1170
1171 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001172 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001173 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001174
1175 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001176 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001177 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001178 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001179 }
1180
1181 // Pass the rest of the arguments, which must match exactly.
1182 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001183 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001184 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001185 }
1186
1187 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001188 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall3019c442010-09-17 00:50:28 +00001189 }
1190 };
1191}
1192
1193/// Enter a cleanup to call 'operator delete' if the initializer in a
1194/// new-expression throws.
1195static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1196 const CXXNewExpr *E,
1197 llvm::Value *NewPtr,
1198 llvm::Value *AllocSize,
1199 const CallArgList &NewArgs) {
1200 // If we're not inside a conditional branch, then the cleanup will
1201 // dominate and we can do the easier (and more efficient) thing.
1202 if (!CGF.isInConditionalBranch()) {
1203 CallDeleteDuringNew *Cleanup = CGF.EHStack
1204 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1205 E->getNumPlacementArgs(),
1206 E->getOperatorDelete(),
1207 NewPtr, AllocSize);
1208 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001209 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001210
1211 return;
1212 }
1213
1214 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001215 DominatingValue<RValue>::saved_type SavedNewPtr =
1216 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1217 DominatingValue<RValue>::saved_type SavedAllocSize =
1218 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001219
1220 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001221 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001222 E->getNumPlacementArgs(),
1223 E->getOperatorDelete(),
1224 SavedNewPtr,
1225 SavedAllocSize);
1226 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001227 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001228 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001229
John McCall6f103ba2011-11-10 10:43:54 +00001230 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001231}
1232
Anders Carlsson16d81b82009-09-22 22:53:17 +00001233llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001234 // The element type being allocated.
1235 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001236
John McCallc2f3e7f2011-03-07 03:12:35 +00001237 // 1. Build a call to the allocation function.
1238 FunctionDecl *allocator = E->getOperatorNew();
1239 const FunctionProtoType *allocatorType =
1240 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001241
John McCallc2f3e7f2011-03-07 03:12:35 +00001242 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001243
1244 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001245 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001246
Sebastian Redl92036472012-02-22 17:37:52 +00001247 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1248 unsigned minElements = 0;
1249 if (E->isArray() && E->hasInitializer()) {
1250 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1251 minElements = ILE->getNumInits();
1252 }
1253
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001254 llvm::Value *numElements = nullptr;
1255 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCallc2f3e7f2011-03-07 03:12:35 +00001256 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001257 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1258 allocSizeWithoutCookie);
Stephen Hines176edba2014-12-01 14:53:08 -08001259
Eli Friedman04c9a492011-05-02 17:57:46 +00001260 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001261
Anders Carlsson16d81b82009-09-22 22:53:17 +00001262 // We start at 1 here because the first argument (the allocation size)
1263 // has already been emitted.
Stephen Hines176edba2014-12-01 14:53:08 -08001264 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
1265 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1266 /*ParamsToSkip*/ 1);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001267
John McCallb1c98a32011-05-16 01:05:12 +00001268 // Emit the allocation call. If the allocator is a global placement
1269 // operator, just "inline" it directly.
1270 RValue RV;
1271 if (allocator->isReservedGlobalPlacementOperator()) {
1272 assert(allocatorArgs.size() == 2);
1273 RV = allocatorArgs[1].RV;
1274 // TODO: kill any unnecessary computations done for the size
1275 // argument.
1276 } else {
Richard Smithddcff1b2013-07-21 23:12:18 +00001277 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCallb1c98a32011-05-16 01:05:12 +00001278 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001279
John McCallc2f3e7f2011-03-07 03:12:35 +00001280 // Emit a null check on the allocation result if the allocation
1281 // function is allowed to return null (because it has a non-throwing
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001282 // exception spec or is the reserved placement new) and we have an
John McCallc2f3e7f2011-03-07 03:12:35 +00001283 // interesting initializer.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001284 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001285 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001286
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001287 llvm::BasicBlock *nullCheckBB = nullptr;
1288 llvm::BasicBlock *contBB = nullptr;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001289
John McCallc2f3e7f2011-03-07 03:12:35 +00001290 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001291 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001292
John McCalla7f633f2011-03-07 01:52:56 +00001293 // The null-check means that the initializer is conditionally
1294 // evaluated.
1295 ConditionalEvaluation conditional(*this);
1296
John McCallc2f3e7f2011-03-07 03:12:35 +00001297 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001298 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001299
1300 nullCheckBB = Builder.GetInsertBlock();
1301 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1302 contBB = createBasicBlock("new.cont");
1303
1304 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1305 Builder.CreateCondBr(isNull, contBB, notNullBB);
1306 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001307 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001308
John McCall7d8647f2010-09-14 07:57:04 +00001309 // If there's an operator delete, enter a cleanup to call it if an
1310 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001311 EHScopeStack::stable_iterator operatorDeleteCleanup;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001312 llvm::Instruction *cleanupDominator = nullptr;
John McCallb1c98a32011-05-16 01:05:12 +00001313 if (E->getOperatorDelete() &&
1314 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001315 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1316 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001317 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001318 }
1319
Eli Friedman576cf172011-09-06 18:53:03 +00001320 assert((allocSize == allocSizeWithoutCookie) ==
1321 CalculateCookiePadding(*this, E).isZero());
1322 if (allocSize != allocSizeWithoutCookie) {
1323 assert(E->isArray());
1324 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1325 numElements,
1326 E, allocType);
1327 }
1328
Chris Lattner2acc6e32011-07-18 04:24:23 +00001329 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001330 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1331 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001332
John McCall19705672011-09-15 06:49:18 +00001333 EmitNewInitializer(*this, E, allocType, result, numElements,
1334 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001335 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001336 // NewPtr is a pointer to the base element type. If we're
1337 // allocating an array of arrays, we'll need to cast back to the
1338 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001339 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001340 if (result->getType() != resultType)
1341 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001342 }
John McCall7d8647f2010-09-14 07:57:04 +00001343
1344 // Deactivate the 'operator delete' cleanup if we finished
1345 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001346 if (operatorDeleteCleanup.isValid()) {
1347 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1348 cleanupDominator->eraseFromParent();
1349 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001350
John McCallc2f3e7f2011-03-07 03:12:35 +00001351 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001352 conditional.end(*this);
1353
John McCallc2f3e7f2011-03-07 03:12:35 +00001354 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1355 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001356
Jay Foadbbf3bac2011-03-30 11:28:58 +00001357 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001358 PHI->addIncoming(result, notNullBB);
1359 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1360 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001361
John McCallc2f3e7f2011-03-07 03:12:35 +00001362 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001363 }
John McCall1e7fe752010-09-02 09:58:18 +00001364
John McCallc2f3e7f2011-03-07 03:12:35 +00001365 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001366}
1367
Eli Friedman5fe05982009-11-18 00:50:08 +00001368void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1369 llvm::Value *Ptr,
1370 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001371 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1372
Eli Friedman5fe05982009-11-18 00:50:08 +00001373 const FunctionProtoType *DeleteFTy =
1374 DeleteFD->getType()->getAs<FunctionProtoType>();
1375
1376 CallArgList DeleteArgs;
1377
Anders Carlsson871d0782009-12-13 20:04:38 +00001378 // Check if we need to pass the size to the delete operator.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001379 llvm::Value *Size = nullptr;
Anders Carlsson871d0782009-12-13 20:04:38 +00001380 QualType SizeTy;
Stephen Hines651f13c2014-04-23 16:59:28 -07001381 if (DeleteFTy->getNumParams() == 2) {
1382 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001383 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1384 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1385 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001386 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001387
1388 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedman5fe05982009-11-18 00:50:08 +00001389 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001390 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001391
Anders Carlsson871d0782009-12-13 20:04:38 +00001392 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001393 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001394
1395 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001396 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedman5fe05982009-11-18 00:50:08 +00001397}
1398
John McCall1e7fe752010-09-02 09:58:18 +00001399namespace {
1400 /// Calls the given 'operator delete' on a single object.
1401 struct CallObjectDelete : EHScopeStack::Cleanup {
1402 llvm::Value *Ptr;
1403 const FunctionDecl *OperatorDelete;
1404 QualType ElementType;
1405
1406 CallObjectDelete(llvm::Value *Ptr,
1407 const FunctionDecl *OperatorDelete,
1408 QualType ElementType)
1409 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1410
Stephen Hines651f13c2014-04-23 16:59:28 -07001411 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001412 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1413 }
1414 };
1415}
1416
Stephen Hines176edba2014-12-01 14:53:08 -08001417void
1418CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1419 llvm::Value *CompletePtr,
1420 QualType ElementType) {
1421 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1422 OperatorDelete, ElementType);
1423}
1424
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001425static void EmitDelete(CodeGenFunction &CGF,
1426 const CXXDeleteExpr *DE,
1427 llvm::Value *Ptr,
1428 QualType ElementType);
1429
1430static void EmitSizedDelete(CodeGenFunction &CGF,
1431 const CXXDeleteExpr *DE,
1432 llvm::Value *Ptr,
1433 QualType ElementType,
1434 FunctionDecl* UnsizedDealloc) {
1435
1436 if (CGF.getLangOpts().DefineSizedDeallocation) {
1437 // The delete operator in use is fixed. So simply emit the delete expr.
1438 EmitDelete(CGF, DE, Ptr, ElementType);
1439 return;
1440 }
1441
1442 assert(UnsizedDealloc && "We must be emiting a 'sized' delete expr");
1443
1444 // Branch off over the value of operator delete:
1445 // Use the sized form if available, and default on the unsized form otherwise.
1446 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("if.then");
1447 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("if.end");
1448 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("if.else");
1449
1450 // Emit the condition.
1451 const FunctionDecl *OpDelFD = DE->getOperatorDelete();
1452 llvm::Value *OpDelAddr = CGF.CGM.GetAddrOfFunction(OpDelFD);
1453 //llvm::Function *OpDel = dyn_cast<llvm::Function>(OpDelAddr);
1454 llvm::Value *SDE = CGF.Builder.CreateIsNotNull(OpDelAddr, "sized.del.exists");
1455 CGF.Builder.CreateCondBr(SDE, ThenBlock, ElseBlock);
1456
1457 // Emit the 'then' code.
1458 CGF.EmitBlock(ThenBlock);
1459 EmitDelete(CGF, DE, Ptr, ElementType);
1460 CGF.EmitBranch(ContBlock);
1461
1462 // Compute the 'unsized' delete expr.
1463 CXXDeleteExpr * E = const_cast<CXXDeleteExpr*>(DE);
1464 CXXDeleteExpr *UnsizedDE =
1465 new (CGF.getContext()) CXXDeleteExpr(CGF.getContext().VoidTy,
1466 E->isGlobalDelete(),
1467 E->isArrayForm(),
1468 E->isArrayFormAsWritten(),
1469 E->doesUsualArrayDeleteWantSize(),
1470 UnsizedDealloc,
1471 E->getArgument(),
1472 E->getLocStart());
1473 // Emit the 'else' code.
1474 {
1475 // There is no need to emit line number for an unconditional branch.
1476 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1477 CGF.EmitBlock(ElseBlock);
1478 }
1479 EmitDelete(CGF, UnsizedDE, Ptr, ElementType);
1480 {
1481 // There is no need to emit line number for an unconditional branch.
1482 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1483 CGF.EmitBranch(ContBlock);
1484 }
1485
1486 // Emit the continuation block for code after the if.
1487 CGF.EmitBlock(ContBlock, true);
1488}
1489
John McCall1e7fe752010-09-02 09:58:18 +00001490/// Emit the code for deleting a single object.
1491static void EmitObjectDelete(CodeGenFunction &CGF,
Stephen Hines176edba2014-12-01 14:53:08 -08001492 const CXXDeleteExpr *DE,
John McCall1e7fe752010-09-02 09:58:18 +00001493 llvm::Value *Ptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001494 QualType ElementType) {
John McCall1e7fe752010-09-02 09:58:18 +00001495 // Find the destructor for the type, if applicable. If the
1496 // destructor is virtual, we'll just emit the vcall and return.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001497 const CXXDestructorDecl *Dtor = nullptr;
John McCall1e7fe752010-09-02 09:58:18 +00001498 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1499 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001500 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001501 Dtor = RD->getDestructor();
1502
1503 if (Dtor->isVirtual()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001504 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1505 Dtor);
John McCall1e7fe752010-09-02 09:58:18 +00001506 return;
1507 }
1508 }
1509 }
1510
1511 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001512 // This doesn't have to a conditional cleanup because we're going
1513 // to pop it off in a second.
Stephen Hines176edba2014-12-01 14:53:08 -08001514 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001515 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1516 Ptr, OperatorDelete, ElementType);
1517
1518 if (Dtor)
1519 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001520 /*ForVirtualBase=*/false,
1521 /*Delegating=*/false,
1522 Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001523 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001524 ElementType->isObjCLifetimeType()) {
1525 switch (ElementType.getObjCLifetime()) {
1526 case Qualifiers::OCL_None:
1527 case Qualifiers::OCL_ExplicitNone:
1528 case Qualifiers::OCL_Autoreleasing:
1529 break;
John McCall1e7fe752010-09-02 09:58:18 +00001530
John McCallf85e1932011-06-15 23:02:42 +00001531 case Qualifiers::OCL_Strong: {
1532 // Load the pointer value.
1533 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1534 ElementType.isVolatileQualified());
1535
John McCall5b07e802013-03-13 03:10:54 +00001536 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001537 break;
1538 }
1539
1540 case Qualifiers::OCL_Weak:
1541 CGF.EmitARCDestroyWeak(Ptr);
1542 break;
1543 }
1544 }
1545
John McCall1e7fe752010-09-02 09:58:18 +00001546 CGF.PopCleanupBlock();
1547}
1548
1549namespace {
1550 /// Calls the given 'operator delete' on an array of objects.
1551 struct CallArrayDelete : EHScopeStack::Cleanup {
1552 llvm::Value *Ptr;
1553 const FunctionDecl *OperatorDelete;
1554 llvm::Value *NumElements;
1555 QualType ElementType;
1556 CharUnits CookieSize;
1557
1558 CallArrayDelete(llvm::Value *Ptr,
1559 const FunctionDecl *OperatorDelete,
1560 llvm::Value *NumElements,
1561 QualType ElementType,
1562 CharUnits CookieSize)
1563 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1564 ElementType(ElementType), CookieSize(CookieSize) {}
1565
Stephen Hines651f13c2014-04-23 16:59:28 -07001566 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001567 const FunctionProtoType *DeleteFTy =
1568 OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001569 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall1e7fe752010-09-02 09:58:18 +00001570
1571 CallArgList Args;
1572
1573 // Pass the pointer as the first argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001574 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall1e7fe752010-09-02 09:58:18 +00001575 llvm::Value *DeletePtr
1576 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001577 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001578
1579 // Pass the original requested size as the second argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001580 if (DeleteFTy->getNumParams() == 2) {
1581 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001582 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001583 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1584
1585 CharUnits ElementTypeSize =
1586 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1587
1588 // The size of an element, multiplied by the number of elements.
1589 llvm::Value *Size
1590 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1591 Size = CGF.Builder.CreateMul(Size, NumElements);
1592
1593 // Plus the size of the cookie if applicable.
1594 if (!CookieSize.isZero()) {
1595 llvm::Value *CookieSizeV
1596 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1597 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1598 }
1599
Eli Friedman04c9a492011-05-02 17:57:46 +00001600 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001601 }
1602
1603 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001604 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall1e7fe752010-09-02 09:58:18 +00001605 }
1606 };
1607}
1608
1609/// Emit the code for deleting an array of objects.
1610static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001611 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001612 llvm::Value *deletedPtr,
1613 QualType elementType) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001614 llvm::Value *numElements = nullptr;
1615 llvm::Value *allocatedPtr = nullptr;
John McCall7cfd76c2011-07-13 01:41:37 +00001616 CharUnits cookieSize;
1617 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1618 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001619
John McCall7cfd76c2011-07-13 01:41:37 +00001620 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001621
1622 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001623 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001624 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001625 allocatedPtr, operatorDelete,
1626 numElements, elementType,
1627 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001628
John McCall7cfd76c2011-07-13 01:41:37 +00001629 // Destroy the elements.
1630 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1631 assert(numElements && "no element count for a type with a destructor!");
1632
John McCall7cfd76c2011-07-13 01:41:37 +00001633 llvm::Value *arrayEnd =
1634 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001635
1636 // Note that it is legal to allocate a zero-length array, and we
1637 // can never fold the check away because the length should always
1638 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001639 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1640 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001641 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001642 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001643 }
1644
John McCall7cfd76c2011-07-13 01:41:37 +00001645 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001646 CGF.PopCleanupBlock();
1647}
1648
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001649static void EmitDelete(CodeGenFunction &CGF,
1650 const CXXDeleteExpr *DE,
1651 llvm::Value *Ptr,
1652 QualType ElementType) {
1653 if (DE->isArrayForm()) {
1654 EmitArrayDelete(CGF, DE, Ptr, ElementType);
1655 } else {
1656 EmitObjectDelete(CGF, DE, Ptr, ElementType);
1657 }
1658}
1659
Anders Carlsson16d81b82009-09-22 22:53:17 +00001660void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001661 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001662 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001663
1664 // Null check the pointer.
1665 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1666 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1667
Anders Carlssonb9241242011-04-11 00:30:07 +00001668 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001669
1670 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1671 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001672
John McCall1e7fe752010-09-02 09:58:18 +00001673 // We might be deleting a pointer to array. If so, GEP down to the
1674 // first non-array element.
1675 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1676 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1677 if (DeleteTy->isConstantArrayType()) {
1678 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001679 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001680
1681 GEP.push_back(Zero); // point at the outermost array
1682
1683 // For each layer of array type we're pointing at:
1684 while (const ConstantArrayType *Arr
1685 = getContext().getAsConstantArrayType(DeleteTy)) {
1686 // 1. Unpeel the array type.
1687 DeleteTy = Arr->getElementType();
1688
1689 // 2. GEP to the first element of the array.
1690 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001691 }
John McCall1e7fe752010-09-02 09:58:18 +00001692
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001693 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001694 }
1695
Douglas Gregoreede61a2010-09-02 17:38:50 +00001696 assert(ConvertTypeForMem(DeleteTy) ==
1697 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001698
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001699 const FunctionDecl *Dealloc = E->getOperatorDelete();
1700 if (FunctionDecl* UnsizedDealloc =
1701 Dealloc->getCorrespondingUnsizedGlobalDeallocationFunction())
1702 EmitSizedDelete(*this, E, Ptr, DeleteTy, UnsizedDealloc);
1703 else
1704 EmitDelete(*this, E, Ptr, DeleteTy);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001705
Anders Carlsson16d81b82009-09-22 22:53:17 +00001706 EmitBlock(DeleteEnd);
1707}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001708
Stephen Hines176edba2014-12-01 14:53:08 -08001709static bool isGLValueFromPointerDeref(const Expr *E) {
1710 E = E->IgnoreParens();
1711
1712 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1713 if (!CE->getSubExpr()->isGLValue())
1714 return false;
1715 return isGLValueFromPointerDeref(CE->getSubExpr());
1716 }
1717
1718 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1719 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1720
1721 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1722 if (BO->getOpcode() == BO_Comma)
1723 return isGLValueFromPointerDeref(BO->getRHS());
1724
1725 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1726 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1727 isGLValueFromPointerDeref(ACO->getFalseExpr());
1728
1729 // C++11 [expr.sub]p1:
1730 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1731 if (isa<ArraySubscriptExpr>(E))
1732 return true;
1733
1734 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1735 if (UO->getOpcode() == UO_Deref)
1736 return true;
1737
1738 return false;
1739}
1740
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001741static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001742 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001743 // Get the vtable pointer.
1744 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1745
1746 // C++ [expr.typeid]p2:
1747 // If the glvalue expression is obtained by applying the unary * operator to
1748 // a pointer and the pointer is a null pointer value, the typeid expression
1749 // throws the std::bad_typeid exception.
Stephen Hines176edba2014-12-01 14:53:08 -08001750 //
1751 // However, this paragraph's intent is not clear. We choose a very generous
1752 // interpretation which implores us to consider comma operators, conditional
1753 // operators, parentheses and other such constructs.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001754 QualType SrcRecordTy = E->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08001755 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1756 isGLValueFromPointerDeref(E), SrcRecordTy)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001757 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001758 CGF.createBasicBlock("typeid.bad_typeid");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001759 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001760
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001761 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1762 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001763
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001764 CGF.EmitBlock(BadTypeidBlock);
1765 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1766 CGF.EmitBlock(EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001767 }
1768
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001769 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1770 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001771}
1772
John McCall3ad32c82011-01-28 08:37:24 +00001773llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001774 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001775 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001776
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001777 if (E->isTypeOperand()) {
David Majnemerfe16aa32013-09-27 07:04:31 +00001778 llvm::Constant *TypeInfo =
1779 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001780 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001781 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001782
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001783 // C++ [expr.typeid]p2:
1784 // When typeid is applied to a glvalue expression whose type is a
1785 // polymorphic class type, the result refers to a std::type_info object
1786 // representing the type of the most derived object (that is, the dynamic
1787 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001788 if (E->isPotentiallyEvaluated())
1789 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1790 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001791
1792 QualType OperandTy = E->getExprOperand()->getType();
1793 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1794 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001795}
Mike Stumpc849c052009-11-16 06:50:58 +00001796
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001797static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1798 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001799 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001800 if (DestTy->isPointerType())
1801 return llvm::Constant::getNullValue(DestLTy);
1802
1803 /// C++ [expr.dynamic.cast]p9:
1804 /// A failed cast to reference type throws std::bad_cast
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001805 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1806 return nullptr;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001807
1808 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1809 return llvm::UndefValue::get(DestLTy);
1810}
1811
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001812llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001813 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001814 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001815
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001816 if (DCE->isAlwaysNull())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001817 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1818 return T;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001819
1820 QualType SrcTy = DCE->getSubExpr()->getType();
1821
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001822 // C++ [expr.dynamic.cast]p7:
1823 // If T is "pointer to cv void," then the result is a pointer to the most
1824 // derived object pointed to by v.
1825 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1826
1827 bool isDynamicCastToVoid;
1828 QualType SrcRecordTy;
1829 QualType DestRecordTy;
1830 if (DestPTy) {
1831 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1832 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1833 DestRecordTy = DestPTy->getPointeeType();
1834 } else {
1835 isDynamicCastToVoid = false;
1836 SrcRecordTy = SrcTy;
1837 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1838 }
1839
1840 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1841
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001842 // C++ [expr.dynamic.cast]p4:
1843 // If the value of v is a null pointer value in the pointer case, the result
1844 // is the null pointer value of type T.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001845 bool ShouldNullCheckSrcValue =
1846 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1847 SrcRecordTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001848
1849 llvm::BasicBlock *CastNull = nullptr;
1850 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001851 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001852
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001853 if (ShouldNullCheckSrcValue) {
1854 CastNull = createBasicBlock("dynamic_cast.null");
1855 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1856
1857 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1858 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1859 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001860 }
1861
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001862 if (isDynamicCastToVoid) {
1863 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1864 DestTy);
1865 } else {
1866 assert(DestRecordTy->isRecordType() &&
1867 "destination type must be a record type!");
1868 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1869 DestTy, DestRecordTy, CastEnd);
1870 }
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001871
1872 if (ShouldNullCheckSrcValue) {
1873 EmitBranch(CastEnd);
1874
1875 EmitBlock(CastNull);
1876 EmitBranch(CastEnd);
1877 }
1878
1879 EmitBlock(CastEnd);
1880
1881 if (ShouldNullCheckSrcValue) {
1882 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1883 PHI->addIncoming(Value, CastNotNull);
1884 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1885
1886 Value = PHI;
1887 }
1888
1889 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001890}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001891
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001892void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001893 RunCleanupsScope Scope(*this);
Stephen Hines176edba2014-12-01 14:53:08 -08001894 LValue SlotLV =
1895 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001896
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001897 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1898 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1899 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001900 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001901 // Emit initialization
David Blaikie581deb32012-06-06 20:45:41 +00001902 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Stephen Hines176edba2014-12-01 14:53:08 -08001903 if (CurField->hasCapturedVLAType()) {
1904 auto VAT = CurField->getCapturedVLAType();
1905 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1906 } else {
1907 ArrayRef<VarDecl *> ArrayIndexes;
1908 if (CurField->getType()->isArrayType())
1909 ArrayIndexes = E->getCaptureInitIndexVars(i);
1910 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1911 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001912 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001913}