blob: b3353ba0db8ba93552e36f59eab363b0f032334e [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Lacey8b549992013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070021#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000023
Anders Carlsson16d81b82009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Stephen Hines176edba2014-12-01 14:53:08 -080027static RequiredArgs commonEmitCXXMemberOrOperatorCall(
28 CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
29 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
31 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Stephen Hines176edba2014-12-01 14:53:08 -080034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +000035
Richard Smith2c9f87c2012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Stephen Hines176edba2014-12-01 14:53:08 -080039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
42 CGF.EmitTypeCheck(
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000046
47 // Push the this ptr.
Stephen Hines176edba2014-12-01 14:53:08 -080048 Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000049
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000050 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssonc997d422010-01-02 01:01:18 +000053 }
John McCallde5d3c72012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlsson3b5ad222010-01-01 20:29:01 +000057
Stephen Hines176edba2014-12-01 14:53:08 -080058 // And the rest of the call args.
59 if (CE) {
60 // Special case: skip first argument of CXXOperatorCall (it is "this").
61 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
62 CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
63 CE->getDirectCallee());
64 } else {
65 assert(
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
68 }
69 return required;
70}
71
72RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
73 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
75 const CallExpr *CE) {
76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77 CallArgList Args;
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79 *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
80 Args);
John McCall0f3d0972012-07-07 06:41:13 +000081 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000082 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000083}
84
Stephen Hines176edba2014-12-01 14:53:08 -080085RValue CodeGenFunction::EmitCXXStructorCall(
86 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
87 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
88 const CallExpr *CE, StructorType Type) {
89 CallArgList Args;
90 commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
91 ImplicitParam, ImplicitParamTy, CE, Args);
92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
93 Callee, ReturnValue, Args, MD);
94}
95
Rafael Espindolaea01d762012-06-28 14:28:57 +000096static CXXRecordDecl *getCXXRecord(const Expr *E) {
97 QualType T = E->getType();
98 if (const PointerType *PTy = T->getAs<PointerType>())
99 T = PTy->getPointeeType();
100 const RecordType *Ty = T->castAs<RecordType>();
101 return cast<CXXRecordDecl>(Ty->getDecl());
102}
103
Francois Pichetdbee3412011-01-18 05:04:39 +0000104// Note: This function also emit constructor calls to support a MSVC
105// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000106RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000108 const Expr *callee = CE->getCallee()->IgnoreParens();
109
110 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000112
113 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
115
116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Stephen Hines176edba2014-12-01 14:53:08 -0800119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
120 ReturnValue);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000121 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000122
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700123 bool HasQualifier = ME->hasQualifier();
124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125 bool IsArrow = ME->isArrow();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000126 const Expr *Base = ME->getBase();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700127
128 return EmitCXXMemberOrOperatorMemberCallExpr(
129 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
130}
131
132RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
133 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
134 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
135 const Expr *Base) {
136 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
137
138 // Compute the object pointer.
139 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000140
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700141 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer9581ed02013-08-25 22:46:27 +0000142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000143 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
144 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
145 assert(DevirtualizedMethod);
146 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
147 const Expr *Inner = Base->ignoreParenBaseCasts();
Stephen Hines176edba2014-12-01 14:53:08 -0800148 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
149 MD->getReturnType().getCanonicalType())
150 // If the return types are not the same, this might be a case where more
151 // code needs to run to compensate for it. For example, the derived
152 // method might return a type that inherits form from the return
153 // type of MD and has a prefix.
154 // For now we just avoid devirtualizing these covariant cases.
155 DevirtualizedMethod = nullptr;
156 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindolaea01d762012-06-28 14:28:57 +0000157 // If the class of the Inner expression is where the dynamic method
158 // is defined, build the this pointer from it.
159 Base = Inner;
160 else if (getCXXRecord(Base) != DevirtualizedClass) {
161 // If the method is defined in a class that is not the best dynamic
162 // one or the one of the full expression, we would have to build
163 // a derived-to-base cast to compute the correct this pointer, but
164 // we don't have support for that yet, so do a virtual call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700165 DevirtualizedMethod = nullptr;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000166 }
167 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000168
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000169 llvm::Value *This;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700170 if (IsArrow)
Rafael Espindolaea01d762012-06-28 14:28:57 +0000171 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000172 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000173 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000174
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000175
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700176 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichetdbee3412011-01-18 05:04:39 +0000178 if (isa<CXXConstructorDecl>(MD) &&
179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700180 return RValue::get(nullptr);
John McCallfc400282010-09-03 01:26:39 +0000181
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700182 if (!MD->getParent()->mayInsertExtraPadding()) {
183 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
184 // We don't like to generate the trivial copy/move assignment operator
185 // when it isn't necessary; just produce the proper effect here.
186 // Special case: skip first argument of CXXOperatorCall (it is "this").
187 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
188 llvm::Value *RHS =
189 EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
190 EmitAggregateAssign(This, RHS, CE->getType());
191 return RValue::get(This);
192 }
Stephen Hines176edba2014-12-01 14:53:08 -0800193
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700194 if (isa<CXXConstructorDecl>(MD) &&
195 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
196 // Trivial move and copy ctor are the same.
197 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
198 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
199 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
200 return RValue::get(This);
201 }
202 llvm_unreachable("unknown trivial member function");
Francois Pichetdbee3412011-01-18 05:04:39 +0000203 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000204 }
205
John McCallfc400282010-09-03 01:26:39 +0000206 // Compute the function type we're calling.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700207 const CXXMethodDecl *CalleeDecl =
208 DevirtualizedMethod ? DevirtualizedMethod : MD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700209 const CGFunctionInfo *FInfo = nullptr;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700210 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Stephen Hines176edba2014-12-01 14:53:08 -0800211 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
212 Dtor, StructorType::Complete);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700213 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Stephen Hines176edba2014-12-01 14:53:08 -0800214 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
215 Ctor, StructorType::Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000216 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000217 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000218
Reid Klecknera4130ba2013-07-22 13:51:44 +0000219 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000220
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000221 // C++ [class.virtual]p12:
222 // Explicit qualification with the scope operator (5.1) suppresses the
223 // virtual call mechanism.
224 //
225 // We also don't emit a virtual call if the base expression has a record type
226 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000227 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin3258abc2013-06-19 23:23:19 +0000228 llvm::Value *Callee;
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000229
John McCallfc400282010-09-03 01:26:39 +0000230 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000231 assert(CE->arg_begin() == CE->arg_end() &&
232 "Destructor shouldn't have explicit parameters");
233 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCallfc400282010-09-03 01:26:39 +0000234 if (UseVirtualCall) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700235 CGM.getCXXABI().EmitVirtualDestructorCall(
236 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000237 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700238 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
239 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000240 else if (!DevirtualizedMethod)
Stephen Hines176edba2014-12-01 14:53:08 -0800241 Callee =
242 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000243 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000244 const CXXDestructorDecl *DDtor =
245 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000246 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
247 }
Stephen Hines176edba2014-12-01 14:53:08 -0800248 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
249 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000250 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700251 return RValue::get(nullptr);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000252 }
253
254 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichetdbee3412011-01-18 05:04:39 +0000255 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000256 } else if (UseVirtualCall) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000257 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000258 } else {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700259 if (SanOpts.has(SanitizerKind::CFINVCall) &&
260 MD->getParent()->isDynamicClass()) {
261 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy);
262 EmitVTablePtrCheckForCall(MD, VTable);
263 }
264
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700265 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
266 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000267 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000268 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000269 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000270 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000271 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000272 }
273
Stephen Hines651f13c2014-04-23 16:59:28 -0700274 if (MD->isVirtual()) {
275 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
276 *this, MD, This, UseVirtualCall);
277 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000278
Stephen Hines176edba2014-12-01 14:53:08 -0800279 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
280 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson3b5ad222010-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 McCall864c0412011-04-26 20:42:42 +0000292 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000293
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000294 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000295 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
298
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000299 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000301
302 // Emit the 'this' pointer.
303 llvm::Value *This;
304
John McCall2de56d12010-08-25 11:45:40 +0000305 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000306 This = EmitScalarExpr(BaseExpr);
307 else
308 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309
Richard Smith4def70d2012-10-09 19:52:38 +0000310 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
311 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000312
John McCall93d557b2010-08-22 00:05:51 +0000313 // Ask the ABI to load the callee. Note that This is modified.
314 llvm::Value *Callee =
Stephen Hines651f13c2014-04-23 16:59:28 -0700315 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000316
Anders Carlsson3b5ad222010-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 Friedman04c9a492011-05-02 17:57:46 +0000323 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000324
325 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326
327 // And the rest of the call args
Stephen Hines176edba2014-12-01 14:53:08 -0800328 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5d4a7552013-10-01 21:51:38 +0000329 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
330 Callee, ReturnValue, Args);
Anders Carlsson3b5ad222010-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!");
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700339 return EmitCXXMemberOrOperatorMemberCallExpr(
340 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
341 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000342}
343
Peter Collingbourne6c0aa5f2011-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 Friedman2ed7cb62011-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();
Stephen Hines651f13c2014-04-23 16:59:28 -0700359 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedman2ed7cb62011-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 Carlsson3b5ad222010-01-01 20:29:01 +0000392void
John McCall558d2ab2010-09-15 10:14:12 +0000393CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
394 AggValueSlot Dest) {
395 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000396 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-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 Kyrtzidis657baf12011-04-28 22:57:55 +0000400 // constructor, emit the zero initialization now, unless destination is
401 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000402 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
403 switch (E->getConstructionKind()) {
404 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-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 Gregor759e41b2010-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 McCallfc1e6c72010-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 Smith7edf9e32012-11-01 22:30:59 +0000422 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000423 assert(getContext().hasSameUnqualifiedType(E->getType(),
424 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000425 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
426 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000427 return;
428 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000429 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000430
John McCallc3c07662011-07-13 06:10:41 +0000431 if (const ConstantArrayType *arrayType
432 = getContext().getAsConstantArrayType(E->getType())) {
Stephen Hines176edba2014-12-01 14:53:08 -0800433 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallc3c07662011-07-13 06:10:41 +0000434 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000435 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000436 bool ForVirtualBase = false;
Douglas Gregor378e1e72013-01-31 05:50:40 +0000437 bool Delegating = false;
438
Sean Huntd49bd552011-05-03 20:19:28 +0000439 switch (E->getConstructionKind()) {
440 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000441 // We should be emitting a constructor; GlobalDecl will assert this
442 Type = CurGD.getCtorType();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000443 Delegating = true;
Sean Huntd49bd552011-05-03 20:19:28 +0000444 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000445
Sean Huntd49bd552011-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 Carlsson155ed4a2010-05-02 23:20:53 +0000457
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000458 // Call the constructor.
Douglas Gregor378e1e72013-01-31 05:50:40 +0000459 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Stephen Hines176edba2014-12-01 14:53:08 -0800460 E);
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000461 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000462}
463
Fariborz Jahanian34999872010-11-13 21:53:34 +0000464void
465CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
466 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000467 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000468 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-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 Carruth858a5462010-11-15 13:54:43 +0000483 assert(!getContext().getAsConstantArrayType(E->getType())
484 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Stephen Hines176edba2014-12-01 14:53:08 -0800485 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahanian34999872010-11-13 21:53:34 +0000486}
487
John McCall1e7fe752010-09-02 09:58:18 +0000488static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
489 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000490 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000491 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000492
John McCallb1c98a32011-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 McCall5172ed92010-08-23 01:17:59 +0000496 return CharUnits::Zero();
497
John McCall6ec278d2011-01-27 09:37:56 +0000498 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000499}
500
John McCall7d166272011-05-15 07:14:44 +0000501static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
502 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000503 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000504 llvm::Value *&numElements,
505 llvm::Value *&sizeWithoutCookie) {
506 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000507
John McCall7d166272011-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 Gregor59174c02010-07-21 01:10:17 +0000513 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000514
John McCall7d166272011-05-15 07:14:44 +0000515 // The width of size_t.
516 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
517
John McCall1e7fe752010-09-02 09:58:18 +0000518 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000519 llvm::APInt cookieSize(sizeWidth,
520 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000521
Anders Carlssona4d4c012009-09-23 16:07:23 +0000522 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-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 McCall7d166272011-05-15 07:14:44 +0000525 numElements = CGF.EmitScalarExpr(e->getArraySize());
526 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000527
John McCall7d166272011-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 Gregor575a1c92011-05-20 16:38:50 +0000534 bool isSigned
535 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000536 llvm::IntegerType *numElementsType
John McCall7d166272011-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 Kyrtzidise7ab92e2010-08-26 15:23:38 +0000542 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000543 = CGF.getContext().getAsConstantArrayType(type)) {
544 type = CAT->getElementType();
545 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000546 }
547
John McCall7d166272011-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 Lattner83252dc2010-07-20 21:07:09 +0000554
Chris Lattner806941e2010-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 McCall7d166272011-05-15 07:14:44 +0000557 if (llvm::ConstantInt *numElementsC =
558 dyn_cast<llvm::ConstantInt>(numElements)) {
559 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000560
John McCall7d166272011-05-15 07:14:44 +0000561 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000562
John McCall7d166272011-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 McCall1e7fe752010-09-02 09:58:18 +0000566
John McCall7d166272011-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 Redl92036472012-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 McCall7d166272011-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.
605 if (hasAnyOverflow) {
606 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
607 } else {
608 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
609 }
610
611 // Otherwise, we might need to use the overflow intrinsics.
612 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000613 // There are up to five conditions we need to test for:
John McCall7d166272011-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 Redl92036472012-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 McCall7d166272011-05-15 07:14:44 +0000620 // sizeWithoutCookie := numElements * typeSizeMultiplier
621 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000622 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000623 // size := sizeWithoutCookie + cookieSize
624 // and check whether it overflows.
625
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700626 llvm::Value *hasOverflow = nullptr;
John McCall7d166272011-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 Redl92036472012-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 McCall7d166272011-05-15 07:14:44 +0000651 if (typeSizeMultiplier == 1)
652 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000653 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-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 Redl92036472012-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 McCall7d166272011-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 McCall7d166272011-05-15 07:14:44 +0000687 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000688 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000689
690 llvm::Value *tsmV =
691 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
692 llvm::Value *result =
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700693 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall7d166272011-05-15 07:14:44 +0000694
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 Lattner806941e2010-07-20 21:55:52 +0000721 }
722
John McCall7d166272011-05-15 07:14:44 +0000723 // Add in the cookie size if necessary.
724 if (cookieSize != 0) {
725 sizeWithoutCookie = size;
726
John McCall7d166272011-05-15 07:14:44 +0000727 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000728 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000729
730 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
731 llvm::Value *result =
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700732 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall7d166272011-05-15 07:14:44 +0000733
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 McCall1e7fe752010-09-02 09:58:18 +0000741 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000742
John McCall7d166272011-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)
747 size = CGF.Builder.CreateSelect(hasOverflow,
748 llvm::Constant::getAllOnesValue(CGF.SizeTy),
749 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000750 }
John McCall1e7fe752010-09-02 09:58:18 +0000751
John McCall7d166272011-05-15 07:14:44 +0000752 if (cookieSize == 0)
753 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000754 else
John McCall7d166272011-05-15 07:14:44 +0000755 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000756
John McCall7d166272011-05-15 07:14:44 +0000757 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000758}
759
Sebastian Redl92036472012-02-22 17:37:52 +0000760static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
761 QualType AllocType, llvm::Value *NewPtr) {
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000762 // FIXME: Refactor with EmitExprAsInit.
Eli Friedmand7722d92011-12-03 02:13:40 +0000763 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall9d232c82013-03-07 21:37:08 +0000764 switch (CGF.getEvaluationKind(AllocType)) {
765 case TEK_Scalar:
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700766 CGF.EmitScalarInit(Init, nullptr,
767 CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
John McCall9d232c82013-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 McCall558d2ab2010-09-15 10:14:12 +0000775 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000776 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000777 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000778 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000779 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000780 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000781 return;
John McCall558d2ab2010-09-15 10:14:12 +0000782 }
John McCall9d232c82013-03-07 21:37:08 +0000783 }
784 llvm_unreachable("bad evaluation kind");
Fariborz Jahanianef668722010-06-25 18:26:07 +0000785}
786
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700787void CodeGenFunction::EmitNewArrayInitializer(
788 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
789 llvm::Value *BeginPtr, llvm::Value *NumElements,
790 llvm::Value *AllocSizeWithoutCookie) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700791 // If we have a type with trivial initialization and no initializer,
792 // there's nothing to do.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000793 if (!E->hasInitializer())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700794 return;
John McCall19705672011-09-15 06:49:18 +0000795
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700796 llvm::Value *CurPtr = BeginPtr;
John McCall19705672011-09-15 06:49:18 +0000797
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700798 unsigned InitListElements = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000799
800 const Expr *Init = E->getInitializer();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700801 llvm::AllocaInst *EndOfInit = nullptr;
802 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
803 EHScopeStack::stable_iterator Cleanup;
804 llvm::Instruction *CleanupDominator = nullptr;
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000805
Sebastian Redl92036472012-02-22 17:37:52 +0000806 // If the initializer is an initializer list, first do the explicit elements.
807 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700808 InitListElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000809
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000810 // If this is a multi-dimensional array new, we will initialize multiple
811 // elements with each init list element.
812 QualType AllocType = E->getAllocatedType();
813 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
814 AllocType->getAsArrayTypeUnsafe())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700815 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700816 ElementTy = ConvertTypeForMem(AllocType);
817 llvm::Type *AllocPtrTy = ElementTy->getPointerTo(AS);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700818 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
819 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000820 }
821
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700822 // Enter a partial-destruction Cleanup if necessary.
823 if (needsEHCleanup(DtorKind)) {
824 // In principle we could tell the Cleanup where we are more
Chad Rosier577fb5b2012-02-24 00:13:55 +0000825 // directly, but the control flow can get so varied here that it
826 // would actually be quite complex. Therefore we go through an
827 // alloca.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700828 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
829 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
830 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
831 getDestroyer(DtorKind));
832 Cleanup = EHStack.stable_begin();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000833 }
834
Sebastian Redl92036472012-02-22 17:37:52 +0000835 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000836 // Tell the cleanup that it needs to destroy up to this
837 // element. TODO: some of these stores can be trivially
838 // observed to be unnecessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700839 if (EndOfInit)
840 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
841 EndOfInit);
842 // FIXME: If the last initializer is an incomplete initializer list for
843 // an array, and we have an array filler, we can fold together the two
844 // initialization loops.
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000845 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700846 ILE->getInit(i)->getType(), CurPtr);
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700847 CurPtr = Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr, 1,
848 "array.exp.next");
Sebastian Redl92036472012-02-22 17:37:52 +0000849 }
850
851 // The remaining elements are filled with the array filler expression.
852 Init = ILE->getArrayFiller();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000853
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700854 // 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 Redl92036472012-02-22 17:37:52 +0000867 }
868
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700869 // 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;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700875
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700876 // 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
897 // 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);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700904 return;
905 }
906
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700907 assert(Init && "have trailing elements to initialize but no initializer");
908
909 // If this is a constructor call, try to optimize it out, and failing that
910 // emit a single loop to initialize all remaining elements.
911 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
912 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));
Stephen Hines176edba2014-12-01 14:53:08 -0800934 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700935 CCE->requiresZeroInitialization());
936 return;
937 }
938
939 // If this is value-initialization, we can usually use memset.
940 ImplicitValueInitExpr IVIE(ElementType);
941 if (isa<ImplicitValueInitExpr>(Init)) {
942 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
956 // 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;
960
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700961 // If we have a struct whose every field is value-initialized, we can
962 // usually use memset.
963 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
964 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
965 if (RType->getDecl()->isStruct()) {
966 unsigned NumFields = 0;
967 for (auto *Field : RType->getDecl()->fields())
968 if (!Field->isUnnamedBitfield())
969 ++NumFields;
970 if (ILE->getNumInits() == NumFields)
971 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
972 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
973 --NumFields;
974 if (ILE->getNumInits() == NumFields && TryMemsetInitialization())
975 return;
976 }
977 }
978 }
979
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700980 // Create the loop blocks.
981 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
982 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
983 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
984
985 // Find the end of the array, hoisted out of the loop.
986 llvm::Value *EndPtr =
987 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall19705672011-09-15 06:49:18 +0000988
Sebastian Redl92036472012-02-22 17:37:52 +0000989 // If the number of elements isn't constant, we have to now check if there is
990 // anything left to initialize.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700991 if (!ConstNum) {
992 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall19705672011-09-15 06:49:18 +0000993 "array.isempty");
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700994 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall19705672011-09-15 06:49:18 +0000995 }
996
997 // Enter the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700998 EmitBlock(LoopBB);
John McCall19705672011-09-15 06:49:18 +0000999
1000 // Set up the current-element phi.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001001 llvm::PHINode *CurPtrPhi =
1002 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
1003 CurPtrPhi->addIncoming(CurPtr, EntryBB);
1004 CurPtr = CurPtrPhi;
John McCall19705672011-09-15 06:49:18 +00001005
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001006 // Store the new Cleanup position for irregular Cleanups.
1007 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosier577fb5b2012-02-24 00:13:55 +00001008
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001009 // Enter a partial-destruction Cleanup if necessary.
1010 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1011 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
1012 getDestroyer(DtorKind));
1013 Cleanup = EHStack.stable_begin();
1014 CleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +00001015 }
1016
1017 // Emit the initializer into this element.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001018 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall19705672011-09-15 06:49:18 +00001019
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001020 // Leave the Cleanup if we entered one.
1021 if (CleanupDominator) {
1022 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1023 CleanupDominator->eraseFromParent();
John McCall6f103ba2011-11-10 10:43:54 +00001024 }
John McCall19705672011-09-15 06:49:18 +00001025
Stephen Hines651f13c2014-04-23 16:59:28 -07001026 // Advance to the next element by adjusting the pointer type as necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001027 llvm::Value *NextPtr =
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001028 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr, 1, "array.next");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001029
John McCall19705672011-09-15 06:49:18 +00001030 // Check whether we've gotten to the end of the array and, if so,
1031 // exit the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001032 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1033 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1034 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall19705672011-09-15 06:49:18 +00001035
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001036 EmitBlock(ContBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +00001037}
1038
Anders Carlssona4d4c012009-09-23 16:07:23 +00001039static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001040 QualType ElementType, llvm::Type *ElementTy,
1041 llvm::Value *NewPtr, llvm::Value *NumElements,
Douglas Gregor59174c02010-07-21 01:10:17 +00001042 llvm::Value *AllocSizeWithoutCookie) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001043 ApplyDebugLocation DL(CGF, E);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001044 if (E->isArray())
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001045 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001046 AllocSizeWithoutCookie);
1047 else if (const Expr *Init = E->getInitializer())
1048 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001049}
1050
Richard Smithddcff1b2013-07-21 23:12:18 +00001051/// Emit a call to an operator new or operator delete function, as implicitly
1052/// created by new-expressions and delete-expressions.
1053static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1054 const FunctionDecl *Callee,
1055 const FunctionProtoType *CalleeType,
1056 const CallArgList &Args) {
1057 llvm::Instruction *CallOrInvoke;
Richard Smith060cb4a2013-07-29 20:14:16 +00001058 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smithddcff1b2013-07-21 23:12:18 +00001059 RValue RV =
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001060 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1061 Args, CalleeType, /*chainCall=*/false),
1062 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
Richard Smithddcff1b2013-07-21 23:12:18 +00001063
1064 /// C++1y [expr.new]p10:
1065 /// [In a new-expression,] an implementation is allowed to omit a call
1066 /// to a replaceable global allocation function.
1067 ///
1068 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola87017a72013-10-22 14:23:09 +00001069 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith060cb4a2013-07-29 20:14:16 +00001070 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola87017a72013-10-22 14:23:09 +00001071 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smithddcff1b2013-07-21 23:12:18 +00001072 // FIXME: Add addAttribute to CallSite.
1073 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1074 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1075 llvm::Attribute::Builtin);
1076 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1077 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1078 llvm::Attribute::Builtin);
1079 else
1080 llvm_unreachable("unexpected kind of call instruction");
1081 }
1082
1083 return RV;
1084}
1085
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001086RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1087 const Expr *Arg,
1088 bool IsDelete) {
1089 CallArgList Args;
1090 const Stmt *ArgS = Arg;
1091 EmitCallArgs(Args, *Type->param_type_begin(),
1092 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1093 // Find the allocation or deallocation function that we're calling.
1094 ASTContext &Ctx = getContext();
1095 DeclarationName Name = Ctx.DeclarationNames
1096 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1097 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1098 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1099 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1100 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1101 llvm_unreachable("predeclared global operator new/delete is missing");
1102}
1103
John McCall7d8647f2010-09-14 07:57:04 +00001104namespace {
1105 /// A cleanup to call the given 'operator delete' function upon
1106 /// abnormal exit from a new expression.
1107 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1108 size_t NumPlacementArgs;
1109 const FunctionDecl *OperatorDelete;
1110 llvm::Value *Ptr;
1111 llvm::Value *AllocSize;
1112
1113 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1114
1115 public:
1116 static size_t getExtraSize(size_t NumPlacementArgs) {
1117 return NumPlacementArgs * sizeof(RValue);
1118 }
1119
1120 CallDeleteDuringNew(size_t NumPlacementArgs,
1121 const FunctionDecl *OperatorDelete,
1122 llvm::Value *Ptr,
1123 llvm::Value *AllocSize)
1124 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1125 Ptr(Ptr), AllocSize(AllocSize) {}
1126
1127 void setPlacementArg(unsigned I, RValue Arg) {
1128 assert(I < NumPlacementArgs && "index out of range");
1129 getPlacementArgs()[I] = Arg;
1130 }
1131
Stephen Hines651f13c2014-04-23 16:59:28 -07001132 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7d8647f2010-09-14 07:57:04 +00001133 const FunctionProtoType *FPT
1134 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001135 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1136 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001137
1138 CallArgList DeleteArgs;
1139
1140 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001141 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001142 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001143
1144 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001145 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001146 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001147
1148 // Pass the rest of the arguments, which must match exactly.
1149 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001150 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001151
1152 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001153 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7d8647f2010-09-14 07:57:04 +00001154 }
1155 };
John McCall3019c442010-09-17 00:50:28 +00001156
1157 /// A cleanup to call the given 'operator delete' function upon
1158 /// abnormal exit from a new expression when the new expression is
1159 /// conditional.
1160 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1161 size_t NumPlacementArgs;
1162 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001163 DominatingValue<RValue>::saved_type Ptr;
1164 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001165
John McCall804b8072011-01-28 10:53:53 +00001166 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1167 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001168 }
1169
1170 public:
1171 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001172 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001173 }
1174
1175 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1176 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001177 DominatingValue<RValue>::saved_type Ptr,
1178 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001179 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1180 Ptr(Ptr), AllocSize(AllocSize) {}
1181
John McCall804b8072011-01-28 10:53:53 +00001182 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001183 assert(I < NumPlacementArgs && "index out of range");
1184 getPlacementArgs()[I] = Arg;
1185 }
1186
Stephen Hines651f13c2014-04-23 16:59:28 -07001187 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall3019c442010-09-17 00:50:28 +00001188 const FunctionProtoType *FPT
1189 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001190 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1191 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall3019c442010-09-17 00:50:28 +00001192
1193 CallArgList DeleteArgs;
1194
1195 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001196 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001197 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001198
1199 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001200 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001201 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001202 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001203 }
1204
1205 // Pass the rest of the arguments, which must match exactly.
1206 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001207 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001208 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001209 }
1210
1211 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001212 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall3019c442010-09-17 00:50:28 +00001213 }
1214 };
1215}
1216
1217/// Enter a cleanup to call 'operator delete' if the initializer in a
1218/// new-expression throws.
1219static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1220 const CXXNewExpr *E,
1221 llvm::Value *NewPtr,
1222 llvm::Value *AllocSize,
1223 const CallArgList &NewArgs) {
1224 // If we're not inside a conditional branch, then the cleanup will
1225 // dominate and we can do the easier (and more efficient) thing.
1226 if (!CGF.isInConditionalBranch()) {
1227 CallDeleteDuringNew *Cleanup = CGF.EHStack
1228 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1229 E->getNumPlacementArgs(),
1230 E->getOperatorDelete(),
1231 NewPtr, AllocSize);
1232 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001233 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001234
1235 return;
1236 }
1237
1238 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001239 DominatingValue<RValue>::saved_type SavedNewPtr =
1240 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1241 DominatingValue<RValue>::saved_type SavedAllocSize =
1242 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001243
1244 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001245 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001246 E->getNumPlacementArgs(),
1247 E->getOperatorDelete(),
1248 SavedNewPtr,
1249 SavedAllocSize);
1250 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001251 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001252 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001253
John McCall6f103ba2011-11-10 10:43:54 +00001254 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001255}
1256
Anders Carlsson16d81b82009-09-22 22:53:17 +00001257llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001258 // The element type being allocated.
1259 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001260
John McCallc2f3e7f2011-03-07 03:12:35 +00001261 // 1. Build a call to the allocation function.
1262 FunctionDecl *allocator = E->getOperatorNew();
1263 const FunctionProtoType *allocatorType =
1264 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001265
John McCallc2f3e7f2011-03-07 03:12:35 +00001266 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001267
1268 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001269 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001270
Sebastian Redl92036472012-02-22 17:37:52 +00001271 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1272 unsigned minElements = 0;
1273 if (E->isArray() && E->hasInitializer()) {
1274 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1275 minElements = ILE->getNumInits();
1276 }
1277
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001278 llvm::Value *numElements = nullptr;
1279 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCallc2f3e7f2011-03-07 03:12:35 +00001280 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001281 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1282 allocSizeWithoutCookie);
Stephen Hines176edba2014-12-01 14:53:08 -08001283
Eli Friedman04c9a492011-05-02 17:57:46 +00001284 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001285
Anders Carlsson16d81b82009-09-22 22:53:17 +00001286 // We start at 1 here because the first argument (the allocation size)
1287 // has already been emitted.
Stephen Hines176edba2014-12-01 14:53:08 -08001288 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
1289 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1290 /*ParamsToSkip*/ 1);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001291
John McCallb1c98a32011-05-16 01:05:12 +00001292 // Emit the allocation call. If the allocator is a global placement
1293 // operator, just "inline" it directly.
1294 RValue RV;
1295 if (allocator->isReservedGlobalPlacementOperator()) {
1296 assert(allocatorArgs.size() == 2);
1297 RV = allocatorArgs[1].RV;
1298 // TODO: kill any unnecessary computations done for the size
1299 // argument.
1300 } else {
Richard Smithddcff1b2013-07-21 23:12:18 +00001301 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCallb1c98a32011-05-16 01:05:12 +00001302 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001303
John McCallc2f3e7f2011-03-07 03:12:35 +00001304 // Emit a null check on the allocation result if the allocation
1305 // function is allowed to return null (because it has a non-throwing
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001306 // exception spec or is the reserved placement new) and we have an
John McCallc2f3e7f2011-03-07 03:12:35 +00001307 // interesting initializer.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001308 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001309 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001310
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001311 llvm::BasicBlock *nullCheckBB = nullptr;
1312 llvm::BasicBlock *contBB = nullptr;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001313
John McCallc2f3e7f2011-03-07 03:12:35 +00001314 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001315 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001316
John McCalla7f633f2011-03-07 01:52:56 +00001317 // The null-check means that the initializer is conditionally
1318 // evaluated.
1319 ConditionalEvaluation conditional(*this);
1320
John McCallc2f3e7f2011-03-07 03:12:35 +00001321 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001322 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001323
1324 nullCheckBB = Builder.GetInsertBlock();
1325 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1326 contBB = createBasicBlock("new.cont");
1327
1328 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1329 Builder.CreateCondBr(isNull, contBB, notNullBB);
1330 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001331 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001332
John McCall7d8647f2010-09-14 07:57:04 +00001333 // If there's an operator delete, enter a cleanup to call it if an
1334 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001335 EHScopeStack::stable_iterator operatorDeleteCleanup;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001336 llvm::Instruction *cleanupDominator = nullptr;
John McCallb1c98a32011-05-16 01:05:12 +00001337 if (E->getOperatorDelete() &&
1338 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001339 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1340 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001341 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001342 }
1343
Eli Friedman576cf172011-09-06 18:53:03 +00001344 assert((allocSize == allocSizeWithoutCookie) ==
1345 CalculateCookiePadding(*this, E).isZero());
1346 if (allocSize != allocSizeWithoutCookie) {
1347 assert(E->isArray());
1348 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1349 numElements,
1350 E, allocType);
1351 }
1352
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001353 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1354 llvm::Type *elementPtrTy = elementTy->getPointerTo(AS);
John McCallc2f3e7f2011-03-07 03:12:35 +00001355 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001356
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001357 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall19705672011-09-15 06:49:18 +00001358 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001359 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001360 // NewPtr is a pointer to the base element type. If we're
1361 // allocating an array of arrays, we'll need to cast back to the
1362 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001363 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001364 if (result->getType() != resultType)
1365 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001366 }
John McCall7d8647f2010-09-14 07:57:04 +00001367
1368 // Deactivate the 'operator delete' cleanup if we finished
1369 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001370 if (operatorDeleteCleanup.isValid()) {
1371 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1372 cleanupDominator->eraseFromParent();
1373 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001374
John McCallc2f3e7f2011-03-07 03:12:35 +00001375 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001376 conditional.end(*this);
1377
John McCallc2f3e7f2011-03-07 03:12:35 +00001378 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1379 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001380
Jay Foadbbf3bac2011-03-30 11:28:58 +00001381 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001382 PHI->addIncoming(result, notNullBB);
1383 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1384 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001385
John McCallc2f3e7f2011-03-07 03:12:35 +00001386 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001387 }
John McCall1e7fe752010-09-02 09:58:18 +00001388
John McCallc2f3e7f2011-03-07 03:12:35 +00001389 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001390}
1391
Eli Friedman5fe05982009-11-18 00:50:08 +00001392void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1393 llvm::Value *Ptr,
1394 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001395 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1396
Eli Friedman5fe05982009-11-18 00:50:08 +00001397 const FunctionProtoType *DeleteFTy =
1398 DeleteFD->getType()->getAs<FunctionProtoType>();
1399
1400 CallArgList DeleteArgs;
1401
Anders Carlsson871d0782009-12-13 20:04:38 +00001402 // Check if we need to pass the size to the delete operator.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001403 llvm::Value *Size = nullptr;
Anders Carlsson871d0782009-12-13 20:04:38 +00001404 QualType SizeTy;
Stephen Hines651f13c2014-04-23 16:59:28 -07001405 if (DeleteFTy->getNumParams() == 2) {
1406 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001407 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1408 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1409 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001410 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001411
1412 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedman5fe05982009-11-18 00:50:08 +00001413 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001414 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001415
Anders Carlsson871d0782009-12-13 20:04:38 +00001416 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001417 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001418
1419 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001420 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedman5fe05982009-11-18 00:50:08 +00001421}
1422
John McCall1e7fe752010-09-02 09:58:18 +00001423namespace {
1424 /// Calls the given 'operator delete' on a single object.
1425 struct CallObjectDelete : EHScopeStack::Cleanup {
1426 llvm::Value *Ptr;
1427 const FunctionDecl *OperatorDelete;
1428 QualType ElementType;
1429
1430 CallObjectDelete(llvm::Value *Ptr,
1431 const FunctionDecl *OperatorDelete,
1432 QualType ElementType)
1433 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1434
Stephen Hines651f13c2014-04-23 16:59:28 -07001435 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001436 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1437 }
1438 };
1439}
1440
Stephen Hines176edba2014-12-01 14:53:08 -08001441void
1442CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1443 llvm::Value *CompletePtr,
1444 QualType ElementType) {
1445 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1446 OperatorDelete, ElementType);
1447}
1448
John McCall1e7fe752010-09-02 09:58:18 +00001449/// Emit the code for deleting a single object.
1450static void EmitObjectDelete(CodeGenFunction &CGF,
Stephen Hines176edba2014-12-01 14:53:08 -08001451 const CXXDeleteExpr *DE,
John McCall1e7fe752010-09-02 09:58:18 +00001452 llvm::Value *Ptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001453 QualType ElementType) {
John McCall1e7fe752010-09-02 09:58:18 +00001454 // Find the destructor for the type, if applicable. If the
1455 // destructor is virtual, we'll just emit the vcall and return.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001456 const CXXDestructorDecl *Dtor = nullptr;
John McCall1e7fe752010-09-02 09:58:18 +00001457 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1458 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001459 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001460 Dtor = RD->getDestructor();
1461
1462 if (Dtor->isVirtual()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001463 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1464 Dtor);
John McCall1e7fe752010-09-02 09:58:18 +00001465 return;
1466 }
1467 }
1468 }
1469
1470 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001471 // This doesn't have to a conditional cleanup because we're going
1472 // to pop it off in a second.
Stephen Hines176edba2014-12-01 14:53:08 -08001473 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001474 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1475 Ptr, OperatorDelete, ElementType);
1476
1477 if (Dtor)
1478 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001479 /*ForVirtualBase=*/false,
1480 /*Delegating=*/false,
1481 Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001482 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001483 ElementType->isObjCLifetimeType()) {
1484 switch (ElementType.getObjCLifetime()) {
1485 case Qualifiers::OCL_None:
1486 case Qualifiers::OCL_ExplicitNone:
1487 case Qualifiers::OCL_Autoreleasing:
1488 break;
John McCall1e7fe752010-09-02 09:58:18 +00001489
John McCallf85e1932011-06-15 23:02:42 +00001490 case Qualifiers::OCL_Strong: {
1491 // Load the pointer value.
1492 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1493 ElementType.isVolatileQualified());
1494
John McCall5b07e802013-03-13 03:10:54 +00001495 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001496 break;
1497 }
1498
1499 case Qualifiers::OCL_Weak:
1500 CGF.EmitARCDestroyWeak(Ptr);
1501 break;
1502 }
1503 }
1504
John McCall1e7fe752010-09-02 09:58:18 +00001505 CGF.PopCleanupBlock();
1506}
1507
1508namespace {
1509 /// Calls the given 'operator delete' on an array of objects.
1510 struct CallArrayDelete : EHScopeStack::Cleanup {
1511 llvm::Value *Ptr;
1512 const FunctionDecl *OperatorDelete;
1513 llvm::Value *NumElements;
1514 QualType ElementType;
1515 CharUnits CookieSize;
1516
1517 CallArrayDelete(llvm::Value *Ptr,
1518 const FunctionDecl *OperatorDelete,
1519 llvm::Value *NumElements,
1520 QualType ElementType,
1521 CharUnits CookieSize)
1522 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1523 ElementType(ElementType), CookieSize(CookieSize) {}
1524
Stephen Hines651f13c2014-04-23 16:59:28 -07001525 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001526 const FunctionProtoType *DeleteFTy =
1527 OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001528 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall1e7fe752010-09-02 09:58:18 +00001529
1530 CallArgList Args;
1531
1532 // Pass the pointer as the first argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001533 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall1e7fe752010-09-02 09:58:18 +00001534 llvm::Value *DeletePtr
1535 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001536 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001537
1538 // Pass the original requested size as the second argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001539 if (DeleteFTy->getNumParams() == 2) {
1540 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001541 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001542 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1543
1544 CharUnits ElementTypeSize =
1545 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1546
1547 // The size of an element, multiplied by the number of elements.
1548 llvm::Value *Size
1549 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1550 Size = CGF.Builder.CreateMul(Size, NumElements);
1551
1552 // Plus the size of the cookie if applicable.
1553 if (!CookieSize.isZero()) {
1554 llvm::Value *CookieSizeV
1555 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1556 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1557 }
1558
Eli Friedman04c9a492011-05-02 17:57:46 +00001559 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001560 }
1561
1562 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001563 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall1e7fe752010-09-02 09:58:18 +00001564 }
1565 };
1566}
1567
1568/// Emit the code for deleting an array of objects.
1569static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001570 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001571 llvm::Value *deletedPtr,
1572 QualType elementType) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001573 llvm::Value *numElements = nullptr;
1574 llvm::Value *allocatedPtr = nullptr;
John McCall7cfd76c2011-07-13 01:41:37 +00001575 CharUnits cookieSize;
1576 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1577 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001578
John McCall7cfd76c2011-07-13 01:41:37 +00001579 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001580
1581 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001582 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001583 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001584 allocatedPtr, operatorDelete,
1585 numElements, elementType,
1586 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001587
John McCall7cfd76c2011-07-13 01:41:37 +00001588 // Destroy the elements.
1589 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1590 assert(numElements && "no element count for a type with a destructor!");
1591
John McCall7cfd76c2011-07-13 01:41:37 +00001592 llvm::Value *arrayEnd =
1593 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001594
1595 // Note that it is legal to allocate a zero-length array, and we
1596 // can never fold the check away because the length should always
1597 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001598 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1599 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001600 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001601 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001602 }
1603
John McCall7cfd76c2011-07-13 01:41:37 +00001604 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001605 CGF.PopCleanupBlock();
1606}
1607
Anders Carlsson16d81b82009-09-22 22:53:17 +00001608void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001609 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001610 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001611
1612 // Null check the pointer.
1613 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1614 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1615
Anders Carlssonb9241242011-04-11 00:30:07 +00001616 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001617
1618 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1619 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001620
John McCall1e7fe752010-09-02 09:58:18 +00001621 // We might be deleting a pointer to array. If so, GEP down to the
1622 // first non-array element.
1623 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1624 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1625 if (DeleteTy->isConstantArrayType()) {
1626 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001627 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001628
1629 GEP.push_back(Zero); // point at the outermost array
1630
1631 // For each layer of array type we're pointing at:
1632 while (const ConstantArrayType *Arr
1633 = getContext().getAsConstantArrayType(DeleteTy)) {
1634 // 1. Unpeel the array type.
1635 DeleteTy = Arr->getElementType();
1636
1637 // 2. GEP to the first element of the array.
1638 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001639 }
John McCall1e7fe752010-09-02 09:58:18 +00001640
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001641 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001642 }
1643
Douglas Gregoreede61a2010-09-02 17:38:50 +00001644 assert(ConvertTypeForMem(DeleteTy) ==
1645 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001646
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001647 if (E->isArrayForm()) {
1648 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1649 } else {
1650 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1651 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001652
Anders Carlsson16d81b82009-09-22 22:53:17 +00001653 EmitBlock(DeleteEnd);
1654}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001655
Stephen Hines176edba2014-12-01 14:53:08 -08001656static bool isGLValueFromPointerDeref(const Expr *E) {
1657 E = E->IgnoreParens();
1658
1659 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1660 if (!CE->getSubExpr()->isGLValue())
1661 return false;
1662 return isGLValueFromPointerDeref(CE->getSubExpr());
1663 }
1664
1665 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1666 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1667
1668 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1669 if (BO->getOpcode() == BO_Comma)
1670 return isGLValueFromPointerDeref(BO->getRHS());
1671
1672 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1673 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1674 isGLValueFromPointerDeref(ACO->getFalseExpr());
1675
1676 // C++11 [expr.sub]p1:
1677 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1678 if (isa<ArraySubscriptExpr>(E))
1679 return true;
1680
1681 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1682 if (UO->getOpcode() == UO_Deref)
1683 return true;
1684
1685 return false;
1686}
1687
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001688static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001689 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001690 // Get the vtable pointer.
1691 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1692
1693 // C++ [expr.typeid]p2:
1694 // If the glvalue expression is obtained by applying the unary * operator to
1695 // a pointer and the pointer is a null pointer value, the typeid expression
1696 // throws the std::bad_typeid exception.
Stephen Hines176edba2014-12-01 14:53:08 -08001697 //
1698 // However, this paragraph's intent is not clear. We choose a very generous
1699 // interpretation which implores us to consider comma operators, conditional
1700 // operators, parentheses and other such constructs.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001701 QualType SrcRecordTy = E->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08001702 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1703 isGLValueFromPointerDeref(E), SrcRecordTy)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001704 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001705 CGF.createBasicBlock("typeid.bad_typeid");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001706 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001707
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001708 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1709 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001710
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001711 CGF.EmitBlock(BadTypeidBlock);
1712 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1713 CGF.EmitBlock(EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001714 }
1715
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001716 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1717 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001718}
1719
John McCall3ad32c82011-01-28 08:37:24 +00001720llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001721 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001722 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001723
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001724 if (E->isTypeOperand()) {
David Majnemerfe16aa32013-09-27 07:04:31 +00001725 llvm::Constant *TypeInfo =
1726 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001727 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001728 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001729
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001730 // C++ [expr.typeid]p2:
1731 // When typeid is applied to a glvalue expression whose type is a
1732 // polymorphic class type, the result refers to a std::type_info object
1733 // representing the type of the most derived object (that is, the dynamic
1734 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001735 if (E->isPotentiallyEvaluated())
1736 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1737 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001738
1739 QualType OperandTy = E->getExprOperand()->getType();
1740 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1741 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001742}
Mike Stumpc849c052009-11-16 06:50:58 +00001743
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001744static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1745 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001746 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001747 if (DestTy->isPointerType())
1748 return llvm::Constant::getNullValue(DestLTy);
1749
1750 /// C++ [expr.dynamic.cast]p9:
1751 /// A failed cast to reference type throws std::bad_cast
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001752 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1753 return nullptr;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001754
1755 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1756 return llvm::UndefValue::get(DestLTy);
1757}
1758
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001759llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001760 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001761 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001762
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001763 if (DCE->isAlwaysNull())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001764 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1765 return T;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001766
1767 QualType SrcTy = DCE->getSubExpr()->getType();
1768
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001769 // C++ [expr.dynamic.cast]p7:
1770 // If T is "pointer to cv void," then the result is a pointer to the most
1771 // derived object pointed to by v.
1772 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1773
1774 bool isDynamicCastToVoid;
1775 QualType SrcRecordTy;
1776 QualType DestRecordTy;
1777 if (DestPTy) {
1778 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1779 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1780 DestRecordTy = DestPTy->getPointeeType();
1781 } else {
1782 isDynamicCastToVoid = false;
1783 SrcRecordTy = SrcTy;
1784 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1785 }
1786
1787 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1788
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001789 // C++ [expr.dynamic.cast]p4:
1790 // If the value of v is a null pointer value in the pointer case, the result
1791 // is the null pointer value of type T.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001792 bool ShouldNullCheckSrcValue =
1793 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1794 SrcRecordTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001795
1796 llvm::BasicBlock *CastNull = nullptr;
1797 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001798 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001799
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001800 if (ShouldNullCheckSrcValue) {
1801 CastNull = createBasicBlock("dynamic_cast.null");
1802 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1803
1804 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1805 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1806 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001807 }
1808
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001809 if (isDynamicCastToVoid) {
1810 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1811 DestTy);
1812 } else {
1813 assert(DestRecordTy->isRecordType() &&
1814 "destination type must be a record type!");
1815 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1816 DestTy, DestRecordTy, CastEnd);
1817 }
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001818
1819 if (ShouldNullCheckSrcValue) {
1820 EmitBranch(CastEnd);
1821
1822 EmitBlock(CastNull);
1823 EmitBranch(CastEnd);
1824 }
1825
1826 EmitBlock(CastEnd);
1827
1828 if (ShouldNullCheckSrcValue) {
1829 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1830 PHI->addIncoming(Value, CastNotNull);
1831 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1832
1833 Value = PHI;
1834 }
1835
1836 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001837}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001838
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001839void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001840 RunCleanupsScope Scope(*this);
Stephen Hines176edba2014-12-01 14:53:08 -08001841 LValue SlotLV =
1842 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001843
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001844 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1845 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1846 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001847 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001848 // Emit initialization
David Blaikie581deb32012-06-06 20:45:41 +00001849 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Stephen Hines176edba2014-12-01 14:53:08 -08001850 if (CurField->hasCapturedVLAType()) {
1851 auto VAT = CurField->getCapturedVLAType();
1852 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1853 } else {
1854 ArrayRef<VarDecl *> ArrayIndexes;
1855 if (CurField->getType()->isArrayType())
1856 ArrayIndexes = E->getCaptureInitIndexVars(i);
1857 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1858 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001859 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001860}