blob: f7bf40660c851413294e2e27ab21722f5d2bf4b4 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
David Majnemer0c0b6d92014-10-31 20:09:12 +000027static 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) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000031 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson27da15b2010-01-01 20:29:01 +000035
Richard Smith69d0d262012-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.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
David Majnemer0c0b6d92014-10-31 20:09:12 +000042 CGF.EmitTypeCheck(
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000046
47 // Push the this ptr.
David Majnemer0c0b6d92014-10-31 20:09:12 +000048 Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000049
Timur Iskhodzhanovee6bc532013-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 Carlssone36a6b32010-01-02 01:01:18 +000053 }
John McCalla729c622012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000057
John McCalla729c622012-02-17 03:33:10 +000058 // And the rest of the call args.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000059 if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000060 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000061 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Majnemer0c0b6d92014-10-31 20:09:12 +000062 CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
63 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000064 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000065 assert(
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000068 }
David Majnemer0c0b6d92014-10-31 20:09:12 +000069 return required;
70}
Anders Carlsson27da15b2010-01-01 20:29:01 +000071
David Majnemer0c0b6d92014-10-31 20:09:12 +000072RValue 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 McCall8dda7b22012-07-07 06:41:13 +000081 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000082 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000083}
84
David Majnemer0c0b6d92014-10-31 20:09:12 +000085RValue 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 Espindola3b33c4e2012-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 Pichet64225792011-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 Carlsson27da15b2010-01-01 20:29:01 +0000106RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000108 const Expr *callee = CE->getCallee()->IgnoreParens();
109
110 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000112
113 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-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);
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
120 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000121 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000122
Nico Weberaad4af62014-12-03 01:21:41 +0000123 bool HasQualifier = ME->hasQualifier();
124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000126 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000127
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 Espindolaecbe2e92012-06-28 01:56:38 +0000140
Craig Topper8a13c412014-05-21 05:09:00 +0000141 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-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();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000148 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 Espindola3b33c4e2012-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.
Craig Topper8a13c412014-05-21 05:09:00 +0000165 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000166 }
167 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000168
Anders Carlsson27da15b2010-01-01 20:29:01 +0000169 llvm::Value *This;
Nico Weberaad4af62014-12-03 01:21:41 +0000170 if (IsArrow)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000171 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000172 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000173 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000174
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175
John McCall0d635f52010-09-03 01:26:39 +0000176 if (MD->isTrivial()) {
Craig Topper8a13c412014-05-21 05:09:00 +0000177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000178 if (isa<CXXConstructorDecl>(MD) &&
179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000180 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000181
Nico Weberaad4af62014-12-03 01:21:41 +0000182 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 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000193
Nico Weberaad4af62014-12-03 01:21:41 +0000194 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 Pichet64225792011-01-18 05:04:39 +0000203 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000204 }
205
John McCall0d635f52010-09-03 01:26:39 +0000206 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000207 const CXXMethodDecl *CalleeDecl =
208 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000209 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000210 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000211 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
212 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000213 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000214 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
215 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000216 else
Eli Friedmanade60972012-10-25 00:12:49 +0000217 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000218
Reid Klecknere7de47e2013-07-22 13:51:44 +0000219 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000220
Anders Carlsson27da15b2010-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 Espindola3b33c4e2012-06-28 14:28:57 +0000227 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000228 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000229
John McCall0d635f52010-09-03 01:26:39 +0000230 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-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 McCall0d635f52010-09-03 01:26:39 +0000234 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000235 CGM.getCXXABI().EmitVirtualDestructorCall(
236 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000237 } else {
Nico Weberaad4af62014-12-03 01:21:41 +0000238 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
239 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000240 else if (!DevirtualizedMethod)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000241 Callee =
242 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000243 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000244 const CXXDestructorDecl *DDtor =
245 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000246 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
247 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000248 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
249 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000250 }
Craig Topper8a13c412014-05-21 05:09:00 +0000251 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000252 }
253
254 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000255 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000256 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000257 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000258 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000259 if (SanOpts.has(SanitizerKind::CFINVCall) &&
260 MD->getParent()->isDynamicClass()) {
261 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy);
262 EmitVTablePtrCheckForCall(MD, VTable);
263 }
264
Nico Weberaad4af62014-12-03 01:21:41 +0000265 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
266 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000267 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000268 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000269 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000270 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000271 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000272 }
273
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000274 if (MD->isVirtual()) {
275 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
276 *this, MD, This, UseVirtualCall);
277 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000278
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000279 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
280 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000281}
282
283RValue
284CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
285 ReturnValueSlot ReturnValue) {
286 const BinaryOperator *BO =
287 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
288 const Expr *BaseExpr = BO->getLHS();
289 const Expr *MemFnExpr = BO->getRHS();
290
291 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000292 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000293
Anders Carlsson27da15b2010-01-01 20:29:01 +0000294 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000295 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
298
Anders Carlsson27da15b2010-01-01 20:29:01 +0000299 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000301
302 // Emit the 'this' pointer.
303 llvm::Value *This;
304
John McCalle3027922010-08-25 11:45:40 +0000305 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000306 This = EmitScalarExpr(BaseExpr);
307 else
308 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000309
Richard Smithe30752c2012-10-09 19:52:38 +0000310 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
311 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000312
John McCall475999d2010-08-22 00:05:51 +0000313 // Ask the ABI to load the callee. Note that This is modified.
314 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000315 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000316
Anders Carlsson27da15b2010-01-01 20:29:01 +0000317 CallArgList Args;
318
319 QualType ThisType =
320 getContext().getPointerType(getContext().getTagDeclType(RD));
321
322 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000323 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000324
325 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000326
327 // And the rest of the call args
Alexey Samsonov8e1162c2014-09-08 17:22:45 +0000328 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000329 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
330 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000331}
332
333RValue
334CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
335 const CXXMethodDecl *MD,
336 ReturnValueSlot ReturnValue) {
337 assert(MD->isInstance() &&
338 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000339 return EmitCXXMemberOrOperatorMemberCallExpr(
340 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
341 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000342}
343
Peter Collingbournefe883422011-10-06 18:29:37 +0000344RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
345 ReturnValueSlot ReturnValue) {
346 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
347}
348
Eli Friedmanfde961d2011-10-14 02:27:24 +0000349static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
350 llvm::Value *DestPtr,
351 const CXXRecordDecl *Base) {
352 if (Base->isEmpty())
353 return;
354
355 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
356
357 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
358 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000359 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000360
361 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
362
363 // If the type contains a pointer to data member we can't memset it to zero.
364 // Instead, create a null constant and copy it to the destination.
365 // TODO: there are other patterns besides zero that we can usefully memset,
366 // like -1, which happens to be the pattern used by member-pointers.
367 // TODO: isZeroInitializable can be over-conservative in the case where a
368 // virtual base contains a member pointer.
369 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
370 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
371
372 llvm::GlobalVariable *NullVariable =
373 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
374 /*isConstant=*/true,
375 llvm::GlobalVariable::PrivateLinkage,
376 NullConstant, Twine());
377 NullVariable->setAlignment(Align.getQuantity());
378 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
379
380 // Get and call the appropriate llvm.memcpy overload.
381 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
382 return;
383 }
384
385 // Otherwise, just memset the whole thing to zero. This is legal
386 // because in LLVM, all default initializers (other than the ones we just
387 // handled above) are guaranteed to have a bit pattern of all zeros.
388 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
389 Align.getQuantity());
390}
391
Anders Carlsson27da15b2010-01-01 20:29:01 +0000392void
John McCall7a626f62010-09-15 10:14:12 +0000393CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
394 AggValueSlot Dest) {
395 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000396 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000397
398 // If we require zero initialization before (or instead of) calling the
399 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000400 // constructor, emit the zero initialization now, unless destination is
401 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000402 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
403 switch (E->getConstructionKind()) {
404 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000405 case CXXConstructExpr::CK_Complete:
406 EmitNullInitialization(Dest.getAddr(), E->getType());
407 break;
408 case CXXConstructExpr::CK_VirtualBase:
409 case CXXConstructExpr::CK_NonVirtualBase:
410 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
411 break;
412 }
413 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000414
415 // If this is a call to a trivial default constructor, do nothing.
416 if (CD->isTrivial() && CD->isDefaultConstructor())
417 return;
418
John McCall8ea46b62010-09-18 00:58:34 +0000419 // Elide the constructor if we're constructing from a temporary.
420 // The temporary check is required because Sema sets this on NRVO
421 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000422 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000423 assert(getContext().hasSameUnqualifiedType(E->getType(),
424 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000425 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
426 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000427 return;
428 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000429 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000430
John McCallf677a8e2011-07-13 06:10:41 +0000431 if (const ConstantArrayType *arrayType
432 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000433 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000434 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000435 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000436 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000437 bool Delegating = false;
438
Alexis Hunt271c3682011-05-03 20:19:28 +0000439 switch (E->getConstructionKind()) {
440 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000441 // We should be emitting a constructor; GlobalDecl will assert this
442 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000443 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000444 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000445
Alexis Hunt271c3682011-05-03 20:19:28 +0000446 case CXXConstructExpr::CK_Complete:
447 Type = Ctor_Complete;
448 break;
449
450 case CXXConstructExpr::CK_VirtualBase:
451 ForVirtualBase = true;
452 // fall-through
453
454 case CXXConstructExpr::CK_NonVirtualBase:
455 Type = Ctor_Base;
456 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000457
Anders Carlsson27da15b2010-01-01 20:29:01 +0000458 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000459 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000460 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000461 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000462}
463
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000464void
465CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
466 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000467 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000468 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000469 Exp = E->getSubExpr();
470 assert(isa<CXXConstructExpr>(Exp) &&
471 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
472 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
473 const CXXConstructorDecl *CD = E->getConstructor();
474 RunCleanupsScope Scope(*this);
475
476 // If we require zero initialization before (or instead of) calling the
477 // constructor, as can be the case with a non-user-provided default
478 // constructor, emit the zero initialization now.
479 // FIXME. Do I still need this for a copy ctor synthesis?
480 if (E->requiresZeroInitialization())
481 EmitNullInitialization(Dest, E->getType());
482
Chandler Carruth99da11c2010-11-15 13:54:43 +0000483 assert(!getContext().getAsConstantArrayType(E->getType())
484 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000485 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000486}
487
John McCall8ed55a52010-09-02 09:58:18 +0000488static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
489 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000490 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000491 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000492
John McCall7ec4b432011-05-16 01:05:12 +0000493 // No cookie is required if the operator new[] being used is the
494 // reserved placement operator new[].
495 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000496 return CharUnits::Zero();
497
John McCall284c48f2011-01-27 09:37:56 +0000498 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000499}
500
John McCall036f2f62011-05-15 07:14:44 +0000501static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
502 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000503 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000504 llvm::Value *&numElements,
505 llvm::Value *&sizeWithoutCookie) {
506 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000507
John McCall036f2f62011-05-15 07:14:44 +0000508 if (!e->isArray()) {
509 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
510 sizeWithoutCookie
511 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
512 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000513 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000514
John McCall036f2f62011-05-15 07:14:44 +0000515 // The width of size_t.
516 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
517
John McCall8ed55a52010-09-02 09:58:18 +0000518 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000519 llvm::APInt cookieSize(sizeWidth,
520 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000521
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000522 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000523 // We multiply the size of all dimensions for NumElements.
524 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000525 numElements = CGF.EmitScalarExpr(e->getArraySize());
526 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000527
John McCall036f2f62011-05-15 07:14:44 +0000528 // The number of elements can be have an arbitrary integer type;
529 // essentially, we need to multiply it by a constant factor, add a
530 // cookie size, and verify that the result is representable as a
531 // size_t. That's just a gloss, though, and it's wrong in one
532 // important way: if the count is negative, it's an error even if
533 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000534 bool isSigned
535 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000536 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000537 = cast<llvm::IntegerType>(numElements->getType());
538 unsigned numElementsWidth = numElementsType->getBitWidth();
539
540 // Compute the constant factor.
541 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000542 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000543 = CGF.getContext().getAsConstantArrayType(type)) {
544 type = CAT->getElementType();
545 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000546 }
547
John McCall036f2f62011-05-15 07:14:44 +0000548 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
549 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
550 typeSizeMultiplier *= arraySizeMultiplier;
551
552 // This will be a size_t.
553 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000554
Chris Lattner32ac5832010-07-20 21:55:52 +0000555 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
556 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000557 if (llvm::ConstantInt *numElementsC =
558 dyn_cast<llvm::ConstantInt>(numElements)) {
559 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000560
John McCall036f2f62011-05-15 07:14:44 +0000561 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000562
John McCall036f2f62011-05-15 07:14:44 +0000563 // If 'count' was a negative number, it's an overflow.
564 if (isSigned && count.isNegative())
565 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000566
John McCall036f2f62011-05-15 07:14:44 +0000567 // We want to do all this arithmetic in size_t. If numElements is
568 // wider than that, check whether it's already too big, and if so,
569 // overflow.
570 else if (numElementsWidth > sizeWidth &&
571 numElementsWidth - sizeWidth > count.countLeadingZeros())
572 hasAnyOverflow = true;
573
574 // Okay, compute a count at the right width.
575 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
576
Sebastian Redlf862eb62012-02-22 17:37:52 +0000577 // If there is a brace-initializer, we cannot allocate fewer elements than
578 // there are initializers. If we do, that's treated like an overflow.
579 if (adjustedCount.ult(minElements))
580 hasAnyOverflow = true;
581
John McCall036f2f62011-05-15 07:14:44 +0000582 // Scale numElements by that. This might overflow, but we don't
583 // care because it only overflows if allocationSize does, too, and
584 // if that overflows then we shouldn't use this.
585 numElements = llvm::ConstantInt::get(CGF.SizeTy,
586 adjustedCount * arraySizeMultiplier);
587
588 // Compute the size before cookie, and track whether it overflowed.
589 bool overflow;
590 llvm::APInt allocationSize
591 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
592 hasAnyOverflow |= overflow;
593
594 // Add in the cookie, and check whether it's overflowed.
595 if (cookieSize != 0) {
596 // Save the current size without a cookie. This shouldn't be
597 // used if there was overflow.
598 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
599
600 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
601 hasAnyOverflow |= overflow;
602 }
603
604 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000605 if (hasAnyOverflow) {
606 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
607 } else {
John McCall036f2f62011-05-15 07:14:44 +0000608 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000609 }
John McCall036f2f62011-05-15 07:14:44 +0000610
611 // Otherwise, we might need to use the overflow intrinsics.
612 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000613 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000614 // 1) if isSigned, we need to check whether numElements is negative;
615 // 2) if numElementsWidth > sizeWidth, we need to check whether
616 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000617 // 3) if minElements > 0, we need to check whether numElements is smaller
618 // than that.
619 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000620 // sizeWithoutCookie := numElements * typeSizeMultiplier
621 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000622 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000623 // size := sizeWithoutCookie + cookieSize
624 // and check whether it overflows.
625
Craig Topper8a13c412014-05-21 05:09:00 +0000626 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000627
628 // If numElementsWidth > sizeWidth, then one way or another, we're
629 // going to have to do a comparison for (2), and this happens to
630 // take care of (1), too.
631 if (numElementsWidth > sizeWidth) {
632 llvm::APInt threshold(numElementsWidth, 1);
633 threshold <<= sizeWidth;
634
635 llvm::Value *thresholdV
636 = llvm::ConstantInt::get(numElementsType, threshold);
637
638 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
639 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
640
641 // Otherwise, if we're signed, we want to sext up to size_t.
642 } else if (isSigned) {
643 if (numElementsWidth < sizeWidth)
644 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
645
646 // If there's a non-1 type size multiplier, then we can do the
647 // signedness check at the same time as we do the multiply
648 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000649 // unsigned overflow. Otherwise, we have to do it here. But at least
650 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000651 if (typeSizeMultiplier == 1)
652 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000653 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000654
655 // Otherwise, zext up to size_t if necessary.
656 } else if (numElementsWidth < sizeWidth) {
657 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
658 }
659
660 assert(numElements->getType() == CGF.SizeTy);
661
Sebastian Redlf862eb62012-02-22 17:37:52 +0000662 if (minElements) {
663 // Don't allow allocation of fewer elements than we have initializers.
664 if (!hasOverflow) {
665 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
666 llvm::ConstantInt::get(CGF.SizeTy, minElements));
667 } else if (numElementsWidth > sizeWidth) {
668 // The other existing overflow subsumes this check.
669 // We do an unsigned comparison, since any signed value < -1 is
670 // taken care of either above or below.
671 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
672 CGF.Builder.CreateICmpULT(numElements,
673 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
674 }
675 }
676
John McCall036f2f62011-05-15 07:14:44 +0000677 size = numElements;
678
679 // Multiply by the type size if necessary. This multiplier
680 // includes all the factors for nested arrays.
681 //
682 // This step also causes numElements to be scaled up by the
683 // nested-array factor if necessary. Overflow on this computation
684 // can be ignored because the result shouldn't be used if
685 // allocation fails.
686 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000687 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000688 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000689
690 llvm::Value *tsmV =
691 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
692 llvm::Value *result =
693 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
694
695 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
696 if (hasOverflow)
697 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
698 else
699 hasOverflow = overflowed;
700
701 size = CGF.Builder.CreateExtractValue(result, 0);
702
703 // Also scale up numElements by the array size multiplier.
704 if (arraySizeMultiplier != 1) {
705 // If the base element type size is 1, then we can re-use the
706 // multiply we just did.
707 if (typeSize.isOne()) {
708 assert(arraySizeMultiplier == typeSizeMultiplier);
709 numElements = size;
710
711 // Otherwise we need a separate multiply.
712 } else {
713 llvm::Value *asmV =
714 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
715 numElements = CGF.Builder.CreateMul(numElements, asmV);
716 }
717 }
718 } else {
719 // numElements doesn't need to be scaled.
720 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000721 }
722
John McCall036f2f62011-05-15 07:14:44 +0000723 // Add in the cookie size if necessary.
724 if (cookieSize != 0) {
725 sizeWithoutCookie = size;
726
John McCall036f2f62011-05-15 07:14:44 +0000727 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000728 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000729
730 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
731 llvm::Value *result =
732 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
733
734 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
735 if (hasOverflow)
736 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
737 else
738 hasOverflow = overflowed;
739
740 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000741 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000742
John McCall036f2f62011-05-15 07:14:44 +0000743 // If we had any possibility of dynamic overflow, make a select to
744 // overwrite 'size' with an all-ones value, which should cause
745 // operator new to throw.
746 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000747 size = CGF.Builder.CreateSelect(hasOverflow,
748 llvm::Constant::getAllOnesValue(CGF.SizeTy),
749 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000750 }
John McCall8ed55a52010-09-02 09:58:18 +0000751
John McCall036f2f62011-05-15 07:14:44 +0000752 if (cookieSize == 0)
753 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000754 else
John McCall036f2f62011-05-15 07:14:44 +0000755 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000756
John McCall036f2f62011-05-15 07:14:44 +0000757 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000758}
759
Sebastian Redlf862eb62012-02-22 17:37:52 +0000760static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
David Blaikie66e41972015-01-14 07:38:27 +0000761 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000762 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000763 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000764 switch (CGF.getEvaluationKind(AllocType)) {
765 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000766 CGF.EmitScalarInit(Init, nullptr,
David Blaikie66e41972015-01-14 07:38:27 +0000767 CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
John McCall47fb9502013-03-07 21:37:08 +0000768 return;
769 case TEK_Complex:
770 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
771 Alignment),
772 /*isInit*/ true);
773 return;
774 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000775 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000776 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000777 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000778 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000779 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000780 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000781 return;
John McCall7a626f62010-09-15 10:14:12 +0000782 }
John McCall47fb9502013-03-07 21:37:08 +0000783 }
784 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000785}
786
787void
Richard Smith06a67e22014-06-03 06:58:52 +0000788CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
789 QualType ElementType,
790 llvm::Value *BeginPtr,
791 llvm::Value *NumElements,
792 llvm::Value *AllocSizeWithoutCookie) {
793 // If we have a type with trivial initialization and no initializer,
794 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000795 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000796 return;
John McCall99210dc2011-09-15 06:49:18 +0000797
Richard Smith06a67e22014-06-03 06:58:52 +0000798 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000799
Richard Smith06a67e22014-06-03 06:58:52 +0000800 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000801
802 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000803 llvm::AllocaInst *EndOfInit = nullptr;
804 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
805 EHScopeStack::stable_iterator Cleanup;
806 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000807
Sebastian Redlf862eb62012-02-22 17:37:52 +0000808 // If the initializer is an initializer list, first do the explicit elements.
809 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000810 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000811
Richard Smith1c96bc52013-12-11 01:40:16 +0000812 // If this is a multi-dimensional array new, we will initialize multiple
813 // elements with each init list element.
814 QualType AllocType = E->getAllocatedType();
815 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
816 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000817 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000818 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000819 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
820 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000821 }
822
Richard Smith06a67e22014-06-03 06:58:52 +0000823 // Enter a partial-destruction Cleanup if necessary.
824 if (needsEHCleanup(DtorKind)) {
825 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000826 // directly, but the control flow can get so varied here that it
827 // would actually be quite complex. Therefore we go through an
828 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000829 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
830 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
831 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
832 getDestroyer(DtorKind));
833 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000834 }
835
Sebastian Redlf862eb62012-02-22 17:37:52 +0000836 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000837 // Tell the cleanup that it needs to destroy up to this
838 // element. TODO: some of these stores can be trivially
839 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000840 if (EndOfInit)
841 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
842 EndOfInit);
843 // FIXME: If the last initializer is an incomplete initializer list for
844 // an array, and we have an array filler, we can fold together the two
845 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000846 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000847 ILE->getInit(i)->getType(), CurPtr);
848 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000849 }
850
851 // The remaining elements are filled with the array filler expression.
852 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000853
Richard Smith06a67e22014-06-03 06:58:52 +0000854 // Extract the initializer for the individual array elements by pulling
855 // out the array filler from all the nested initializer lists. This avoids
856 // generating a nested loop for the initialization.
857 while (Init && Init->getType()->isConstantArrayType()) {
858 auto *SubILE = dyn_cast<InitListExpr>(Init);
859 if (!SubILE)
860 break;
861 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
862 Init = SubILE->getArrayFiller();
863 }
864
865 // Switch back to initializing one base element at a time.
866 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000867 }
868
Richard Smith06a67e22014-06-03 06:58:52 +0000869 // Attempt to perform zero-initialization using memset.
870 auto TryMemsetInitialization = [&]() -> bool {
871 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
872 // we can initialize with a memset to -1.
873 if (!CGM.getTypes().isZeroInitializable(ElementType))
874 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000875
Richard Smith06a67e22014-06-03 06:58:52 +0000876 // Optimization: since zero initialization will just set the memory
877 // to all zeroes, generate a single memset to do it in one shot.
878
879 // Subtract out the size of any elements we've already initialized.
880 auto *RemainingSize = AllocSizeWithoutCookie;
881 if (InitListElements) {
882 // We know this can't overflow; we check this when doing the allocation.
883 auto *InitializedSize = llvm::ConstantInt::get(
884 RemainingSize->getType(),
885 getContext().getTypeSizeInChars(ElementType).getQuantity() *
886 InitListElements);
887 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
888 }
889
890 // Create the memset.
891 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
892 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
893 Alignment.getQuantity(), false);
894 return true;
895 };
896
Richard Smith454a7cd2014-06-03 08:26:00 +0000897 // If all elements have already been initialized, skip any further
898 // initialization.
899 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
900 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
901 // If there was a Cleanup, deactivate it.
902 if (CleanupDominator)
903 DeactivateCleanupBlock(Cleanup, CleanupDominator);
904 return;
905 }
906
907 assert(Init && "have trailing elements to initialize but no initializer");
908
Richard Smith06a67e22014-06-03 06:58:52 +0000909 // If this is a constructor call, try to optimize it out, and failing that
910 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000911 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000912 CXXConstructorDecl *Ctor = CCE->getConstructor();
913 if (Ctor->isTrivial()) {
914 // If new expression did not specify value-initialization, then there
915 // is no initialization.
916 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
917 return;
918
919 if (TryMemsetInitialization())
920 return;
921 }
922
923 // Store the new Cleanup position for irregular Cleanups.
924 //
925 // FIXME: Share this cleanup with the constructor call emission rather than
926 // having it create a cleanup of its own.
927 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
928
929 // Emit a constructor call loop to initialize the remaining elements.
930 if (InitListElements)
931 NumElements = Builder.CreateSub(
932 NumElements,
933 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000934 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000935 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000936 return;
937 }
938
Richard Smith06a67e22014-06-03 06:58:52 +0000939 // If this is value-initialization, we can usually use memset.
940 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000941 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000942 if (TryMemsetInitialization())
943 return;
944
945 // Switch to an ImplicitValueInitExpr for the element type. This handles
946 // only one case: multidimensional array new of pointers to members. In
947 // all other cases, we already have an initializer for the array element.
948 Init = &IVIE;
949 }
950
951 // At this point we should have found an initializer for the individual
952 // elements of the array.
953 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
954 "got wrong type of element to initialize");
955
Richard Smith454a7cd2014-06-03 08:26:00 +0000956 // If we have an empty initializer list, we can usually use memset.
957 if (auto *ILE = dyn_cast<InitListExpr>(Init))
958 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
959 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000960
961 // Create the loop blocks.
962 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
963 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
964 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
965
966 // Find the end of the array, hoisted out of the loop.
967 llvm::Value *EndPtr =
968 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000969
Sebastian Redlf862eb62012-02-22 17:37:52 +0000970 // If the number of elements isn't constant, we have to now check if there is
971 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000972 if (!ConstNum) {
973 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000974 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000975 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000976 }
977
978 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000979 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000980
981 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000982 llvm::PHINode *CurPtrPhi =
983 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
984 CurPtrPhi->addIncoming(CurPtr, EntryBB);
985 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000986
Richard Smith06a67e22014-06-03 06:58:52 +0000987 // Store the new Cleanup position for irregular Cleanups.
988 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000989
Richard Smith06a67e22014-06-03 06:58:52 +0000990 // Enter a partial-destruction Cleanup if necessary.
991 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
992 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
993 getDestroyer(DtorKind));
994 Cleanup = EHStack.stable_begin();
995 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000996 }
997
998 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000999 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +00001000
Richard Smith06a67e22014-06-03 06:58:52 +00001001 // Leave the Cleanup if we entered one.
1002 if (CleanupDominator) {
1003 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1004 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001005 }
John McCall99210dc2011-09-15 06:49:18 +00001006
Faisal Vali57ae0562013-12-14 00:40:05 +00001007 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001008 llvm::Value *NextPtr =
1009 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
1010
John McCall99210dc2011-09-15 06:49:18 +00001011 // Check whether we've gotten to the end of the array and, if so,
1012 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001013 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1014 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1015 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001016
Richard Smith06a67e22014-06-03 06:58:52 +00001017 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001018}
1019
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001020static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +00001021 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001022 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001023 llvm::Value *NumElements,
1024 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001025 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001026 if (E->isArray())
1027 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
1028 AllocSizeWithoutCookie);
1029 else if (const Expr *Init = E->getInitializer())
David Blaikie66e41972015-01-14 07:38:27 +00001030 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001031}
1032
Richard Smith8d0dc312013-07-21 23:12:18 +00001033/// Emit a call to an operator new or operator delete function, as implicitly
1034/// created by new-expressions and delete-expressions.
1035static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1036 const FunctionDecl *Callee,
1037 const FunctionProtoType *CalleeType,
1038 const CallArgList &Args) {
1039 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001040 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001041 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001042 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1043 Args, CalleeType, /*chainCall=*/false),
1044 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001045
1046 /// C++1y [expr.new]p10:
1047 /// [In a new-expression,] an implementation is allowed to omit a call
1048 /// to a replaceable global allocation function.
1049 ///
1050 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001051 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001052 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001053 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001054 // FIXME: Add addAttribute to CallSite.
1055 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1056 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1057 llvm::Attribute::Builtin);
1058 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1059 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1060 llvm::Attribute::Builtin);
1061 else
1062 llvm_unreachable("unexpected kind of call instruction");
1063 }
1064
1065 return RV;
1066}
1067
Richard Smith760520b2014-06-03 23:27:44 +00001068RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1069 const Expr *Arg,
1070 bool IsDelete) {
1071 CallArgList Args;
1072 const Stmt *ArgS = Arg;
1073 EmitCallArgs(Args, *Type->param_type_begin(),
1074 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1075 // Find the allocation or deallocation function that we're calling.
1076 ASTContext &Ctx = getContext();
1077 DeclarationName Name = Ctx.DeclarationNames
1078 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1079 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001080 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1081 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1082 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001083 llvm_unreachable("predeclared global operator new/delete is missing");
1084}
1085
John McCall824c2f52010-09-14 07:57:04 +00001086namespace {
1087 /// A cleanup to call the given 'operator delete' function upon
1088 /// abnormal exit from a new expression.
1089 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1090 size_t NumPlacementArgs;
1091 const FunctionDecl *OperatorDelete;
1092 llvm::Value *Ptr;
1093 llvm::Value *AllocSize;
1094
1095 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1096
1097 public:
1098 static size_t getExtraSize(size_t NumPlacementArgs) {
1099 return NumPlacementArgs * sizeof(RValue);
1100 }
1101
1102 CallDeleteDuringNew(size_t NumPlacementArgs,
1103 const FunctionDecl *OperatorDelete,
1104 llvm::Value *Ptr,
1105 llvm::Value *AllocSize)
1106 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1107 Ptr(Ptr), AllocSize(AllocSize) {}
1108
1109 void setPlacementArg(unsigned I, RValue Arg) {
1110 assert(I < NumPlacementArgs && "index out of range");
1111 getPlacementArgs()[I] = Arg;
1112 }
1113
Craig Topper4f12f102014-03-12 06:41:41 +00001114 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001115 const FunctionProtoType *FPT
1116 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001117 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1118 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001119
1120 CallArgList DeleteArgs;
1121
1122 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001123 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001124 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001125
1126 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001127 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001128 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001129
1130 // Pass the rest of the arguments, which must match exactly.
1131 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001132 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001133
1134 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001135 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001136 }
1137 };
John McCall7f9c92a2010-09-17 00:50:28 +00001138
1139 /// A cleanup to call the given 'operator delete' function upon
1140 /// abnormal exit from a new expression when the new expression is
1141 /// conditional.
1142 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1143 size_t NumPlacementArgs;
1144 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001145 DominatingValue<RValue>::saved_type Ptr;
1146 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001147
John McCallcb5f77f2011-01-28 10:53:53 +00001148 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1149 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001150 }
1151
1152 public:
1153 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001154 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001155 }
1156
1157 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1158 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001159 DominatingValue<RValue>::saved_type Ptr,
1160 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001161 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1162 Ptr(Ptr), AllocSize(AllocSize) {}
1163
John McCallcb5f77f2011-01-28 10:53:53 +00001164 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001165 assert(I < NumPlacementArgs && "index out of range");
1166 getPlacementArgs()[I] = Arg;
1167 }
1168
Craig Topper4f12f102014-03-12 06:41:41 +00001169 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001170 const FunctionProtoType *FPT
1171 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001172 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1173 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001174
1175 CallArgList DeleteArgs;
1176
1177 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001178 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001179 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001180
1181 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001182 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001183 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001184 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001185 }
1186
1187 // Pass the rest of the arguments, which must match exactly.
1188 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001189 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001190 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001191 }
1192
1193 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001194 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001195 }
1196 };
1197}
1198
1199/// Enter a cleanup to call 'operator delete' if the initializer in a
1200/// new-expression throws.
1201static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1202 const CXXNewExpr *E,
1203 llvm::Value *NewPtr,
1204 llvm::Value *AllocSize,
1205 const CallArgList &NewArgs) {
1206 // If we're not inside a conditional branch, then the cleanup will
1207 // dominate and we can do the easier (and more efficient) thing.
1208 if (!CGF.isInConditionalBranch()) {
1209 CallDeleteDuringNew *Cleanup = CGF.EHStack
1210 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1211 E->getNumPlacementArgs(),
1212 E->getOperatorDelete(),
1213 NewPtr, AllocSize);
1214 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001215 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001216
1217 return;
1218 }
1219
1220 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001221 DominatingValue<RValue>::saved_type SavedNewPtr =
1222 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1223 DominatingValue<RValue>::saved_type SavedAllocSize =
1224 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001225
1226 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001227 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001228 E->getNumPlacementArgs(),
1229 E->getOperatorDelete(),
1230 SavedNewPtr,
1231 SavedAllocSize);
1232 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001233 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001234 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001235
John McCallf4beacd2011-11-10 10:43:54 +00001236 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001237}
1238
Anders Carlssoncc52f652009-09-22 22:53:17 +00001239llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001240 // The element type being allocated.
1241 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001242
John McCall75f94982011-03-07 03:12:35 +00001243 // 1. Build a call to the allocation function.
1244 FunctionDecl *allocator = E->getOperatorNew();
1245 const FunctionProtoType *allocatorType =
1246 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001247
John McCall75f94982011-03-07 03:12:35 +00001248 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001249
1250 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001251 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001252
Sebastian Redlf862eb62012-02-22 17:37:52 +00001253 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1254 unsigned minElements = 0;
1255 if (E->isArray() && E->hasInitializer()) {
1256 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1257 minElements = ILE->getNumInits();
1258 }
1259
Craig Topper8a13c412014-05-21 05:09:00 +00001260 llvm::Value *numElements = nullptr;
1261 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001262 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001263 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1264 allocSizeWithoutCookie);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001265
Eli Friedman43dca6a2011-05-02 17:57:46 +00001266 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001267
Anders Carlssoncc52f652009-09-22 22:53:17 +00001268 // We start at 1 here because the first argument (the allocation size)
1269 // has already been emitted.
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001270 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001271 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1272 /*ParamsToSkip*/ 1);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001273
John McCall7ec4b432011-05-16 01:05:12 +00001274 // Emit the allocation call. If the allocator is a global placement
1275 // operator, just "inline" it directly.
1276 RValue RV;
1277 if (allocator->isReservedGlobalPlacementOperator()) {
1278 assert(allocatorArgs.size() == 2);
1279 RV = allocatorArgs[1].RV;
1280 // TODO: kill any unnecessary computations done for the size
1281 // argument.
1282 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001283 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001284 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001285
John McCall75f94982011-03-07 03:12:35 +00001286 // Emit a null check on the allocation result if the allocation
1287 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001288 // exception spec or is the reserved placement new) and we have an
John McCall75f94982011-03-07 03:12:35 +00001289 // interesting initializer.
Richard Smith902a0232015-02-14 01:52:20 +00001290 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001291 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001292
Craig Topper8a13c412014-05-21 05:09:00 +00001293 llvm::BasicBlock *nullCheckBB = nullptr;
1294 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001295
John McCall75f94982011-03-07 03:12:35 +00001296 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001297 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001298
John McCallf7dcf322011-03-07 01:52:56 +00001299 // The null-check means that the initializer is conditionally
1300 // evaluated.
1301 ConditionalEvaluation conditional(*this);
1302
John McCall75f94982011-03-07 03:12:35 +00001303 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001304 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001305
1306 nullCheckBB = Builder.GetInsertBlock();
1307 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1308 contBB = createBasicBlock("new.cont");
1309
1310 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1311 Builder.CreateCondBr(isNull, contBB, notNullBB);
1312 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001313 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001314
John McCall824c2f52010-09-14 07:57:04 +00001315 // If there's an operator delete, enter a cleanup to call it if an
1316 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001317 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001318 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001319 if (E->getOperatorDelete() &&
1320 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001321 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1322 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001323 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001324 }
1325
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001326 assert((allocSize == allocSizeWithoutCookie) ==
1327 CalculateCookiePadding(*this, E).isZero());
1328 if (allocSize != allocSizeWithoutCookie) {
1329 assert(E->isArray());
1330 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1331 numElements,
1332 E, allocType);
1333 }
1334
Chris Lattner2192fe52011-07-18 04:24:23 +00001335 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001336 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1337 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001338
John McCall99210dc2011-09-15 06:49:18 +00001339 EmitNewInitializer(*this, E, allocType, result, numElements,
1340 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001341 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001342 // NewPtr is a pointer to the base element type. If we're
1343 // allocating an array of arrays, we'll need to cast back to the
1344 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001345 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001346 if (result->getType() != resultType)
1347 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001348 }
John McCall824c2f52010-09-14 07:57:04 +00001349
1350 // Deactivate the 'operator delete' cleanup if we finished
1351 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001352 if (operatorDeleteCleanup.isValid()) {
1353 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1354 cleanupDominator->eraseFromParent();
1355 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001356
John McCall75f94982011-03-07 03:12:35 +00001357 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001358 conditional.end(*this);
1359
John McCall75f94982011-03-07 03:12:35 +00001360 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1361 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001362
Jay Foad20c0f022011-03-30 11:28:58 +00001363 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001364 PHI->addIncoming(result, notNullBB);
1365 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1366 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001367
John McCall75f94982011-03-07 03:12:35 +00001368 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001369 }
John McCall8ed55a52010-09-02 09:58:18 +00001370
John McCall75f94982011-03-07 03:12:35 +00001371 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001372}
1373
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001374void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1375 llvm::Value *Ptr,
1376 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001377 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1378
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001379 const FunctionProtoType *DeleteFTy =
1380 DeleteFD->getType()->getAs<FunctionProtoType>();
1381
1382 CallArgList DeleteArgs;
1383
Anders Carlsson21122cf2009-12-13 20:04:38 +00001384 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001385 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001386 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001387 if (DeleteFTy->getNumParams() == 2) {
1388 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001389 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1390 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1391 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001392 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001393
1394 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001395 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001396 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001397
Anders Carlsson21122cf2009-12-13 20:04:38 +00001398 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001399 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001400
1401 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001402 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001403}
1404
John McCall8ed55a52010-09-02 09:58:18 +00001405namespace {
1406 /// Calls the given 'operator delete' on a single object.
1407 struct CallObjectDelete : EHScopeStack::Cleanup {
1408 llvm::Value *Ptr;
1409 const FunctionDecl *OperatorDelete;
1410 QualType ElementType;
1411
1412 CallObjectDelete(llvm::Value *Ptr,
1413 const FunctionDecl *OperatorDelete,
1414 QualType ElementType)
1415 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1416
Craig Topper4f12f102014-03-12 06:41:41 +00001417 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001418 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1419 }
1420 };
1421}
1422
David Majnemer0c0b6d92014-10-31 20:09:12 +00001423void
1424CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1425 llvm::Value *CompletePtr,
1426 QualType ElementType) {
1427 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1428 OperatorDelete, ElementType);
1429}
1430
John McCall8ed55a52010-09-02 09:58:18 +00001431/// Emit the code for deleting a single object.
1432static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001433 const CXXDeleteExpr *DE,
John McCall8ed55a52010-09-02 09:58:18 +00001434 llvm::Value *Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001435 QualType ElementType) {
John McCall8ed55a52010-09-02 09:58:18 +00001436 // Find the destructor for the type, if applicable. If the
1437 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001438 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001439 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1440 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001441 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001442 Dtor = RD->getDestructor();
1443
1444 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001445 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1446 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001447 return;
1448 }
1449 }
1450 }
1451
1452 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001453 // This doesn't have to a conditional cleanup because we're going
1454 // to pop it off in a second.
David Majnemer08681372014-11-01 07:37:17 +00001455 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001456 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1457 Ptr, OperatorDelete, ElementType);
1458
1459 if (Dtor)
1460 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001461 /*ForVirtualBase=*/false,
1462 /*Delegating=*/false,
1463 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001464 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001465 ElementType->isObjCLifetimeType()) {
1466 switch (ElementType.getObjCLifetime()) {
1467 case Qualifiers::OCL_None:
1468 case Qualifiers::OCL_ExplicitNone:
1469 case Qualifiers::OCL_Autoreleasing:
1470 break;
John McCall8ed55a52010-09-02 09:58:18 +00001471
John McCall31168b02011-06-15 23:02:42 +00001472 case Qualifiers::OCL_Strong: {
1473 // Load the pointer value.
1474 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1475 ElementType.isVolatileQualified());
1476
John McCallcdda29c2013-03-13 03:10:54 +00001477 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001478 break;
1479 }
1480
1481 case Qualifiers::OCL_Weak:
1482 CGF.EmitARCDestroyWeak(Ptr);
1483 break;
1484 }
1485 }
1486
John McCall8ed55a52010-09-02 09:58:18 +00001487 CGF.PopCleanupBlock();
1488}
1489
1490namespace {
1491 /// Calls the given 'operator delete' on an array of objects.
1492 struct CallArrayDelete : EHScopeStack::Cleanup {
1493 llvm::Value *Ptr;
1494 const FunctionDecl *OperatorDelete;
1495 llvm::Value *NumElements;
1496 QualType ElementType;
1497 CharUnits CookieSize;
1498
1499 CallArrayDelete(llvm::Value *Ptr,
1500 const FunctionDecl *OperatorDelete,
1501 llvm::Value *NumElements,
1502 QualType ElementType,
1503 CharUnits CookieSize)
1504 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1505 ElementType(ElementType), CookieSize(CookieSize) {}
1506
Craig Topper4f12f102014-03-12 06:41:41 +00001507 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001508 const FunctionProtoType *DeleteFTy =
1509 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001510 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001511
1512 CallArgList Args;
1513
1514 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001515 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001516 llvm::Value *DeletePtr
1517 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001518 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001519
1520 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001521 if (DeleteFTy->getNumParams() == 2) {
1522 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001523 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001524 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1525
1526 CharUnits ElementTypeSize =
1527 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1528
1529 // The size of an element, multiplied by the number of elements.
1530 llvm::Value *Size
1531 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1532 Size = CGF.Builder.CreateMul(Size, NumElements);
1533
1534 // Plus the size of the cookie if applicable.
1535 if (!CookieSize.isZero()) {
1536 llvm::Value *CookieSizeV
1537 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1538 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1539 }
1540
Eli Friedman43dca6a2011-05-02 17:57:46 +00001541 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001542 }
1543
1544 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001545 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001546 }
1547 };
1548}
1549
1550/// Emit the code for deleting an array of objects.
1551static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001552 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001553 llvm::Value *deletedPtr,
1554 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001555 llvm::Value *numElements = nullptr;
1556 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001557 CharUnits cookieSize;
1558 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1559 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001560
John McCallca2c56f2011-07-13 01:41:37 +00001561 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001562
1563 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001564 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001565 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001566 allocatedPtr, operatorDelete,
1567 numElements, elementType,
1568 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001569
John McCallca2c56f2011-07-13 01:41:37 +00001570 // Destroy the elements.
1571 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1572 assert(numElements && "no element count for a type with a destructor!");
1573
John McCallca2c56f2011-07-13 01:41:37 +00001574 llvm::Value *arrayEnd =
1575 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001576
1577 // Note that it is legal to allocate a zero-length array, and we
1578 // can never fold the check away because the length should always
1579 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001580 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1581 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001582 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001583 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001584 }
1585
John McCallca2c56f2011-07-13 01:41:37 +00001586 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001587 CGF.PopCleanupBlock();
1588}
1589
Anders Carlssoncc52f652009-09-22 22:53:17 +00001590void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001591 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001592 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001593
1594 // Null check the pointer.
1595 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1596 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1597
Anders Carlsson98981b12011-04-11 00:30:07 +00001598 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001599
1600 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1601 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001602
John McCall8ed55a52010-09-02 09:58:18 +00001603 // We might be deleting a pointer to array. If so, GEP down to the
1604 // first non-array element.
1605 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1606 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1607 if (DeleteTy->isConstantArrayType()) {
1608 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001609 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001610
1611 GEP.push_back(Zero); // point at the outermost array
1612
1613 // For each layer of array type we're pointing at:
1614 while (const ConstantArrayType *Arr
1615 = getContext().getAsConstantArrayType(DeleteTy)) {
1616 // 1. Unpeel the array type.
1617 DeleteTy = Arr->getElementType();
1618
1619 // 2. GEP to the first element of the array.
1620 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001621 }
John McCall8ed55a52010-09-02 09:58:18 +00001622
Jay Foad040dd822011-07-22 08:16:57 +00001623 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001624 }
1625
Douglas Gregor04f36212010-09-02 17:38:50 +00001626 assert(ConvertTypeForMem(DeleteTy) ==
1627 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001628
Reid Kleckner7270ef52015-03-19 17:03:58 +00001629 if (E->isArrayForm()) {
1630 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1631 } else {
1632 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1633 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001634
Anders Carlssoncc52f652009-09-22 22:53:17 +00001635 EmitBlock(DeleteEnd);
1636}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001637
David Majnemer1c3d95e2014-07-19 00:17:06 +00001638static bool isGLValueFromPointerDeref(const Expr *E) {
1639 E = E->IgnoreParens();
1640
1641 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1642 if (!CE->getSubExpr()->isGLValue())
1643 return false;
1644 return isGLValueFromPointerDeref(CE->getSubExpr());
1645 }
1646
1647 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1648 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1649
1650 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1651 if (BO->getOpcode() == BO_Comma)
1652 return isGLValueFromPointerDeref(BO->getRHS());
1653
1654 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1655 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1656 isGLValueFromPointerDeref(ACO->getFalseExpr());
1657
1658 // C++11 [expr.sub]p1:
1659 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1660 if (isa<ArraySubscriptExpr>(E))
1661 return true;
1662
1663 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1664 if (UO->getOpcode() == UO_Deref)
1665 return true;
1666
1667 return false;
1668}
1669
Warren Hunt747e3012014-06-18 21:15:55 +00001670static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001671 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001672 // Get the vtable pointer.
1673 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1674
1675 // C++ [expr.typeid]p2:
1676 // If the glvalue expression is obtained by applying the unary * operator to
1677 // a pointer and the pointer is a null pointer value, the typeid expression
1678 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001679 //
1680 // However, this paragraph's intent is not clear. We choose a very generous
1681 // interpretation which implores us to consider comma operators, conditional
1682 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001683 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001684 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1685 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001686 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001687 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001688 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001689
David Majnemer1162d252014-06-22 19:05:33 +00001690 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1691 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001692
David Majnemer1162d252014-06-22 19:05:33 +00001693 CGF.EmitBlock(BadTypeidBlock);
1694 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1695 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001696 }
1697
David Majnemer1162d252014-06-22 19:05:33 +00001698 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1699 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001700}
1701
John McCalle4df6c82011-01-28 08:37:24 +00001702llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001703 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001704 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001705
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001706 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001707 llvm::Constant *TypeInfo =
1708 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001709 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001710 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001711
Anders Carlsson940f02d2011-04-18 00:57:03 +00001712 // C++ [expr.typeid]p2:
1713 // When typeid is applied to a glvalue expression whose type is a
1714 // polymorphic class type, the result refers to a std::type_info object
1715 // representing the type of the most derived object (that is, the dynamic
1716 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001717 if (E->isPotentiallyEvaluated())
1718 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1719 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001720
1721 QualType OperandTy = E->getExprOperand()->getType();
1722 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1723 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001724}
Mike Stump65511702009-11-16 06:50:58 +00001725
Anders Carlssonc1c99712011-04-11 01:45:29 +00001726static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1727 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001728 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001729 if (DestTy->isPointerType())
1730 return llvm::Constant::getNullValue(DestLTy);
1731
1732 /// C++ [expr.dynamic.cast]p9:
1733 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001734 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1735 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001736
1737 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1738 return llvm::UndefValue::get(DestLTy);
1739}
1740
Anders Carlsson882d7902011-04-11 00:46:40 +00001741llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001742 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001743 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001744
Anders Carlssonc1c99712011-04-11 01:45:29 +00001745 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001746 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1747 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001748
1749 QualType SrcTy = DCE->getSubExpr()->getType();
1750
David Majnemer1162d252014-06-22 19:05:33 +00001751 // C++ [expr.dynamic.cast]p7:
1752 // If T is "pointer to cv void," then the result is a pointer to the most
1753 // derived object pointed to by v.
1754 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1755
1756 bool isDynamicCastToVoid;
1757 QualType SrcRecordTy;
1758 QualType DestRecordTy;
1759 if (DestPTy) {
1760 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1761 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1762 DestRecordTy = DestPTy->getPointeeType();
1763 } else {
1764 isDynamicCastToVoid = false;
1765 SrcRecordTy = SrcTy;
1766 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1767 }
1768
1769 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1770
Anders Carlsson882d7902011-04-11 00:46:40 +00001771 // C++ [expr.dynamic.cast]p4:
1772 // If the value of v is a null pointer value in the pointer case, the result
1773 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001774 bool ShouldNullCheckSrcValue =
1775 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1776 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001777
1778 llvm::BasicBlock *CastNull = nullptr;
1779 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001780 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001781
Anders Carlsson882d7902011-04-11 00:46:40 +00001782 if (ShouldNullCheckSrcValue) {
1783 CastNull = createBasicBlock("dynamic_cast.null");
1784 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1785
1786 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1787 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1788 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001789 }
1790
David Majnemer1162d252014-06-22 19:05:33 +00001791 if (isDynamicCastToVoid) {
1792 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1793 DestTy);
1794 } else {
1795 assert(DestRecordTy->isRecordType() &&
1796 "destination type must be a record type!");
1797 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1798 DestTy, DestRecordTy, CastEnd);
1799 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001800
1801 if (ShouldNullCheckSrcValue) {
1802 EmitBranch(CastEnd);
1803
1804 EmitBlock(CastNull);
1805 EmitBranch(CastEnd);
1806 }
1807
1808 EmitBlock(CastEnd);
1809
1810 if (ShouldNullCheckSrcValue) {
1811 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1812 PHI->addIncoming(Value, CastNotNull);
1813 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1814
1815 Value = PHI;
1816 }
1817
1818 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001819}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001820
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001821void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001822 RunCleanupsScope Scope(*this);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001823 LValue SlotLV =
1824 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001825
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001826 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1827 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1828 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001829 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001830 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00001831 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001832 if (CurField->hasCapturedVLAType()) {
1833 auto VAT = CurField->getCapturedVLAType();
1834 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1835 } else {
1836 ArrayRef<VarDecl *> ArrayIndexes;
1837 if (CurField->getType()->isArrayType())
1838 ArrayIndexes = E->getCaptureInitIndexVars(i);
1839 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1840 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001841 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001842}