blob: 4876b1a6edaedf74ad19f309321857624cac6abb [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
David Majnemer0c0b6d92014-10-31 20:09:12 +000027static RequiredArgs commonEmitCXXMemberOrOperatorCall(
28 CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
29 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000031 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson27da15b2010-01-01 20:29:01 +000035
Richard Smith69d0d262012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
David Majnemer0c0b6d92014-10-31 20:09:12 +000042 CGF.EmitTypeCheck(
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000046
47 // Push the this ptr.
David Majnemer0c0b6d92014-10-31 20:09:12 +000048 Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000049
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000050 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000053 }
John McCalla729c622012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000057
John McCalla729c622012-02-17 03:33:10 +000058 // And the rest of the call args.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000059 if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000060 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000061 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Majnemer0c0b6d92014-10-31 20:09:12 +000062 CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
63 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000064 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000065 assert(
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000068 }
David Majnemer0c0b6d92014-10-31 20:09:12 +000069 return required;
70}
Anders Carlsson27da15b2010-01-01 20:29:01 +000071
David Majnemer0c0b6d92014-10-31 20:09:12 +000072RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
73 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
75 const CallExpr *CE) {
76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77 CallArgList Args;
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79 *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
80 Args);
John McCall8dda7b22012-07-07 06:41:13 +000081 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000082 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000083}
84
David Majnemer0c0b6d92014-10-31 20:09:12 +000085RValue CodeGenFunction::EmitCXXStructorCall(
86 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
87 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
88 const CallExpr *CE, StructorType Type) {
89 CallArgList Args;
90 commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
91 ImplicitParam, ImplicitParamTy, CE, Args);
92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
93 Callee, ReturnValue, Args, MD);
94}
95
Rafael Espindola3b33c4e2012-06-28 14:28:57 +000096static CXXRecordDecl *getCXXRecord(const Expr *E) {
97 QualType T = E->getType();
98 if (const PointerType *PTy = T->getAs<PointerType>())
99 T = PTy->getPointeeType();
100 const RecordType *Ty = T->castAs<RecordType>();
101 return cast<CXXRecordDecl>(Ty->getDecl());
102}
103
Francois Pichet64225792011-01-18 05:04:39 +0000104// Note: This function also emit constructor calls to support a MSVC
105// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000106RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000108 const Expr *callee = CE->getCallee()->IgnoreParens();
109
110 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000112
113 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
115
116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
120 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000121 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000122
Nico Weberaad4af62014-12-03 01:21:41 +0000123 bool HasQualifier = ME->hasQualifier();
124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000126 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000127
128 return EmitCXXMemberOrOperatorMemberCallExpr(
129 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
130}
131
132RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
133 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
134 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
135 const Expr *Base) {
136 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
137
138 // Compute the object pointer.
139 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000140
Craig Topper8a13c412014-05-21 05:09:00 +0000141 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000143 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
144 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
145 assert(DevirtualizedMethod);
146 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
147 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000148 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
149 MD->getReturnType().getCanonicalType())
150 // If the return types are not the same, this might be a case where more
151 // code needs to run to compensate for it. For example, the derived
152 // method might return a type that inherits form from the return
153 // type of MD and has a prefix.
154 // For now we just avoid devirtualizing these covariant cases.
155 DevirtualizedMethod = nullptr;
156 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000157 // If the class of the Inner expression is where the dynamic method
158 // is defined, build the this pointer from it.
159 Base = Inner;
160 else if (getCXXRecord(Base) != DevirtualizedClass) {
161 // If the method is defined in a class that is not the best dynamic
162 // one or the one of the full expression, we would have to build
163 // a derived-to-base cast to compute the correct this pointer, but
164 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000165 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000166 }
167 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000168
Anders Carlsson27da15b2010-01-01 20:29:01 +0000169 llvm::Value *This;
Nico Weberaad4af62014-12-03 01:21:41 +0000170 if (IsArrow)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000171 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000172 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000173 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000174
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175
John McCall0d635f52010-09-03 01:26:39 +0000176 if (MD->isTrivial()) {
Craig Topper8a13c412014-05-21 05:09:00 +0000177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000178 if (isa<CXXConstructorDecl>(MD) &&
179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000180 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000181
Nico Weberaad4af62014-12-03 01:21:41 +0000182 if (!MD->getParent()->mayInsertExtraPadding()) {
183 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
184 // We don't like to generate the trivial copy/move assignment operator
185 // when it isn't necessary; just produce the proper effect here.
186 // Special case: skip first argument of CXXOperatorCall (it is "this").
187 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
188 llvm::Value *RHS =
189 EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
David Blaikied73f3c62014-12-09 23:33:26 +0000190 if (auto *DI = getDebugInfo())
191 DI->EmitLocation(Builder, CE->getLocStart());
Nico Weberaad4af62014-12-03 01:21:41 +0000192 EmitAggregateAssign(This, RHS, CE->getType());
193 return RValue::get(This);
194 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000195
Nico Weberaad4af62014-12-03 01:21:41 +0000196 if (isa<CXXConstructorDecl>(MD) &&
197 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
198 // Trivial move and copy ctor are the same.
199 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
200 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
201 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
202 return RValue::get(This);
203 }
204 llvm_unreachable("unknown trivial member function");
Francois Pichet64225792011-01-18 05:04:39 +0000205 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000206 }
207
John McCall0d635f52010-09-03 01:26:39 +0000208 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000209 const CXXMethodDecl *CalleeDecl =
210 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000211 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000212 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000213 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
214 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000215 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000216 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
217 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000218 else
Eli Friedmanade60972012-10-25 00:12:49 +0000219 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000220
Reid Klecknere7de47e2013-07-22 13:51:44 +0000221 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000222
Anders Carlsson27da15b2010-01-01 20:29:01 +0000223 // C++ [class.virtual]p12:
224 // Explicit qualification with the scope operator (5.1) suppresses the
225 // virtual call mechanism.
226 //
227 // We also don't emit a virtual call if the base expression has a record type
228 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000229 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000230 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000231
John McCall0d635f52010-09-03 01:26:39 +0000232 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000233 assert(CE->arg_begin() == CE->arg_end() &&
234 "Destructor shouldn't have explicit parameters");
235 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000236 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000237 CGM.getCXXABI().EmitVirtualDestructorCall(
238 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239 } else {
Nico Weberaad4af62014-12-03 01:21:41 +0000240 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
241 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000242 else if (!DevirtualizedMethod)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000243 Callee =
244 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000245 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000246 const CXXDestructorDecl *DDtor =
247 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000248 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
249 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000250 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
251 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 }
Craig Topper8a13c412014-05-21 05:09:00 +0000253 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000254 }
255
256 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000257 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000258 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000259 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000260 } else {
Nico Weberaad4af62014-12-03 01:21:41 +0000261 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
262 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000263 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000264 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000265 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000266 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000267 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000268 }
269
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000270 if (MD->isVirtual()) {
271 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
272 *this, MD, This, UseVirtualCall);
273 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000274
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000275 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
276 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000277}
278
279RValue
280CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
281 ReturnValueSlot ReturnValue) {
282 const BinaryOperator *BO =
283 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
284 const Expr *BaseExpr = BO->getLHS();
285 const Expr *MemFnExpr = BO->getRHS();
286
287 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000288 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000289
Anders Carlsson27da15b2010-01-01 20:29:01 +0000290 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000291 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000292 const CXXRecordDecl *RD =
293 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
294
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000296 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000297
298 // Emit the 'this' pointer.
299 llvm::Value *This;
300
John McCalle3027922010-08-25 11:45:40 +0000301 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000302 This = EmitScalarExpr(BaseExpr);
303 else
304 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305
Richard Smithe30752c2012-10-09 19:52:38 +0000306 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
307 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000308
John McCall475999d2010-08-22 00:05:51 +0000309 // Ask the ABI to load the callee. Note that This is modified.
310 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000311 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312
Anders Carlsson27da15b2010-01-01 20:29:01 +0000313 CallArgList Args;
314
315 QualType ThisType =
316 getContext().getPointerType(getContext().getTagDeclType(RD));
317
318 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000319 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000320
321 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000322
323 // And the rest of the call args
Alexey Samsonov8e1162c2014-09-08 17:22:45 +0000324 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000325 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
326 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000327}
328
329RValue
330CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
331 const CXXMethodDecl *MD,
332 ReturnValueSlot ReturnValue) {
333 assert(MD->isInstance() &&
334 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000335 return EmitCXXMemberOrOperatorMemberCallExpr(
336 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
337 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000338}
339
Peter Collingbournefe883422011-10-06 18:29:37 +0000340RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
341 ReturnValueSlot ReturnValue) {
342 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
343}
344
Eli Friedmanfde961d2011-10-14 02:27:24 +0000345static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
346 llvm::Value *DestPtr,
347 const CXXRecordDecl *Base) {
348 if (Base->isEmpty())
349 return;
350
351 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
352
353 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
354 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000355 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000356
357 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
358
359 // If the type contains a pointer to data member we can't memset it to zero.
360 // Instead, create a null constant and copy it to the destination.
361 // TODO: there are other patterns besides zero that we can usefully memset,
362 // like -1, which happens to be the pattern used by member-pointers.
363 // TODO: isZeroInitializable can be over-conservative in the case where a
364 // virtual base contains a member pointer.
365 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
366 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
367
368 llvm::GlobalVariable *NullVariable =
369 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
370 /*isConstant=*/true,
371 llvm::GlobalVariable::PrivateLinkage,
372 NullConstant, Twine());
373 NullVariable->setAlignment(Align.getQuantity());
374 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
375
376 // Get and call the appropriate llvm.memcpy overload.
377 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
378 return;
379 }
380
381 // Otherwise, just memset the whole thing to zero. This is legal
382 // because in LLVM, all default initializers (other than the ones we just
383 // handled above) are guaranteed to have a bit pattern of all zeros.
384 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
385 Align.getQuantity());
386}
387
Anders Carlsson27da15b2010-01-01 20:29:01 +0000388void
John McCall7a626f62010-09-15 10:14:12 +0000389CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
390 AggValueSlot Dest) {
391 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000392 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000393
394 // If we require zero initialization before (or instead of) calling the
395 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000396 // constructor, emit the zero initialization now, unless destination is
397 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000398 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
399 switch (E->getConstructionKind()) {
400 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000401 case CXXConstructExpr::CK_Complete:
402 EmitNullInitialization(Dest.getAddr(), E->getType());
403 break;
404 case CXXConstructExpr::CK_VirtualBase:
405 case CXXConstructExpr::CK_NonVirtualBase:
406 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
407 break;
408 }
409 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000410
411 // If this is a call to a trivial default constructor, do nothing.
412 if (CD->isTrivial() && CD->isDefaultConstructor())
413 return;
414
John McCall8ea46b62010-09-18 00:58:34 +0000415 // Elide the constructor if we're constructing from a temporary.
416 // The temporary check is required because Sema sets this on NRVO
417 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000418 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000419 assert(getContext().hasSameUnqualifiedType(E->getType(),
420 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000421 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
422 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000423 return;
424 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000425 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000426
John McCallf677a8e2011-07-13 06:10:41 +0000427 if (const ConstantArrayType *arrayType
428 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000429 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000430 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000431 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000432 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000433 bool Delegating = false;
434
Alexis Hunt271c3682011-05-03 20:19:28 +0000435 switch (E->getConstructionKind()) {
436 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000437 // We should be emitting a constructor; GlobalDecl will assert this
438 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000439 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000440 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000441
Alexis Hunt271c3682011-05-03 20:19:28 +0000442 case CXXConstructExpr::CK_Complete:
443 Type = Ctor_Complete;
444 break;
445
446 case CXXConstructExpr::CK_VirtualBase:
447 ForVirtualBase = true;
448 // fall-through
449
450 case CXXConstructExpr::CK_NonVirtualBase:
451 Type = Ctor_Base;
452 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000453
Anders Carlsson27da15b2010-01-01 20:29:01 +0000454 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000455 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000456 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000457 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000458}
459
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000460void
461CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
462 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000463 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000464 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000465 Exp = E->getSubExpr();
466 assert(isa<CXXConstructExpr>(Exp) &&
467 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
468 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
469 const CXXConstructorDecl *CD = E->getConstructor();
470 RunCleanupsScope Scope(*this);
471
472 // If we require zero initialization before (or instead of) calling the
473 // constructor, as can be the case with a non-user-provided default
474 // constructor, emit the zero initialization now.
475 // FIXME. Do I still need this for a copy ctor synthesis?
476 if (E->requiresZeroInitialization())
477 EmitNullInitialization(Dest, E->getType());
478
Chandler Carruth99da11c2010-11-15 13:54:43 +0000479 assert(!getContext().getAsConstantArrayType(E->getType())
480 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000481 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000482}
483
John McCall8ed55a52010-09-02 09:58:18 +0000484static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
485 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000486 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000487 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000488
John McCall7ec4b432011-05-16 01:05:12 +0000489 // No cookie is required if the operator new[] being used is the
490 // reserved placement operator new[].
491 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000492 return CharUnits::Zero();
493
John McCall284c48f2011-01-27 09:37:56 +0000494 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000495}
496
John McCall036f2f62011-05-15 07:14:44 +0000497static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
498 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000499 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000500 llvm::Value *&numElements,
501 llvm::Value *&sizeWithoutCookie) {
502 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000503
John McCall036f2f62011-05-15 07:14:44 +0000504 if (!e->isArray()) {
505 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
506 sizeWithoutCookie
507 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
508 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000509 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000510
John McCall036f2f62011-05-15 07:14:44 +0000511 // The width of size_t.
512 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
513
John McCall8ed55a52010-09-02 09:58:18 +0000514 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000515 llvm::APInt cookieSize(sizeWidth,
516 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000517
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000518 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000519 // We multiply the size of all dimensions for NumElements.
520 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000521 numElements = CGF.EmitScalarExpr(e->getArraySize());
522 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000523
John McCall036f2f62011-05-15 07:14:44 +0000524 // The number of elements can be have an arbitrary integer type;
525 // essentially, we need to multiply it by a constant factor, add a
526 // cookie size, and verify that the result is representable as a
527 // size_t. That's just a gloss, though, and it's wrong in one
528 // important way: if the count is negative, it's an error even if
529 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000530 bool isSigned
531 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000532 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000533 = cast<llvm::IntegerType>(numElements->getType());
534 unsigned numElementsWidth = numElementsType->getBitWidth();
535
536 // Compute the constant factor.
537 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000538 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000539 = CGF.getContext().getAsConstantArrayType(type)) {
540 type = CAT->getElementType();
541 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000542 }
543
John McCall036f2f62011-05-15 07:14:44 +0000544 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
545 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
546 typeSizeMultiplier *= arraySizeMultiplier;
547
548 // This will be a size_t.
549 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000550
Chris Lattner32ac5832010-07-20 21:55:52 +0000551 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
552 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000553 if (llvm::ConstantInt *numElementsC =
554 dyn_cast<llvm::ConstantInt>(numElements)) {
555 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000556
John McCall036f2f62011-05-15 07:14:44 +0000557 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000558
John McCall036f2f62011-05-15 07:14:44 +0000559 // If 'count' was a negative number, it's an overflow.
560 if (isSigned && count.isNegative())
561 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000562
John McCall036f2f62011-05-15 07:14:44 +0000563 // We want to do all this arithmetic in size_t. If numElements is
564 // wider than that, check whether it's already too big, and if so,
565 // overflow.
566 else if (numElementsWidth > sizeWidth &&
567 numElementsWidth - sizeWidth > count.countLeadingZeros())
568 hasAnyOverflow = true;
569
570 // Okay, compute a count at the right width.
571 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
572
Sebastian Redlf862eb62012-02-22 17:37:52 +0000573 // If there is a brace-initializer, we cannot allocate fewer elements than
574 // there are initializers. If we do, that's treated like an overflow.
575 if (adjustedCount.ult(minElements))
576 hasAnyOverflow = true;
577
John McCall036f2f62011-05-15 07:14:44 +0000578 // Scale numElements by that. This might overflow, but we don't
579 // care because it only overflows if allocationSize does, too, and
580 // if that overflows then we shouldn't use this.
581 numElements = llvm::ConstantInt::get(CGF.SizeTy,
582 adjustedCount * arraySizeMultiplier);
583
584 // Compute the size before cookie, and track whether it overflowed.
585 bool overflow;
586 llvm::APInt allocationSize
587 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
588 hasAnyOverflow |= overflow;
589
590 // Add in the cookie, and check whether it's overflowed.
591 if (cookieSize != 0) {
592 // Save the current size without a cookie. This shouldn't be
593 // used if there was overflow.
594 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
595
596 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
597 hasAnyOverflow |= overflow;
598 }
599
600 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000601 if (hasAnyOverflow) {
602 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
603 } else {
John McCall036f2f62011-05-15 07:14:44 +0000604 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000605 }
John McCall036f2f62011-05-15 07:14:44 +0000606
607 // Otherwise, we might need to use the overflow intrinsics.
608 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000609 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000610 // 1) if isSigned, we need to check whether numElements is negative;
611 // 2) if numElementsWidth > sizeWidth, we need to check whether
612 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000613 // 3) if minElements > 0, we need to check whether numElements is smaller
614 // than that.
615 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000616 // sizeWithoutCookie := numElements * typeSizeMultiplier
617 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000618 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000619 // size := sizeWithoutCookie + cookieSize
620 // and check whether it overflows.
621
Craig Topper8a13c412014-05-21 05:09:00 +0000622 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000623
624 // If numElementsWidth > sizeWidth, then one way or another, we're
625 // going to have to do a comparison for (2), and this happens to
626 // take care of (1), too.
627 if (numElementsWidth > sizeWidth) {
628 llvm::APInt threshold(numElementsWidth, 1);
629 threshold <<= sizeWidth;
630
631 llvm::Value *thresholdV
632 = llvm::ConstantInt::get(numElementsType, threshold);
633
634 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
635 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
636
637 // Otherwise, if we're signed, we want to sext up to size_t.
638 } else if (isSigned) {
639 if (numElementsWidth < sizeWidth)
640 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
641
642 // If there's a non-1 type size multiplier, then we can do the
643 // signedness check at the same time as we do the multiply
644 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000645 // unsigned overflow. Otherwise, we have to do it here. But at least
646 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000647 if (typeSizeMultiplier == 1)
648 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000649 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000650
651 // Otherwise, zext up to size_t if necessary.
652 } else if (numElementsWidth < sizeWidth) {
653 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
654 }
655
656 assert(numElements->getType() == CGF.SizeTy);
657
Sebastian Redlf862eb62012-02-22 17:37:52 +0000658 if (minElements) {
659 // Don't allow allocation of fewer elements than we have initializers.
660 if (!hasOverflow) {
661 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
662 llvm::ConstantInt::get(CGF.SizeTy, minElements));
663 } else if (numElementsWidth > sizeWidth) {
664 // The other existing overflow subsumes this check.
665 // We do an unsigned comparison, since any signed value < -1 is
666 // taken care of either above or below.
667 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
668 CGF.Builder.CreateICmpULT(numElements,
669 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
670 }
671 }
672
John McCall036f2f62011-05-15 07:14:44 +0000673 size = numElements;
674
675 // Multiply by the type size if necessary. This multiplier
676 // includes all the factors for nested arrays.
677 //
678 // This step also causes numElements to be scaled up by the
679 // nested-array factor if necessary. Overflow on this computation
680 // can be ignored because the result shouldn't be used if
681 // allocation fails.
682 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000683 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000684 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000685
686 llvm::Value *tsmV =
687 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
688 llvm::Value *result =
689 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
690
691 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
692 if (hasOverflow)
693 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
694 else
695 hasOverflow = overflowed;
696
697 size = CGF.Builder.CreateExtractValue(result, 0);
698
699 // Also scale up numElements by the array size multiplier.
700 if (arraySizeMultiplier != 1) {
701 // If the base element type size is 1, then we can re-use the
702 // multiply we just did.
703 if (typeSize.isOne()) {
704 assert(arraySizeMultiplier == typeSizeMultiplier);
705 numElements = size;
706
707 // Otherwise we need a separate multiply.
708 } else {
709 llvm::Value *asmV =
710 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
711 numElements = CGF.Builder.CreateMul(numElements, asmV);
712 }
713 }
714 } else {
715 // numElements doesn't need to be scaled.
716 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000717 }
718
John McCall036f2f62011-05-15 07:14:44 +0000719 // Add in the cookie size if necessary.
720 if (cookieSize != 0) {
721 sizeWithoutCookie = size;
722
John McCall036f2f62011-05-15 07:14:44 +0000723 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000724 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000725
726 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
727 llvm::Value *result =
728 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
729
730 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
731 if (hasOverflow)
732 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
733 else
734 hasOverflow = overflowed;
735
736 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000737 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000738
John McCall036f2f62011-05-15 07:14:44 +0000739 // If we had any possibility of dynamic overflow, make a select to
740 // overwrite 'size' with an all-ones value, which should cause
741 // operator new to throw.
742 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000743 size = CGF.Builder.CreateSelect(hasOverflow,
744 llvm::Constant::getAllOnesValue(CGF.SizeTy),
745 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000746 }
John McCall8ed55a52010-09-02 09:58:18 +0000747
John McCall036f2f62011-05-15 07:14:44 +0000748 if (cookieSize == 0)
749 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000750 else
John McCall036f2f62011-05-15 07:14:44 +0000751 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000752
John McCall036f2f62011-05-15 07:14:44 +0000753 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000754}
755
Sebastian Redlf862eb62012-02-22 17:37:52 +0000756static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
757 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000758 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000759 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000760 switch (CGF.getEvaluationKind(AllocType)) {
761 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000762 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
763 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000764 false);
John McCall47fb9502013-03-07 21:37:08 +0000765 return;
766 case TEK_Complex:
767 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
768 Alignment),
769 /*isInit*/ true);
770 return;
771 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000772 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000773 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000774 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000775 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000776 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000777 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000778 return;
John McCall7a626f62010-09-15 10:14:12 +0000779 }
John McCall47fb9502013-03-07 21:37:08 +0000780 }
781 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000782}
783
784void
Richard Smith06a67e22014-06-03 06:58:52 +0000785CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
786 QualType ElementType,
787 llvm::Value *BeginPtr,
788 llvm::Value *NumElements,
789 llvm::Value *AllocSizeWithoutCookie) {
790 // If we have a type with trivial initialization and no initializer,
791 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000792 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000793 return;
John McCall99210dc2011-09-15 06:49:18 +0000794
Richard Smith06a67e22014-06-03 06:58:52 +0000795 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000796
Richard Smith06a67e22014-06-03 06:58:52 +0000797 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000798
799 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000800 llvm::AllocaInst *EndOfInit = nullptr;
801 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
802 EHScopeStack::stable_iterator Cleanup;
803 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000804
Sebastian Redlf862eb62012-02-22 17:37:52 +0000805 // If the initializer is an initializer list, first do the explicit elements.
806 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000807 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000808
Richard Smith1c96bc52013-12-11 01:40:16 +0000809 // If this is a multi-dimensional array new, we will initialize multiple
810 // elements with each init list element.
811 QualType AllocType = E->getAllocatedType();
812 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
813 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000814 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000815 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000816 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
817 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000818 }
819
Richard Smith06a67e22014-06-03 06:58:52 +0000820 // Enter a partial-destruction Cleanup if necessary.
821 if (needsEHCleanup(DtorKind)) {
822 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000823 // directly, but the control flow can get so varied here that it
824 // would actually be quite complex. Therefore we go through an
825 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000826 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
827 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
828 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
829 getDestroyer(DtorKind));
830 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000831 }
832
Sebastian Redlf862eb62012-02-22 17:37:52 +0000833 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000834 // Tell the cleanup that it needs to destroy up to this
835 // element. TODO: some of these stores can be trivially
836 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000837 if (EndOfInit)
838 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
839 EndOfInit);
840 // FIXME: If the last initializer is an incomplete initializer list for
841 // an array, and we have an array filler, we can fold together the two
842 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000843 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000844 ILE->getInit(i)->getType(), CurPtr);
845 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000846 }
847
848 // The remaining elements are filled with the array filler expression.
849 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000850
Richard Smith06a67e22014-06-03 06:58:52 +0000851 // Extract the initializer for the individual array elements by pulling
852 // out the array filler from all the nested initializer lists. This avoids
853 // generating a nested loop for the initialization.
854 while (Init && Init->getType()->isConstantArrayType()) {
855 auto *SubILE = dyn_cast<InitListExpr>(Init);
856 if (!SubILE)
857 break;
858 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
859 Init = SubILE->getArrayFiller();
860 }
861
862 // Switch back to initializing one base element at a time.
863 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000864 }
865
Richard Smith06a67e22014-06-03 06:58:52 +0000866 // Attempt to perform zero-initialization using memset.
867 auto TryMemsetInitialization = [&]() -> bool {
868 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
869 // we can initialize with a memset to -1.
870 if (!CGM.getTypes().isZeroInitializable(ElementType))
871 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000872
Richard Smith06a67e22014-06-03 06:58:52 +0000873 // Optimization: since zero initialization will just set the memory
874 // to all zeroes, generate a single memset to do it in one shot.
875
876 // Subtract out the size of any elements we've already initialized.
877 auto *RemainingSize = AllocSizeWithoutCookie;
878 if (InitListElements) {
879 // We know this can't overflow; we check this when doing the allocation.
880 auto *InitializedSize = llvm::ConstantInt::get(
881 RemainingSize->getType(),
882 getContext().getTypeSizeInChars(ElementType).getQuantity() *
883 InitListElements);
884 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
885 }
886
887 // Create the memset.
888 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
889 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
890 Alignment.getQuantity(), false);
891 return true;
892 };
893
Richard Smith454a7cd2014-06-03 08:26:00 +0000894 // If all elements have already been initialized, skip any further
895 // initialization.
896 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
897 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
898 // If there was a Cleanup, deactivate it.
899 if (CleanupDominator)
900 DeactivateCleanupBlock(Cleanup, CleanupDominator);
901 return;
902 }
903
904 assert(Init && "have trailing elements to initialize but no initializer");
905
Richard Smith06a67e22014-06-03 06:58:52 +0000906 // If this is a constructor call, try to optimize it out, and failing that
907 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000908 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000909 CXXConstructorDecl *Ctor = CCE->getConstructor();
910 if (Ctor->isTrivial()) {
911 // If new expression did not specify value-initialization, then there
912 // is no initialization.
913 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
914 return;
915
916 if (TryMemsetInitialization())
917 return;
918 }
919
920 // Store the new Cleanup position for irregular Cleanups.
921 //
922 // FIXME: Share this cleanup with the constructor call emission rather than
923 // having it create a cleanup of its own.
924 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
925
926 // Emit a constructor call loop to initialize the remaining elements.
927 if (InitListElements)
928 NumElements = Builder.CreateSub(
929 NumElements,
930 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000931 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000932 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000933 return;
934 }
935
Richard Smith06a67e22014-06-03 06:58:52 +0000936 // If this is value-initialization, we can usually use memset.
937 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000938 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000939 if (TryMemsetInitialization())
940 return;
941
942 // Switch to an ImplicitValueInitExpr for the element type. This handles
943 // only one case: multidimensional array new of pointers to members. In
944 // all other cases, we already have an initializer for the array element.
945 Init = &IVIE;
946 }
947
948 // At this point we should have found an initializer for the individual
949 // elements of the array.
950 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
951 "got wrong type of element to initialize");
952
Richard Smith454a7cd2014-06-03 08:26:00 +0000953 // If we have an empty initializer list, we can usually use memset.
954 if (auto *ILE = dyn_cast<InitListExpr>(Init))
955 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
956 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000957
958 // Create the loop blocks.
959 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
960 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
961 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
962
963 // Find the end of the array, hoisted out of the loop.
964 llvm::Value *EndPtr =
965 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000966
Sebastian Redlf862eb62012-02-22 17:37:52 +0000967 // If the number of elements isn't constant, we have to now check if there is
968 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000969 if (!ConstNum) {
970 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000971 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000972 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000973 }
974
975 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000976 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000977
978 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000979 llvm::PHINode *CurPtrPhi =
980 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
981 CurPtrPhi->addIncoming(CurPtr, EntryBB);
982 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000983
Richard Smith06a67e22014-06-03 06:58:52 +0000984 // Store the new Cleanup position for irregular Cleanups.
985 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000986
Richard Smith06a67e22014-06-03 06:58:52 +0000987 // Enter a partial-destruction Cleanup if necessary.
988 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
989 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
990 getDestroyer(DtorKind));
991 Cleanup = EHStack.stable_begin();
992 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000993 }
994
995 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000996 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +0000997
Richard Smith06a67e22014-06-03 06:58:52 +0000998 // Leave the Cleanup if we entered one.
999 if (CleanupDominator) {
1000 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1001 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001002 }
John McCall99210dc2011-09-15 06:49:18 +00001003
Faisal Vali57ae0562013-12-14 00:40:05 +00001004 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001005 llvm::Value *NextPtr =
1006 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
1007
John McCall99210dc2011-09-15 06:49:18 +00001008 // Check whether we've gotten to the end of the array and, if so,
1009 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001010 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1011 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1012 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001013
Richard Smith06a67e22014-06-03 06:58:52 +00001014 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001015}
1016
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001017static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +00001018 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001019 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001020 llvm::Value *NumElements,
1021 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +00001022 if (E->isArray())
1023 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
1024 AllocSizeWithoutCookie);
1025 else if (const Expr *Init = E->getInitializer())
1026 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001027}
1028
Richard Smith8d0dc312013-07-21 23:12:18 +00001029/// Emit a call to an operator new or operator delete function, as implicitly
1030/// created by new-expressions and delete-expressions.
1031static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1032 const FunctionDecl *Callee,
1033 const FunctionProtoType *CalleeType,
1034 const CallArgList &Args) {
1035 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001036 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001037 RValue RV =
1038 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +00001039 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +00001040 Callee, &CallOrInvoke);
1041
1042 /// C++1y [expr.new]p10:
1043 /// [In a new-expression,] an implementation is allowed to omit a call
1044 /// to a replaceable global allocation function.
1045 ///
1046 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001047 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001048 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001049 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001050 // FIXME: Add addAttribute to CallSite.
1051 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1052 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1053 llvm::Attribute::Builtin);
1054 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1055 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1056 llvm::Attribute::Builtin);
1057 else
1058 llvm_unreachable("unexpected kind of call instruction");
1059 }
1060
1061 return RV;
1062}
1063
Richard Smith760520b2014-06-03 23:27:44 +00001064RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1065 const Expr *Arg,
1066 bool IsDelete) {
1067 CallArgList Args;
1068 const Stmt *ArgS = Arg;
1069 EmitCallArgs(Args, *Type->param_type_begin(),
1070 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1071 // Find the allocation or deallocation function that we're calling.
1072 ASTContext &Ctx = getContext();
1073 DeclarationName Name = Ctx.DeclarationNames
1074 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1075 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001076 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1077 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1078 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001079 llvm_unreachable("predeclared global operator new/delete is missing");
1080}
1081
John McCall824c2f52010-09-14 07:57:04 +00001082namespace {
1083 /// A cleanup to call the given 'operator delete' function upon
1084 /// abnormal exit from a new expression.
1085 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1086 size_t NumPlacementArgs;
1087 const FunctionDecl *OperatorDelete;
1088 llvm::Value *Ptr;
1089 llvm::Value *AllocSize;
1090
1091 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1092
1093 public:
1094 static size_t getExtraSize(size_t NumPlacementArgs) {
1095 return NumPlacementArgs * sizeof(RValue);
1096 }
1097
1098 CallDeleteDuringNew(size_t NumPlacementArgs,
1099 const FunctionDecl *OperatorDelete,
1100 llvm::Value *Ptr,
1101 llvm::Value *AllocSize)
1102 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1103 Ptr(Ptr), AllocSize(AllocSize) {}
1104
1105 void setPlacementArg(unsigned I, RValue Arg) {
1106 assert(I < NumPlacementArgs && "index out of range");
1107 getPlacementArgs()[I] = Arg;
1108 }
1109
Craig Topper4f12f102014-03-12 06:41:41 +00001110 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001111 const FunctionProtoType *FPT
1112 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001113 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1114 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001115
1116 CallArgList DeleteArgs;
1117
1118 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001119 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001120 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001121
1122 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001123 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001124 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001125
1126 // Pass the rest of the arguments, which must match exactly.
1127 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001128 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001129
1130 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001131 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001132 }
1133 };
John McCall7f9c92a2010-09-17 00:50:28 +00001134
1135 /// A cleanup to call the given 'operator delete' function upon
1136 /// abnormal exit from a new expression when the new expression is
1137 /// conditional.
1138 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1139 size_t NumPlacementArgs;
1140 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001141 DominatingValue<RValue>::saved_type Ptr;
1142 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001143
John McCallcb5f77f2011-01-28 10:53:53 +00001144 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1145 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001146 }
1147
1148 public:
1149 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001150 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001151 }
1152
1153 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1154 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001155 DominatingValue<RValue>::saved_type Ptr,
1156 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001157 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1158 Ptr(Ptr), AllocSize(AllocSize) {}
1159
John McCallcb5f77f2011-01-28 10:53:53 +00001160 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001161 assert(I < NumPlacementArgs && "index out of range");
1162 getPlacementArgs()[I] = Arg;
1163 }
1164
Craig Topper4f12f102014-03-12 06:41:41 +00001165 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001166 const FunctionProtoType *FPT
1167 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001168 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1169 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001170
1171 CallArgList DeleteArgs;
1172
1173 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001174 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001175 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001176
1177 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001178 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001179 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001180 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001181 }
1182
1183 // Pass the rest of the arguments, which must match exactly.
1184 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001185 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001186 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001187 }
1188
1189 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001190 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001191 }
1192 };
1193}
1194
1195/// Enter a cleanup to call 'operator delete' if the initializer in a
1196/// new-expression throws.
1197static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1198 const CXXNewExpr *E,
1199 llvm::Value *NewPtr,
1200 llvm::Value *AllocSize,
1201 const CallArgList &NewArgs) {
1202 // If we're not inside a conditional branch, then the cleanup will
1203 // dominate and we can do the easier (and more efficient) thing.
1204 if (!CGF.isInConditionalBranch()) {
1205 CallDeleteDuringNew *Cleanup = CGF.EHStack
1206 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1207 E->getNumPlacementArgs(),
1208 E->getOperatorDelete(),
1209 NewPtr, AllocSize);
1210 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001211 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001212
1213 return;
1214 }
1215
1216 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001217 DominatingValue<RValue>::saved_type SavedNewPtr =
1218 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1219 DominatingValue<RValue>::saved_type SavedAllocSize =
1220 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001221
1222 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001223 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001224 E->getNumPlacementArgs(),
1225 E->getOperatorDelete(),
1226 SavedNewPtr,
1227 SavedAllocSize);
1228 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001229 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001230 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001231
John McCallf4beacd2011-11-10 10:43:54 +00001232 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001233}
1234
Anders Carlssoncc52f652009-09-22 22:53:17 +00001235llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001236 // The element type being allocated.
1237 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001238
John McCall75f94982011-03-07 03:12:35 +00001239 // 1. Build a call to the allocation function.
1240 FunctionDecl *allocator = E->getOperatorNew();
1241 const FunctionProtoType *allocatorType =
1242 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001243
John McCall75f94982011-03-07 03:12:35 +00001244 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001245
1246 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001247 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001248
Sebastian Redlf862eb62012-02-22 17:37:52 +00001249 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1250 unsigned minElements = 0;
1251 if (E->isArray() && E->hasInitializer()) {
1252 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1253 minElements = ILE->getNumInits();
1254 }
1255
Craig Topper8a13c412014-05-21 05:09:00 +00001256 llvm::Value *numElements = nullptr;
1257 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001258 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001259 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1260 allocSizeWithoutCookie);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001261
Eli Friedman43dca6a2011-05-02 17:57:46 +00001262 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001263
Anders Carlssoncc52f652009-09-22 22:53:17 +00001264 // We start at 1 here because the first argument (the allocation size)
1265 // has already been emitted.
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001266 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001267 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1268 /*ParamsToSkip*/ 1);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001269
John McCall7ec4b432011-05-16 01:05:12 +00001270 // Emit the allocation call. If the allocator is a global placement
1271 // operator, just "inline" it directly.
1272 RValue RV;
1273 if (allocator->isReservedGlobalPlacementOperator()) {
1274 assert(allocatorArgs.size() == 2);
1275 RV = allocatorArgs[1].RV;
1276 // TODO: kill any unnecessary computations done for the size
1277 // argument.
1278 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001279 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001280 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001281
John McCall75f94982011-03-07 03:12:35 +00001282 // Emit a null check on the allocation result if the allocation
1283 // function is allowed to return null (because it has a non-throwing
1284 // exception spec; for this part, we inline
1285 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1286 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001287 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001288 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001289
Craig Topper8a13c412014-05-21 05:09:00 +00001290 llvm::BasicBlock *nullCheckBB = nullptr;
1291 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001292
John McCall75f94982011-03-07 03:12:35 +00001293 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001294 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001295
John McCallf7dcf322011-03-07 01:52:56 +00001296 // The null-check means that the initializer is conditionally
1297 // evaluated.
1298 ConditionalEvaluation conditional(*this);
1299
John McCall75f94982011-03-07 03:12:35 +00001300 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001301 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001302
1303 nullCheckBB = Builder.GetInsertBlock();
1304 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1305 contBB = createBasicBlock("new.cont");
1306
1307 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1308 Builder.CreateCondBr(isNull, contBB, notNullBB);
1309 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001310 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001311
John McCall824c2f52010-09-14 07:57:04 +00001312 // If there's an operator delete, enter a cleanup to call it if an
1313 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001314 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001315 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001316 if (E->getOperatorDelete() &&
1317 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001318 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1319 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001320 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001321 }
1322
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001323 assert((allocSize == allocSizeWithoutCookie) ==
1324 CalculateCookiePadding(*this, E).isZero());
1325 if (allocSize != allocSizeWithoutCookie) {
1326 assert(E->isArray());
1327 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1328 numElements,
1329 E, allocType);
1330 }
1331
Chris Lattner2192fe52011-07-18 04:24:23 +00001332 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001333 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1334 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001335
John McCall99210dc2011-09-15 06:49:18 +00001336 EmitNewInitializer(*this, E, allocType, result, numElements,
1337 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001338 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001339 // NewPtr is a pointer to the base element type. If we're
1340 // allocating an array of arrays, we'll need to cast back to the
1341 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001342 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001343 if (result->getType() != resultType)
1344 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001345 }
John McCall824c2f52010-09-14 07:57:04 +00001346
1347 // Deactivate the 'operator delete' cleanup if we finished
1348 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001349 if (operatorDeleteCleanup.isValid()) {
1350 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1351 cleanupDominator->eraseFromParent();
1352 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001353
John McCall75f94982011-03-07 03:12:35 +00001354 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001355 conditional.end(*this);
1356
John McCall75f94982011-03-07 03:12:35 +00001357 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1358 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001359
Jay Foad20c0f022011-03-30 11:28:58 +00001360 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001361 PHI->addIncoming(result, notNullBB);
1362 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1363 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001364
John McCall75f94982011-03-07 03:12:35 +00001365 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001366 }
John McCall8ed55a52010-09-02 09:58:18 +00001367
John McCall75f94982011-03-07 03:12:35 +00001368 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001369}
1370
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001371void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1372 llvm::Value *Ptr,
1373 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001374 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1375
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001376 const FunctionProtoType *DeleteFTy =
1377 DeleteFD->getType()->getAs<FunctionProtoType>();
1378
1379 CallArgList DeleteArgs;
1380
Anders Carlsson21122cf2009-12-13 20:04:38 +00001381 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001382 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001383 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001384 if (DeleteFTy->getNumParams() == 2) {
1385 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001386 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1387 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1388 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001389 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001390
1391 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001392 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001393 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001394
Anders Carlsson21122cf2009-12-13 20:04:38 +00001395 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001396 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001397
1398 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001399 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001400}
1401
John McCall8ed55a52010-09-02 09:58:18 +00001402namespace {
1403 /// Calls the given 'operator delete' on a single object.
1404 struct CallObjectDelete : EHScopeStack::Cleanup {
1405 llvm::Value *Ptr;
1406 const FunctionDecl *OperatorDelete;
1407 QualType ElementType;
1408
1409 CallObjectDelete(llvm::Value *Ptr,
1410 const FunctionDecl *OperatorDelete,
1411 QualType ElementType)
1412 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1413
Craig Topper4f12f102014-03-12 06:41:41 +00001414 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001415 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1416 }
1417 };
1418}
1419
David Majnemer0c0b6d92014-10-31 20:09:12 +00001420void
1421CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1422 llvm::Value *CompletePtr,
1423 QualType ElementType) {
1424 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1425 OperatorDelete, ElementType);
1426}
1427
John McCall8ed55a52010-09-02 09:58:18 +00001428/// Emit the code for deleting a single object.
1429static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001430 const CXXDeleteExpr *DE,
John McCall8ed55a52010-09-02 09:58:18 +00001431 llvm::Value *Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001432 QualType ElementType) {
John McCall8ed55a52010-09-02 09:58:18 +00001433 // Find the destructor for the type, if applicable. If the
1434 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001435 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001436 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1437 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001438 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001439 Dtor = RD->getDestructor();
1440
1441 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001442 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1443 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001444 return;
1445 }
1446 }
1447 }
1448
1449 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001450 // This doesn't have to a conditional cleanup because we're going
1451 // to pop it off in a second.
David Majnemer08681372014-11-01 07:37:17 +00001452 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001453 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1454 Ptr, OperatorDelete, ElementType);
1455
1456 if (Dtor)
1457 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001458 /*ForVirtualBase=*/false,
1459 /*Delegating=*/false,
1460 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001461 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001462 ElementType->isObjCLifetimeType()) {
1463 switch (ElementType.getObjCLifetime()) {
1464 case Qualifiers::OCL_None:
1465 case Qualifiers::OCL_ExplicitNone:
1466 case Qualifiers::OCL_Autoreleasing:
1467 break;
John McCall8ed55a52010-09-02 09:58:18 +00001468
John McCall31168b02011-06-15 23:02:42 +00001469 case Qualifiers::OCL_Strong: {
1470 // Load the pointer value.
1471 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1472 ElementType.isVolatileQualified());
1473
John McCallcdda29c2013-03-13 03:10:54 +00001474 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001475 break;
1476 }
1477
1478 case Qualifiers::OCL_Weak:
1479 CGF.EmitARCDestroyWeak(Ptr);
1480 break;
1481 }
1482 }
1483
John McCall8ed55a52010-09-02 09:58:18 +00001484 CGF.PopCleanupBlock();
1485}
1486
1487namespace {
1488 /// Calls the given 'operator delete' on an array of objects.
1489 struct CallArrayDelete : EHScopeStack::Cleanup {
1490 llvm::Value *Ptr;
1491 const FunctionDecl *OperatorDelete;
1492 llvm::Value *NumElements;
1493 QualType ElementType;
1494 CharUnits CookieSize;
1495
1496 CallArrayDelete(llvm::Value *Ptr,
1497 const FunctionDecl *OperatorDelete,
1498 llvm::Value *NumElements,
1499 QualType ElementType,
1500 CharUnits CookieSize)
1501 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1502 ElementType(ElementType), CookieSize(CookieSize) {}
1503
Craig Topper4f12f102014-03-12 06:41:41 +00001504 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001505 const FunctionProtoType *DeleteFTy =
1506 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001507 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001508
1509 CallArgList Args;
1510
1511 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001512 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001513 llvm::Value *DeletePtr
1514 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001515 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001516
1517 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001518 if (DeleteFTy->getNumParams() == 2) {
1519 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001520 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001521 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1522
1523 CharUnits ElementTypeSize =
1524 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1525
1526 // The size of an element, multiplied by the number of elements.
1527 llvm::Value *Size
1528 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1529 Size = CGF.Builder.CreateMul(Size, NumElements);
1530
1531 // Plus the size of the cookie if applicable.
1532 if (!CookieSize.isZero()) {
1533 llvm::Value *CookieSizeV
1534 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1535 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1536 }
1537
Eli Friedman43dca6a2011-05-02 17:57:46 +00001538 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001539 }
1540
1541 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001542 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001543 }
1544 };
1545}
1546
1547/// Emit the code for deleting an array of objects.
1548static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001549 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001550 llvm::Value *deletedPtr,
1551 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001552 llvm::Value *numElements = nullptr;
1553 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001554 CharUnits cookieSize;
1555 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1556 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001557
John McCallca2c56f2011-07-13 01:41:37 +00001558 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001559
1560 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001561 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001562 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001563 allocatedPtr, operatorDelete,
1564 numElements, elementType,
1565 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001566
John McCallca2c56f2011-07-13 01:41:37 +00001567 // Destroy the elements.
1568 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1569 assert(numElements && "no element count for a type with a destructor!");
1570
John McCallca2c56f2011-07-13 01:41:37 +00001571 llvm::Value *arrayEnd =
1572 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001573
1574 // Note that it is legal to allocate a zero-length array, and we
1575 // can never fold the check away because the length should always
1576 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001577 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1578 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001579 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001580 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001581 }
1582
John McCallca2c56f2011-07-13 01:41:37 +00001583 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001584 CGF.PopCleanupBlock();
1585}
1586
Anders Carlssoncc52f652009-09-22 22:53:17 +00001587void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001588 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001589 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001590
1591 // Null check the pointer.
1592 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1593 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1594
Anders Carlsson98981b12011-04-11 00:30:07 +00001595 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001596
1597 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1598 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001599
John McCall8ed55a52010-09-02 09:58:18 +00001600 // We might be deleting a pointer to array. If so, GEP down to the
1601 // first non-array element.
1602 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1603 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1604 if (DeleteTy->isConstantArrayType()) {
1605 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001606 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001607
1608 GEP.push_back(Zero); // point at the outermost array
1609
1610 // For each layer of array type we're pointing at:
1611 while (const ConstantArrayType *Arr
1612 = getContext().getAsConstantArrayType(DeleteTy)) {
1613 // 1. Unpeel the array type.
1614 DeleteTy = Arr->getElementType();
1615
1616 // 2. GEP to the first element of the array.
1617 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001618 }
John McCall8ed55a52010-09-02 09:58:18 +00001619
Jay Foad040dd822011-07-22 08:16:57 +00001620 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001621 }
1622
Douglas Gregor04f36212010-09-02 17:38:50 +00001623 assert(ConvertTypeForMem(DeleteTy) ==
1624 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001625
1626 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001627 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001628 } else {
David Majnemer08681372014-11-01 07:37:17 +00001629 EmitObjectDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001630 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001631
Anders Carlssoncc52f652009-09-22 22:53:17 +00001632 EmitBlock(DeleteEnd);
1633}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001634
David Majnemer1c3d95e2014-07-19 00:17:06 +00001635static bool isGLValueFromPointerDeref(const Expr *E) {
1636 E = E->IgnoreParens();
1637
1638 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1639 if (!CE->getSubExpr()->isGLValue())
1640 return false;
1641 return isGLValueFromPointerDeref(CE->getSubExpr());
1642 }
1643
1644 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1645 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1646
1647 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1648 if (BO->getOpcode() == BO_Comma)
1649 return isGLValueFromPointerDeref(BO->getRHS());
1650
1651 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1652 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1653 isGLValueFromPointerDeref(ACO->getFalseExpr());
1654
1655 // C++11 [expr.sub]p1:
1656 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1657 if (isa<ArraySubscriptExpr>(E))
1658 return true;
1659
1660 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1661 if (UO->getOpcode() == UO_Deref)
1662 return true;
1663
1664 return false;
1665}
1666
Warren Hunt747e3012014-06-18 21:15:55 +00001667static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001668 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001669 // Get the vtable pointer.
1670 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1671
1672 // C++ [expr.typeid]p2:
1673 // If the glvalue expression is obtained by applying the unary * operator to
1674 // a pointer and the pointer is a null pointer value, the typeid expression
1675 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001676 //
1677 // However, this paragraph's intent is not clear. We choose a very generous
1678 // interpretation which implores us to consider comma operators, conditional
1679 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001680 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001681 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1682 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001683 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001684 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001685 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001686
David Majnemer1162d252014-06-22 19:05:33 +00001687 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1688 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001689
David Majnemer1162d252014-06-22 19:05:33 +00001690 CGF.EmitBlock(BadTypeidBlock);
1691 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1692 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001693 }
1694
David Majnemer1162d252014-06-22 19:05:33 +00001695 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1696 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001697}
1698
John McCalle4df6c82011-01-28 08:37:24 +00001699llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001700 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001701 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001702
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001703 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001704 llvm::Constant *TypeInfo =
1705 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001706 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001707 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001708
Anders Carlsson940f02d2011-04-18 00:57:03 +00001709 // C++ [expr.typeid]p2:
1710 // When typeid is applied to a glvalue expression whose type is a
1711 // polymorphic class type, the result refers to a std::type_info object
1712 // representing the type of the most derived object (that is, the dynamic
1713 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001714 if (E->isPotentiallyEvaluated())
1715 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1716 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001717
1718 QualType OperandTy = E->getExprOperand()->getType();
1719 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1720 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001721}
Mike Stump65511702009-11-16 06:50:58 +00001722
Anders Carlssonc1c99712011-04-11 01:45:29 +00001723static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1724 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001725 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001726 if (DestTy->isPointerType())
1727 return llvm::Constant::getNullValue(DestLTy);
1728
1729 /// C++ [expr.dynamic.cast]p9:
1730 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001731 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1732 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001733
1734 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1735 return llvm::UndefValue::get(DestLTy);
1736}
1737
Anders Carlsson882d7902011-04-11 00:46:40 +00001738llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001739 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001740 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001741
Anders Carlssonc1c99712011-04-11 01:45:29 +00001742 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001743 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1744 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001745
1746 QualType SrcTy = DCE->getSubExpr()->getType();
1747
David Majnemer1162d252014-06-22 19:05:33 +00001748 // C++ [expr.dynamic.cast]p7:
1749 // If T is "pointer to cv void," then the result is a pointer to the most
1750 // derived object pointed to by v.
1751 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1752
1753 bool isDynamicCastToVoid;
1754 QualType SrcRecordTy;
1755 QualType DestRecordTy;
1756 if (DestPTy) {
1757 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1758 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1759 DestRecordTy = DestPTy->getPointeeType();
1760 } else {
1761 isDynamicCastToVoid = false;
1762 SrcRecordTy = SrcTy;
1763 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1764 }
1765
1766 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1767
Anders Carlsson882d7902011-04-11 00:46:40 +00001768 // C++ [expr.dynamic.cast]p4:
1769 // If the value of v is a null pointer value in the pointer case, the result
1770 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001771 bool ShouldNullCheckSrcValue =
1772 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1773 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001774
1775 llvm::BasicBlock *CastNull = nullptr;
1776 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001777 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001778
Anders Carlsson882d7902011-04-11 00:46:40 +00001779 if (ShouldNullCheckSrcValue) {
1780 CastNull = createBasicBlock("dynamic_cast.null");
1781 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1782
1783 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1784 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1785 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001786 }
1787
David Majnemer1162d252014-06-22 19:05:33 +00001788 if (isDynamicCastToVoid) {
1789 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1790 DestTy);
1791 } else {
1792 assert(DestRecordTy->isRecordType() &&
1793 "destination type must be a record type!");
1794 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1795 DestTy, DestRecordTy, CastEnd);
1796 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001797
1798 if (ShouldNullCheckSrcValue) {
1799 EmitBranch(CastEnd);
1800
1801 EmitBlock(CastNull);
1802 EmitBranch(CastEnd);
1803 }
1804
1805 EmitBlock(CastEnd);
1806
1807 if (ShouldNullCheckSrcValue) {
1808 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1809 PHI->addIncoming(Value, CastNotNull);
1810 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1811
1812 Value = PHI;
1813 }
1814
1815 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001816}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001817
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001818void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001819 RunCleanupsScope Scope(*this);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001820 LValue SlotLV =
1821 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001822
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001823 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1824 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1825 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001826 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001827 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00001828 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001829 if (CurField->hasCapturedVLAType()) {
1830 auto VAT = CurField->getCapturedVLAType();
1831 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1832 } else {
1833 ArrayRef<VarDecl *> ArrayIndexes;
1834 if (CurField->getType()->isArrayType())
1835 ArrayIndexes = E->getCaptureInitIndexVars(i);
1836 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1837 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001838 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001839}