blob: ff084de41c616914debfb9cdd853d8c5b1b0309f [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
John McCall0d635f52010-09-03 01:26:39 +0000123 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000124 const Expr *Base = ME->getBase();
125 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000126
Craig Topper8a13c412014-05-21 05:09:00 +0000127 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000128 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000129 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
130 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
131 assert(DevirtualizedMethod);
132 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
133 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000134 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
135 MD->getReturnType().getCanonicalType())
136 // If the return types are not the same, this might be a case where more
137 // code needs to run to compensate for it. For example, the derived
138 // method might return a type that inherits form from the return
139 // type of MD and has a prefix.
140 // For now we just avoid devirtualizing these covariant cases.
141 DevirtualizedMethod = nullptr;
142 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000143 // If the class of the Inner expression is where the dynamic method
144 // is defined, build the this pointer from it.
145 Base = Inner;
146 else if (getCXXRecord(Base) != DevirtualizedClass) {
147 // If the method is defined in a class that is not the best dynamic
148 // one or the one of the full expression, we would have to build
149 // a derived-to-base cast to compute the correct this pointer, but
150 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000151 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000152 }
153 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000154
Anders Carlsson27da15b2010-01-01 20:29:01 +0000155 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000156 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000157 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000158 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000159 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000160
Anders Carlsson27da15b2010-01-01 20:29:01 +0000161
John McCall0d635f52010-09-03 01:26:39 +0000162 if (MD->isTrivial()) {
Craig Topper8a13c412014-05-21 05:09:00 +0000163 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000164 if (isa<CXXConstructorDecl>(MD) &&
165 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000166 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000167
Sebastian Redl22653ba2011-08-30 19:58:05 +0000168 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
169 // We don't like to generate the trivial copy/move assignment operator
170 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000171 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000172 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000173 return RValue::get(This);
174 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000175
176 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000177 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
178 // Trivial move and copy ctor are the same.
Alexey Samsonov525bf652014-08-25 21:58:56 +0000179 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Francois Pichet64225792011-01-18 05:04:39 +0000180 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Alexey Samsonov525bf652014-08-25 21:58:56 +0000181 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000182 return RValue::get(This);
183 }
184 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000185 }
186
John McCall0d635f52010-09-03 01:26:39 +0000187 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000188 const CXXMethodDecl *CalleeDecl =
189 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000190 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000191 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000192 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
193 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000194 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000195 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
196 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000197 else
Eli Friedmanade60972012-10-25 00:12:49 +0000198 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000199
Reid Klecknere7de47e2013-07-22 13:51:44 +0000200 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000201
Anders Carlsson27da15b2010-01-01 20:29:01 +0000202 // C++ [class.virtual]p12:
203 // Explicit qualification with the scope operator (5.1) suppresses the
204 // virtual call mechanism.
205 //
206 // We also don't emit a virtual call if the base expression has a record type
207 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000208 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000209 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000210
John McCall0d635f52010-09-03 01:26:39 +0000211 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000212 assert(CE->arg_begin() == CE->arg_end() &&
213 "Destructor shouldn't have explicit parameters");
214 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000215 if (UseVirtualCall) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000216 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000217 This, CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000218 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000219 if (getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000220 MD->isVirtual() &&
221 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000222 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000223 else if (!DevirtualizedMethod)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000224 Callee =
225 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000226 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000227 const CXXDestructorDecl *DDtor =
228 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000229 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
230 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000231 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
232 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000233 }
Craig Topper8a13c412014-05-21 05:09:00 +0000234 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000235 }
236
237 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000238 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000239 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000240 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000241 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000242 if (getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000243 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000244 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000245 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000246 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000247 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000248 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000249 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000250 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000251 }
252
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000253 if (MD->isVirtual()) {
254 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
255 *this, MD, This, UseVirtualCall);
256 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000257
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000258 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
259 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000260}
261
262RValue
263CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
264 ReturnValueSlot ReturnValue) {
265 const BinaryOperator *BO =
266 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
267 const Expr *BaseExpr = BO->getLHS();
268 const Expr *MemFnExpr = BO->getRHS();
269
270 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000271 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000272
Anders Carlsson27da15b2010-01-01 20:29:01 +0000273 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000274 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000275 const CXXRecordDecl *RD =
276 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
277
Anders Carlsson27da15b2010-01-01 20:29:01 +0000278 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000279 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000280
281 // Emit the 'this' pointer.
282 llvm::Value *This;
283
John McCalle3027922010-08-25 11:45:40 +0000284 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000285 This = EmitScalarExpr(BaseExpr);
286 else
287 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000288
Richard Smithe30752c2012-10-09 19:52:38 +0000289 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
290 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000291
John McCall475999d2010-08-22 00:05:51 +0000292 // Ask the ABI to load the callee. Note that This is modified.
293 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000294 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 CallArgList Args;
297
298 QualType ThisType =
299 getContext().getPointerType(getContext().getTagDeclType(RD));
300
301 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000302 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000303
304 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305
306 // And the rest of the call args
Alexey Samsonov8e1162c2014-09-08 17:22:45 +0000307 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000308 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
309 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000310}
311
312RValue
313CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
314 const CXXMethodDecl *MD,
315 ReturnValueSlot ReturnValue) {
316 assert(MD->isInstance() &&
317 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000318 LValue LV = EmitLValue(E->getArg(0));
319 llvm::Value *This = LV.getAddress();
320
Douglas Gregor146b8e92011-09-06 16:26:56 +0000321 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
Kostya Serebryany4133eab2014-11-11 23:38:13 +0000322 MD->isTrivial() && !MD->getParent()->mayInsertExtraPadding()) {
Douglas Gregor146b8e92011-09-06 16:26:56 +0000323 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
324 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000325 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000326 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000327 }
328
Anders Carlssonc36783e2011-05-08 20:32:23 +0000329 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000330 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
331 /*ImplicitParam=*/nullptr, QualType(), E);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000332}
333
Peter Collingbournefe883422011-10-06 18:29:37 +0000334RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
335 ReturnValueSlot ReturnValue) {
336 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
337}
338
Eli Friedmanfde961d2011-10-14 02:27:24 +0000339static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
340 llvm::Value *DestPtr,
341 const CXXRecordDecl *Base) {
342 if (Base->isEmpty())
343 return;
344
345 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
346
347 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
348 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000349 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000350
351 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
352
353 // If the type contains a pointer to data member we can't memset it to zero.
354 // Instead, create a null constant and copy it to the destination.
355 // TODO: there are other patterns besides zero that we can usefully memset,
356 // like -1, which happens to be the pattern used by member-pointers.
357 // TODO: isZeroInitializable can be over-conservative in the case where a
358 // virtual base contains a member pointer.
359 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
360 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
361
362 llvm::GlobalVariable *NullVariable =
363 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
364 /*isConstant=*/true,
365 llvm::GlobalVariable::PrivateLinkage,
366 NullConstant, Twine());
367 NullVariable->setAlignment(Align.getQuantity());
368 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
369
370 // Get and call the appropriate llvm.memcpy overload.
371 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
372 return;
373 }
374
375 // Otherwise, just memset the whole thing to zero. This is legal
376 // because in LLVM, all default initializers (other than the ones we just
377 // handled above) are guaranteed to have a bit pattern of all zeros.
378 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
379 Align.getQuantity());
380}
381
Anders Carlsson27da15b2010-01-01 20:29:01 +0000382void
John McCall7a626f62010-09-15 10:14:12 +0000383CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
384 AggValueSlot Dest) {
385 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000386 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000387
388 // If we require zero initialization before (or instead of) calling the
389 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000390 // constructor, emit the zero initialization now, unless destination is
391 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000392 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
393 switch (E->getConstructionKind()) {
394 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000395 case CXXConstructExpr::CK_Complete:
396 EmitNullInitialization(Dest.getAddr(), E->getType());
397 break;
398 case CXXConstructExpr::CK_VirtualBase:
399 case CXXConstructExpr::CK_NonVirtualBase:
400 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
401 break;
402 }
403 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000404
405 // If this is a call to a trivial default constructor, do nothing.
406 if (CD->isTrivial() && CD->isDefaultConstructor())
407 return;
408
John McCall8ea46b62010-09-18 00:58:34 +0000409 // Elide the constructor if we're constructing from a temporary.
410 // The temporary check is required because Sema sets this on NRVO
411 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000412 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000413 assert(getContext().hasSameUnqualifiedType(E->getType(),
414 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000415 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
416 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000417 return;
418 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000419 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000420
John McCallf677a8e2011-07-13 06:10:41 +0000421 if (const ConstantArrayType *arrayType
422 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000423 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000424 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000425 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000426 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000427 bool Delegating = false;
428
Alexis Hunt271c3682011-05-03 20:19:28 +0000429 switch (E->getConstructionKind()) {
430 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000431 // We should be emitting a constructor; GlobalDecl will assert this
432 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000433 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000434 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000435
Alexis Hunt271c3682011-05-03 20:19:28 +0000436 case CXXConstructExpr::CK_Complete:
437 Type = Ctor_Complete;
438 break;
439
440 case CXXConstructExpr::CK_VirtualBase:
441 ForVirtualBase = true;
442 // fall-through
443
444 case CXXConstructExpr::CK_NonVirtualBase:
445 Type = Ctor_Base;
446 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000447
Anders Carlsson27da15b2010-01-01 20:29:01 +0000448 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000449 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000450 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000451 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000452}
453
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000454void
455CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
456 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000457 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000458 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000459 Exp = E->getSubExpr();
460 assert(isa<CXXConstructExpr>(Exp) &&
461 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
462 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
463 const CXXConstructorDecl *CD = E->getConstructor();
464 RunCleanupsScope Scope(*this);
465
466 // If we require zero initialization before (or instead of) calling the
467 // constructor, as can be the case with a non-user-provided default
468 // constructor, emit the zero initialization now.
469 // FIXME. Do I still need this for a copy ctor synthesis?
470 if (E->requiresZeroInitialization())
471 EmitNullInitialization(Dest, E->getType());
472
Chandler Carruth99da11c2010-11-15 13:54:43 +0000473 assert(!getContext().getAsConstantArrayType(E->getType())
474 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000475 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000476}
477
John McCall8ed55a52010-09-02 09:58:18 +0000478static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
479 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000480 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000481 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000482
John McCall7ec4b432011-05-16 01:05:12 +0000483 // No cookie is required if the operator new[] being used is the
484 // reserved placement operator new[].
485 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000486 return CharUnits::Zero();
487
John McCall284c48f2011-01-27 09:37:56 +0000488 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000489}
490
John McCall036f2f62011-05-15 07:14:44 +0000491static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
492 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000493 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000494 llvm::Value *&numElements,
495 llvm::Value *&sizeWithoutCookie) {
496 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000497
John McCall036f2f62011-05-15 07:14:44 +0000498 if (!e->isArray()) {
499 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
500 sizeWithoutCookie
501 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
502 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000503 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000504
John McCall036f2f62011-05-15 07:14:44 +0000505 // The width of size_t.
506 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
507
John McCall8ed55a52010-09-02 09:58:18 +0000508 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000509 llvm::APInt cookieSize(sizeWidth,
510 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000511
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000512 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000513 // We multiply the size of all dimensions for NumElements.
514 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000515 numElements = CGF.EmitScalarExpr(e->getArraySize());
516 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000517
John McCall036f2f62011-05-15 07:14:44 +0000518 // The number of elements can be have an arbitrary integer type;
519 // essentially, we need to multiply it by a constant factor, add a
520 // cookie size, and verify that the result is representable as a
521 // size_t. That's just a gloss, though, and it's wrong in one
522 // important way: if the count is negative, it's an error even if
523 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000524 bool isSigned
525 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000526 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000527 = cast<llvm::IntegerType>(numElements->getType());
528 unsigned numElementsWidth = numElementsType->getBitWidth();
529
530 // Compute the constant factor.
531 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000532 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000533 = CGF.getContext().getAsConstantArrayType(type)) {
534 type = CAT->getElementType();
535 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000536 }
537
John McCall036f2f62011-05-15 07:14:44 +0000538 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
539 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
540 typeSizeMultiplier *= arraySizeMultiplier;
541
542 // This will be a size_t.
543 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000544
Chris Lattner32ac5832010-07-20 21:55:52 +0000545 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
546 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000547 if (llvm::ConstantInt *numElementsC =
548 dyn_cast<llvm::ConstantInt>(numElements)) {
549 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000550
John McCall036f2f62011-05-15 07:14:44 +0000551 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000552
John McCall036f2f62011-05-15 07:14:44 +0000553 // If 'count' was a negative number, it's an overflow.
554 if (isSigned && count.isNegative())
555 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000556
John McCall036f2f62011-05-15 07:14:44 +0000557 // We want to do all this arithmetic in size_t. If numElements is
558 // wider than that, check whether it's already too big, and if so,
559 // overflow.
560 else if (numElementsWidth > sizeWidth &&
561 numElementsWidth - sizeWidth > count.countLeadingZeros())
562 hasAnyOverflow = true;
563
564 // Okay, compute a count at the right width.
565 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
566
Sebastian Redlf862eb62012-02-22 17:37:52 +0000567 // If there is a brace-initializer, we cannot allocate fewer elements than
568 // there are initializers. If we do, that's treated like an overflow.
569 if (adjustedCount.ult(minElements))
570 hasAnyOverflow = true;
571
John McCall036f2f62011-05-15 07:14:44 +0000572 // Scale numElements by that. This might overflow, but we don't
573 // care because it only overflows if allocationSize does, too, and
574 // if that overflows then we shouldn't use this.
575 numElements = llvm::ConstantInt::get(CGF.SizeTy,
576 adjustedCount * arraySizeMultiplier);
577
578 // Compute the size before cookie, and track whether it overflowed.
579 bool overflow;
580 llvm::APInt allocationSize
581 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
582 hasAnyOverflow |= overflow;
583
584 // Add in the cookie, and check whether it's overflowed.
585 if (cookieSize != 0) {
586 // Save the current size without a cookie. This shouldn't be
587 // used if there was overflow.
588 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
589
590 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
591 hasAnyOverflow |= overflow;
592 }
593
594 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000595 if (hasAnyOverflow) {
596 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
597 } else {
John McCall036f2f62011-05-15 07:14:44 +0000598 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000599 }
John McCall036f2f62011-05-15 07:14:44 +0000600
601 // Otherwise, we might need to use the overflow intrinsics.
602 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000603 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000604 // 1) if isSigned, we need to check whether numElements is negative;
605 // 2) if numElementsWidth > sizeWidth, we need to check whether
606 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000607 // 3) if minElements > 0, we need to check whether numElements is smaller
608 // than that.
609 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000610 // sizeWithoutCookie := numElements * typeSizeMultiplier
611 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000612 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000613 // size := sizeWithoutCookie + cookieSize
614 // and check whether it overflows.
615
Craig Topper8a13c412014-05-21 05:09:00 +0000616 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000617
618 // If numElementsWidth > sizeWidth, then one way or another, we're
619 // going to have to do a comparison for (2), and this happens to
620 // take care of (1), too.
621 if (numElementsWidth > sizeWidth) {
622 llvm::APInt threshold(numElementsWidth, 1);
623 threshold <<= sizeWidth;
624
625 llvm::Value *thresholdV
626 = llvm::ConstantInt::get(numElementsType, threshold);
627
628 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
629 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
630
631 // Otherwise, if we're signed, we want to sext up to size_t.
632 } else if (isSigned) {
633 if (numElementsWidth < sizeWidth)
634 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
635
636 // If there's a non-1 type size multiplier, then we can do the
637 // signedness check at the same time as we do the multiply
638 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000639 // unsigned overflow. Otherwise, we have to do it here. But at least
640 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000641 if (typeSizeMultiplier == 1)
642 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000643 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000644
645 // Otherwise, zext up to size_t if necessary.
646 } else if (numElementsWidth < sizeWidth) {
647 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
648 }
649
650 assert(numElements->getType() == CGF.SizeTy);
651
Sebastian Redlf862eb62012-02-22 17:37:52 +0000652 if (minElements) {
653 // Don't allow allocation of fewer elements than we have initializers.
654 if (!hasOverflow) {
655 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
656 llvm::ConstantInt::get(CGF.SizeTy, minElements));
657 } else if (numElementsWidth > sizeWidth) {
658 // The other existing overflow subsumes this check.
659 // We do an unsigned comparison, since any signed value < -1 is
660 // taken care of either above or below.
661 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
662 CGF.Builder.CreateICmpULT(numElements,
663 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
664 }
665 }
666
John McCall036f2f62011-05-15 07:14:44 +0000667 size = numElements;
668
669 // Multiply by the type size if necessary. This multiplier
670 // includes all the factors for nested arrays.
671 //
672 // This step also causes numElements to be scaled up by the
673 // nested-array factor if necessary. Overflow on this computation
674 // can be ignored because the result shouldn't be used if
675 // allocation fails.
676 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000677 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000678 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000679
680 llvm::Value *tsmV =
681 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
682 llvm::Value *result =
683 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
684
685 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
686 if (hasOverflow)
687 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
688 else
689 hasOverflow = overflowed;
690
691 size = CGF.Builder.CreateExtractValue(result, 0);
692
693 // Also scale up numElements by the array size multiplier.
694 if (arraySizeMultiplier != 1) {
695 // If the base element type size is 1, then we can re-use the
696 // multiply we just did.
697 if (typeSize.isOne()) {
698 assert(arraySizeMultiplier == typeSizeMultiplier);
699 numElements = size;
700
701 // Otherwise we need a separate multiply.
702 } else {
703 llvm::Value *asmV =
704 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
705 numElements = CGF.Builder.CreateMul(numElements, asmV);
706 }
707 }
708 } else {
709 // numElements doesn't need to be scaled.
710 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000711 }
712
John McCall036f2f62011-05-15 07:14:44 +0000713 // Add in the cookie size if necessary.
714 if (cookieSize != 0) {
715 sizeWithoutCookie = size;
716
John McCall036f2f62011-05-15 07:14:44 +0000717 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000718 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000719
720 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
721 llvm::Value *result =
722 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
723
724 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
725 if (hasOverflow)
726 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
727 else
728 hasOverflow = overflowed;
729
730 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000731 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000732
John McCall036f2f62011-05-15 07:14:44 +0000733 // If we had any possibility of dynamic overflow, make a select to
734 // overwrite 'size' with an all-ones value, which should cause
735 // operator new to throw.
736 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000737 size = CGF.Builder.CreateSelect(hasOverflow,
738 llvm::Constant::getAllOnesValue(CGF.SizeTy),
739 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000740 }
John McCall8ed55a52010-09-02 09:58:18 +0000741
John McCall036f2f62011-05-15 07:14:44 +0000742 if (cookieSize == 0)
743 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000744 else
John McCall036f2f62011-05-15 07:14:44 +0000745 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000746
John McCall036f2f62011-05-15 07:14:44 +0000747 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000748}
749
Sebastian Redlf862eb62012-02-22 17:37:52 +0000750static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
751 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000752 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000753 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000754 switch (CGF.getEvaluationKind(AllocType)) {
755 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000756 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
757 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000758 false);
John McCall47fb9502013-03-07 21:37:08 +0000759 return;
760 case TEK_Complex:
761 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
762 Alignment),
763 /*isInit*/ true);
764 return;
765 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000766 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000767 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000768 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000769 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000770 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000771 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000772 return;
John McCall7a626f62010-09-15 10:14:12 +0000773 }
John McCall47fb9502013-03-07 21:37:08 +0000774 }
775 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000776}
777
778void
Richard Smith06a67e22014-06-03 06:58:52 +0000779CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
780 QualType ElementType,
781 llvm::Value *BeginPtr,
782 llvm::Value *NumElements,
783 llvm::Value *AllocSizeWithoutCookie) {
784 // If we have a type with trivial initialization and no initializer,
785 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000786 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000787 return;
John McCall99210dc2011-09-15 06:49:18 +0000788
Richard Smith06a67e22014-06-03 06:58:52 +0000789 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000790
Richard Smith06a67e22014-06-03 06:58:52 +0000791 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000792
793 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000794 llvm::AllocaInst *EndOfInit = nullptr;
795 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
796 EHScopeStack::stable_iterator Cleanup;
797 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000798
Sebastian Redlf862eb62012-02-22 17:37:52 +0000799 // If the initializer is an initializer list, first do the explicit elements.
800 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000801 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000802
Richard Smith1c96bc52013-12-11 01:40:16 +0000803 // If this is a multi-dimensional array new, we will initialize multiple
804 // elements with each init list element.
805 QualType AllocType = E->getAllocatedType();
806 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
807 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000808 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000809 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000810 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
811 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000812 }
813
Richard Smith06a67e22014-06-03 06:58:52 +0000814 // Enter a partial-destruction Cleanup if necessary.
815 if (needsEHCleanup(DtorKind)) {
816 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000817 // directly, but the control flow can get so varied here that it
818 // would actually be quite complex. Therefore we go through an
819 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000820 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
821 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
822 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
823 getDestroyer(DtorKind));
824 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000825 }
826
Sebastian Redlf862eb62012-02-22 17:37:52 +0000827 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000828 // Tell the cleanup that it needs to destroy up to this
829 // element. TODO: some of these stores can be trivially
830 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000831 if (EndOfInit)
832 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
833 EndOfInit);
834 // FIXME: If the last initializer is an incomplete initializer list for
835 // an array, and we have an array filler, we can fold together the two
836 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000837 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000838 ILE->getInit(i)->getType(), CurPtr);
839 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000840 }
841
842 // The remaining elements are filled with the array filler expression.
843 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000844
Richard Smith06a67e22014-06-03 06:58:52 +0000845 // Extract the initializer for the individual array elements by pulling
846 // out the array filler from all the nested initializer lists. This avoids
847 // generating a nested loop for the initialization.
848 while (Init && Init->getType()->isConstantArrayType()) {
849 auto *SubILE = dyn_cast<InitListExpr>(Init);
850 if (!SubILE)
851 break;
852 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
853 Init = SubILE->getArrayFiller();
854 }
855
856 // Switch back to initializing one base element at a time.
857 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000858 }
859
Richard Smith06a67e22014-06-03 06:58:52 +0000860 // Attempt to perform zero-initialization using memset.
861 auto TryMemsetInitialization = [&]() -> bool {
862 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
863 // we can initialize with a memset to -1.
864 if (!CGM.getTypes().isZeroInitializable(ElementType))
865 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000866
Richard Smith06a67e22014-06-03 06:58:52 +0000867 // Optimization: since zero initialization will just set the memory
868 // to all zeroes, generate a single memset to do it in one shot.
869
870 // Subtract out the size of any elements we've already initialized.
871 auto *RemainingSize = AllocSizeWithoutCookie;
872 if (InitListElements) {
873 // We know this can't overflow; we check this when doing the allocation.
874 auto *InitializedSize = llvm::ConstantInt::get(
875 RemainingSize->getType(),
876 getContext().getTypeSizeInChars(ElementType).getQuantity() *
877 InitListElements);
878 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
879 }
880
881 // Create the memset.
882 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
883 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
884 Alignment.getQuantity(), false);
885 return true;
886 };
887
Richard Smith454a7cd2014-06-03 08:26:00 +0000888 // If all elements have already been initialized, skip any further
889 // initialization.
890 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
891 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
892 // If there was a Cleanup, deactivate it.
893 if (CleanupDominator)
894 DeactivateCleanupBlock(Cleanup, CleanupDominator);
895 return;
896 }
897
898 assert(Init && "have trailing elements to initialize but no initializer");
899
Richard Smith06a67e22014-06-03 06:58:52 +0000900 // If this is a constructor call, try to optimize it out, and failing that
901 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000902 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000903 CXXConstructorDecl *Ctor = CCE->getConstructor();
904 if (Ctor->isTrivial()) {
905 // If new expression did not specify value-initialization, then there
906 // is no initialization.
907 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
908 return;
909
910 if (TryMemsetInitialization())
911 return;
912 }
913
914 // Store the new Cleanup position for irregular Cleanups.
915 //
916 // FIXME: Share this cleanup with the constructor call emission rather than
917 // having it create a cleanup of its own.
918 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
919
920 // Emit a constructor call loop to initialize the remaining elements.
921 if (InitListElements)
922 NumElements = Builder.CreateSub(
923 NumElements,
924 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000925 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000926 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000927 return;
928 }
929
Richard Smith06a67e22014-06-03 06:58:52 +0000930 // If this is value-initialization, we can usually use memset.
931 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000932 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000933 if (TryMemsetInitialization())
934 return;
935
936 // Switch to an ImplicitValueInitExpr for the element type. This handles
937 // only one case: multidimensional array new of pointers to members. In
938 // all other cases, we already have an initializer for the array element.
939 Init = &IVIE;
940 }
941
942 // At this point we should have found an initializer for the individual
943 // elements of the array.
944 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
945 "got wrong type of element to initialize");
946
Richard Smith454a7cd2014-06-03 08:26:00 +0000947 // If we have an empty initializer list, we can usually use memset.
948 if (auto *ILE = dyn_cast<InitListExpr>(Init))
949 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
950 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000951
952 // Create the loop blocks.
953 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
954 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
955 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
956
957 // Find the end of the array, hoisted out of the loop.
958 llvm::Value *EndPtr =
959 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000960
Sebastian Redlf862eb62012-02-22 17:37:52 +0000961 // If the number of elements isn't constant, we have to now check if there is
962 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000963 if (!ConstNum) {
964 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000965 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000966 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000967 }
968
969 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000970 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000971
972 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000973 llvm::PHINode *CurPtrPhi =
974 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
975 CurPtrPhi->addIncoming(CurPtr, EntryBB);
976 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000977
Richard Smith06a67e22014-06-03 06:58:52 +0000978 // Store the new Cleanup position for irregular Cleanups.
979 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000980
Richard Smith06a67e22014-06-03 06:58:52 +0000981 // Enter a partial-destruction Cleanup if necessary.
982 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
983 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
984 getDestroyer(DtorKind));
985 Cleanup = EHStack.stable_begin();
986 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000987 }
988
989 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000990 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +0000991
Richard Smith06a67e22014-06-03 06:58:52 +0000992 // Leave the Cleanup if we entered one.
993 if (CleanupDominator) {
994 DeactivateCleanupBlock(Cleanup, CleanupDominator);
995 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +0000996 }
John McCall99210dc2011-09-15 06:49:18 +0000997
Faisal Vali57ae0562013-12-14 00:40:05 +0000998 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000999 llvm::Value *NextPtr =
1000 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
1001
John McCall99210dc2011-09-15 06:49:18 +00001002 // Check whether we've gotten to the end of the array and, if so,
1003 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001004 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1005 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1006 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001007
Richard Smith06a67e22014-06-03 06:58:52 +00001008 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001009}
1010
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001011static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +00001012 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001013 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001014 llvm::Value *NumElements,
1015 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +00001016 if (E->isArray())
1017 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
1018 AllocSizeWithoutCookie);
1019 else if (const Expr *Init = E->getInitializer())
1020 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001021}
1022
Richard Smith8d0dc312013-07-21 23:12:18 +00001023/// Emit a call to an operator new or operator delete function, as implicitly
1024/// created by new-expressions and delete-expressions.
1025static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1026 const FunctionDecl *Callee,
1027 const FunctionProtoType *CalleeType,
1028 const CallArgList &Args) {
1029 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001030 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001031 RValue RV =
1032 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +00001033 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +00001034 Callee, &CallOrInvoke);
1035
1036 /// C++1y [expr.new]p10:
1037 /// [In a new-expression,] an implementation is allowed to omit a call
1038 /// to a replaceable global allocation function.
1039 ///
1040 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001041 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001042 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001043 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001044 // FIXME: Add addAttribute to CallSite.
1045 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1046 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1047 llvm::Attribute::Builtin);
1048 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1049 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1050 llvm::Attribute::Builtin);
1051 else
1052 llvm_unreachable("unexpected kind of call instruction");
1053 }
1054
1055 return RV;
1056}
1057
Richard Smith760520b2014-06-03 23:27:44 +00001058RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1059 const Expr *Arg,
1060 bool IsDelete) {
1061 CallArgList Args;
1062 const Stmt *ArgS = Arg;
1063 EmitCallArgs(Args, *Type->param_type_begin(),
1064 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1065 // Find the allocation or deallocation function that we're calling.
1066 ASTContext &Ctx = getContext();
1067 DeclarationName Name = Ctx.DeclarationNames
1068 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1069 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001070 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1071 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1072 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001073 llvm_unreachable("predeclared global operator new/delete is missing");
1074}
1075
John McCall824c2f52010-09-14 07:57:04 +00001076namespace {
1077 /// A cleanup to call the given 'operator delete' function upon
1078 /// abnormal exit from a new expression.
1079 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1080 size_t NumPlacementArgs;
1081 const FunctionDecl *OperatorDelete;
1082 llvm::Value *Ptr;
1083 llvm::Value *AllocSize;
1084
1085 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1086
1087 public:
1088 static size_t getExtraSize(size_t NumPlacementArgs) {
1089 return NumPlacementArgs * sizeof(RValue);
1090 }
1091
1092 CallDeleteDuringNew(size_t NumPlacementArgs,
1093 const FunctionDecl *OperatorDelete,
1094 llvm::Value *Ptr,
1095 llvm::Value *AllocSize)
1096 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1097 Ptr(Ptr), AllocSize(AllocSize) {}
1098
1099 void setPlacementArg(unsigned I, RValue Arg) {
1100 assert(I < NumPlacementArgs && "index out of range");
1101 getPlacementArgs()[I] = Arg;
1102 }
1103
Craig Topper4f12f102014-03-12 06:41:41 +00001104 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001105 const FunctionProtoType *FPT
1106 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001107 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1108 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001109
1110 CallArgList DeleteArgs;
1111
1112 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001113 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001114 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001115
1116 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001117 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001118 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001119
1120 // Pass the rest of the arguments, which must match exactly.
1121 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001122 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001123
1124 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001125 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001126 }
1127 };
John McCall7f9c92a2010-09-17 00:50:28 +00001128
1129 /// A cleanup to call the given 'operator delete' function upon
1130 /// abnormal exit from a new expression when the new expression is
1131 /// conditional.
1132 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1133 size_t NumPlacementArgs;
1134 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001135 DominatingValue<RValue>::saved_type Ptr;
1136 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001137
John McCallcb5f77f2011-01-28 10:53:53 +00001138 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1139 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001140 }
1141
1142 public:
1143 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001144 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001145 }
1146
1147 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1148 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001149 DominatingValue<RValue>::saved_type Ptr,
1150 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001151 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1152 Ptr(Ptr), AllocSize(AllocSize) {}
1153
John McCallcb5f77f2011-01-28 10:53:53 +00001154 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001155 assert(I < NumPlacementArgs && "index out of range");
1156 getPlacementArgs()[I] = Arg;
1157 }
1158
Craig Topper4f12f102014-03-12 06:41:41 +00001159 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001160 const FunctionProtoType *FPT
1161 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001162 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1163 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001164
1165 CallArgList DeleteArgs;
1166
1167 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001168 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001169 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001170
1171 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001172 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001173 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001174 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001175 }
1176
1177 // Pass the rest of the arguments, which must match exactly.
1178 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001179 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001180 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001181 }
1182
1183 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001184 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001185 }
1186 };
1187}
1188
1189/// Enter a cleanup to call 'operator delete' if the initializer in a
1190/// new-expression throws.
1191static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1192 const CXXNewExpr *E,
1193 llvm::Value *NewPtr,
1194 llvm::Value *AllocSize,
1195 const CallArgList &NewArgs) {
1196 // If we're not inside a conditional branch, then the cleanup will
1197 // dominate and we can do the easier (and more efficient) thing.
1198 if (!CGF.isInConditionalBranch()) {
1199 CallDeleteDuringNew *Cleanup = CGF.EHStack
1200 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1201 E->getNumPlacementArgs(),
1202 E->getOperatorDelete(),
1203 NewPtr, AllocSize);
1204 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001205 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001206
1207 return;
1208 }
1209
1210 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001211 DominatingValue<RValue>::saved_type SavedNewPtr =
1212 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1213 DominatingValue<RValue>::saved_type SavedAllocSize =
1214 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001215
1216 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001217 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001218 E->getNumPlacementArgs(),
1219 E->getOperatorDelete(),
1220 SavedNewPtr,
1221 SavedAllocSize);
1222 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001223 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001224 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001225
John McCallf4beacd2011-11-10 10:43:54 +00001226 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001227}
1228
Anders Carlssoncc52f652009-09-22 22:53:17 +00001229llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001230 // The element type being allocated.
1231 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001232
John McCall75f94982011-03-07 03:12:35 +00001233 // 1. Build a call to the allocation function.
1234 FunctionDecl *allocator = E->getOperatorNew();
1235 const FunctionProtoType *allocatorType =
1236 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001237
John McCall75f94982011-03-07 03:12:35 +00001238 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001239
1240 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001241 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001242
Sebastian Redlf862eb62012-02-22 17:37:52 +00001243 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1244 unsigned minElements = 0;
1245 if (E->isArray() && E->hasInitializer()) {
1246 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1247 minElements = ILE->getNumInits();
1248 }
1249
Craig Topper8a13c412014-05-21 05:09:00 +00001250 llvm::Value *numElements = nullptr;
1251 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001252 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001253 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1254 allocSizeWithoutCookie);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001255
Eli Friedman43dca6a2011-05-02 17:57:46 +00001256 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001257
Anders Carlssoncc52f652009-09-22 22:53:17 +00001258 // We start at 1 here because the first argument (the allocation size)
1259 // has already been emitted.
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001260 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001261 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1262 /*ParamsToSkip*/ 1);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001263
John McCall7ec4b432011-05-16 01:05:12 +00001264 // Emit the allocation call. If the allocator is a global placement
1265 // operator, just "inline" it directly.
1266 RValue RV;
1267 if (allocator->isReservedGlobalPlacementOperator()) {
1268 assert(allocatorArgs.size() == 2);
1269 RV = allocatorArgs[1].RV;
1270 // TODO: kill any unnecessary computations done for the size
1271 // argument.
1272 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001273 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001274 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001275
John McCall75f94982011-03-07 03:12:35 +00001276 // Emit a null check on the allocation result if the allocation
1277 // function is allowed to return null (because it has a non-throwing
1278 // exception spec; for this part, we inline
1279 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1280 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001281 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001282 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001283
Craig Topper8a13c412014-05-21 05:09:00 +00001284 llvm::BasicBlock *nullCheckBB = nullptr;
1285 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001286
John McCall75f94982011-03-07 03:12:35 +00001287 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001288 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001289
John McCallf7dcf322011-03-07 01:52:56 +00001290 // The null-check means that the initializer is conditionally
1291 // evaluated.
1292 ConditionalEvaluation conditional(*this);
1293
John McCall75f94982011-03-07 03:12:35 +00001294 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001295 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001296
1297 nullCheckBB = Builder.GetInsertBlock();
1298 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1299 contBB = createBasicBlock("new.cont");
1300
1301 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1302 Builder.CreateCondBr(isNull, contBB, notNullBB);
1303 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001304 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001305
John McCall824c2f52010-09-14 07:57:04 +00001306 // If there's an operator delete, enter a cleanup to call it if an
1307 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001308 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001309 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001310 if (E->getOperatorDelete() &&
1311 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001312 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1313 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001314 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001315 }
1316
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001317 assert((allocSize == allocSizeWithoutCookie) ==
1318 CalculateCookiePadding(*this, E).isZero());
1319 if (allocSize != allocSizeWithoutCookie) {
1320 assert(E->isArray());
1321 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1322 numElements,
1323 E, allocType);
1324 }
1325
Chris Lattner2192fe52011-07-18 04:24:23 +00001326 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001327 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1328 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001329
John McCall99210dc2011-09-15 06:49:18 +00001330 EmitNewInitializer(*this, E, allocType, result, numElements,
1331 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001332 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001333 // NewPtr is a pointer to the base element type. If we're
1334 // allocating an array of arrays, we'll need to cast back to the
1335 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001336 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001337 if (result->getType() != resultType)
1338 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001339 }
John McCall824c2f52010-09-14 07:57:04 +00001340
1341 // Deactivate the 'operator delete' cleanup if we finished
1342 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001343 if (operatorDeleteCleanup.isValid()) {
1344 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1345 cleanupDominator->eraseFromParent();
1346 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001347
John McCall75f94982011-03-07 03:12:35 +00001348 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001349 conditional.end(*this);
1350
John McCall75f94982011-03-07 03:12:35 +00001351 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1352 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001353
Jay Foad20c0f022011-03-30 11:28:58 +00001354 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001355 PHI->addIncoming(result, notNullBB);
1356 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1357 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001358
John McCall75f94982011-03-07 03:12:35 +00001359 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001360 }
John McCall8ed55a52010-09-02 09:58:18 +00001361
John McCall75f94982011-03-07 03:12:35 +00001362 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001363}
1364
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001365void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1366 llvm::Value *Ptr,
1367 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001368 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1369
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001370 const FunctionProtoType *DeleteFTy =
1371 DeleteFD->getType()->getAs<FunctionProtoType>();
1372
1373 CallArgList DeleteArgs;
1374
Anders Carlsson21122cf2009-12-13 20:04:38 +00001375 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001376 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001377 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001378 if (DeleteFTy->getNumParams() == 2) {
1379 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001380 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1381 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1382 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001383 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001384
1385 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001386 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001387 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001388
Anders Carlsson21122cf2009-12-13 20:04:38 +00001389 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001390 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001391
1392 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001393 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001394}
1395
John McCall8ed55a52010-09-02 09:58:18 +00001396namespace {
1397 /// Calls the given 'operator delete' on a single object.
1398 struct CallObjectDelete : EHScopeStack::Cleanup {
1399 llvm::Value *Ptr;
1400 const FunctionDecl *OperatorDelete;
1401 QualType ElementType;
1402
1403 CallObjectDelete(llvm::Value *Ptr,
1404 const FunctionDecl *OperatorDelete,
1405 QualType ElementType)
1406 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1407
Craig Topper4f12f102014-03-12 06:41:41 +00001408 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001409 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1410 }
1411 };
1412}
1413
David Majnemer0c0b6d92014-10-31 20:09:12 +00001414void
1415CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1416 llvm::Value *CompletePtr,
1417 QualType ElementType) {
1418 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1419 OperatorDelete, ElementType);
1420}
1421
John McCall8ed55a52010-09-02 09:58:18 +00001422/// Emit the code for deleting a single object.
1423static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001424 const CXXDeleteExpr *DE,
John McCall8ed55a52010-09-02 09:58:18 +00001425 llvm::Value *Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001426 QualType ElementType) {
John McCall8ed55a52010-09-02 09:58:18 +00001427 // Find the destructor for the type, if applicable. If the
1428 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001429 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001430 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1431 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001432 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001433 Dtor = RD->getDestructor();
1434
1435 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001436 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1437 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001438 return;
1439 }
1440 }
1441 }
1442
1443 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001444 // This doesn't have to a conditional cleanup because we're going
1445 // to pop it off in a second.
David Majnemer08681372014-11-01 07:37:17 +00001446 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001447 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1448 Ptr, OperatorDelete, ElementType);
1449
1450 if (Dtor)
1451 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001452 /*ForVirtualBase=*/false,
1453 /*Delegating=*/false,
1454 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001455 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001456 ElementType->isObjCLifetimeType()) {
1457 switch (ElementType.getObjCLifetime()) {
1458 case Qualifiers::OCL_None:
1459 case Qualifiers::OCL_ExplicitNone:
1460 case Qualifiers::OCL_Autoreleasing:
1461 break;
John McCall8ed55a52010-09-02 09:58:18 +00001462
John McCall31168b02011-06-15 23:02:42 +00001463 case Qualifiers::OCL_Strong: {
1464 // Load the pointer value.
1465 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1466 ElementType.isVolatileQualified());
1467
John McCallcdda29c2013-03-13 03:10:54 +00001468 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001469 break;
1470 }
1471
1472 case Qualifiers::OCL_Weak:
1473 CGF.EmitARCDestroyWeak(Ptr);
1474 break;
1475 }
1476 }
1477
John McCall8ed55a52010-09-02 09:58:18 +00001478 CGF.PopCleanupBlock();
1479}
1480
1481namespace {
1482 /// Calls the given 'operator delete' on an array of objects.
1483 struct CallArrayDelete : EHScopeStack::Cleanup {
1484 llvm::Value *Ptr;
1485 const FunctionDecl *OperatorDelete;
1486 llvm::Value *NumElements;
1487 QualType ElementType;
1488 CharUnits CookieSize;
1489
1490 CallArrayDelete(llvm::Value *Ptr,
1491 const FunctionDecl *OperatorDelete,
1492 llvm::Value *NumElements,
1493 QualType ElementType,
1494 CharUnits CookieSize)
1495 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1496 ElementType(ElementType), CookieSize(CookieSize) {}
1497
Craig Topper4f12f102014-03-12 06:41:41 +00001498 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001499 const FunctionProtoType *DeleteFTy =
1500 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001501 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001502
1503 CallArgList Args;
1504
1505 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001506 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001507 llvm::Value *DeletePtr
1508 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001509 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001510
1511 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001512 if (DeleteFTy->getNumParams() == 2) {
1513 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001514 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001515 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1516
1517 CharUnits ElementTypeSize =
1518 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1519
1520 // The size of an element, multiplied by the number of elements.
1521 llvm::Value *Size
1522 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1523 Size = CGF.Builder.CreateMul(Size, NumElements);
1524
1525 // Plus the size of the cookie if applicable.
1526 if (!CookieSize.isZero()) {
1527 llvm::Value *CookieSizeV
1528 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1529 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1530 }
1531
Eli Friedman43dca6a2011-05-02 17:57:46 +00001532 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001533 }
1534
1535 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001536 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001537 }
1538 };
1539}
1540
1541/// Emit the code for deleting an array of objects.
1542static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001543 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001544 llvm::Value *deletedPtr,
1545 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001546 llvm::Value *numElements = nullptr;
1547 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001548 CharUnits cookieSize;
1549 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1550 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001551
John McCallca2c56f2011-07-13 01:41:37 +00001552 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001553
1554 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001555 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001556 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001557 allocatedPtr, operatorDelete,
1558 numElements, elementType,
1559 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001560
John McCallca2c56f2011-07-13 01:41:37 +00001561 // Destroy the elements.
1562 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1563 assert(numElements && "no element count for a type with a destructor!");
1564
John McCallca2c56f2011-07-13 01:41:37 +00001565 llvm::Value *arrayEnd =
1566 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001567
1568 // Note that it is legal to allocate a zero-length array, and we
1569 // can never fold the check away because the length should always
1570 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001571 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1572 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001573 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001574 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001575 }
1576
John McCallca2c56f2011-07-13 01:41:37 +00001577 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001578 CGF.PopCleanupBlock();
1579}
1580
Anders Carlssoncc52f652009-09-22 22:53:17 +00001581void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001582 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001583 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001584
1585 // Null check the pointer.
1586 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1587 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1588
Anders Carlsson98981b12011-04-11 00:30:07 +00001589 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001590
1591 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1592 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001593
John McCall8ed55a52010-09-02 09:58:18 +00001594 // We might be deleting a pointer to array. If so, GEP down to the
1595 // first non-array element.
1596 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1597 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1598 if (DeleteTy->isConstantArrayType()) {
1599 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001600 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001601
1602 GEP.push_back(Zero); // point at the outermost array
1603
1604 // For each layer of array type we're pointing at:
1605 while (const ConstantArrayType *Arr
1606 = getContext().getAsConstantArrayType(DeleteTy)) {
1607 // 1. Unpeel the array type.
1608 DeleteTy = Arr->getElementType();
1609
1610 // 2. GEP to the first element of the array.
1611 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001612 }
John McCall8ed55a52010-09-02 09:58:18 +00001613
Jay Foad040dd822011-07-22 08:16:57 +00001614 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001615 }
1616
Douglas Gregor04f36212010-09-02 17:38:50 +00001617 assert(ConvertTypeForMem(DeleteTy) ==
1618 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001619
1620 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001621 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001622 } else {
David Majnemer08681372014-11-01 07:37:17 +00001623 EmitObjectDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001624 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001625
Anders Carlssoncc52f652009-09-22 22:53:17 +00001626 EmitBlock(DeleteEnd);
1627}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001628
David Majnemer1c3d95e2014-07-19 00:17:06 +00001629static bool isGLValueFromPointerDeref(const Expr *E) {
1630 E = E->IgnoreParens();
1631
1632 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1633 if (!CE->getSubExpr()->isGLValue())
1634 return false;
1635 return isGLValueFromPointerDeref(CE->getSubExpr());
1636 }
1637
1638 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1639 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1640
1641 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1642 if (BO->getOpcode() == BO_Comma)
1643 return isGLValueFromPointerDeref(BO->getRHS());
1644
1645 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1646 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1647 isGLValueFromPointerDeref(ACO->getFalseExpr());
1648
1649 // C++11 [expr.sub]p1:
1650 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1651 if (isa<ArraySubscriptExpr>(E))
1652 return true;
1653
1654 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1655 if (UO->getOpcode() == UO_Deref)
1656 return true;
1657
1658 return false;
1659}
1660
Warren Hunt747e3012014-06-18 21:15:55 +00001661static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001662 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001663 // Get the vtable pointer.
1664 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1665
1666 // C++ [expr.typeid]p2:
1667 // If the glvalue expression is obtained by applying the unary * operator to
1668 // a pointer and the pointer is a null pointer value, the typeid expression
1669 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001670 //
1671 // However, this paragraph's intent is not clear. We choose a very generous
1672 // interpretation which implores us to consider comma operators, conditional
1673 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001674 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001675 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1676 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001677 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001678 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001679 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001680
David Majnemer1162d252014-06-22 19:05:33 +00001681 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1682 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001683
David Majnemer1162d252014-06-22 19:05:33 +00001684 CGF.EmitBlock(BadTypeidBlock);
1685 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1686 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001687 }
1688
David Majnemer1162d252014-06-22 19:05:33 +00001689 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1690 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001691}
1692
John McCalle4df6c82011-01-28 08:37:24 +00001693llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001694 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001695 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001696
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001697 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001698 llvm::Constant *TypeInfo =
1699 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001700 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001701 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001702
Anders Carlsson940f02d2011-04-18 00:57:03 +00001703 // C++ [expr.typeid]p2:
1704 // When typeid is applied to a glvalue expression whose type is a
1705 // polymorphic class type, the result refers to a std::type_info object
1706 // representing the type of the most derived object (that is, the dynamic
1707 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001708 if (E->isPotentiallyEvaluated())
1709 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1710 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001711
1712 QualType OperandTy = E->getExprOperand()->getType();
1713 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1714 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001715}
Mike Stump65511702009-11-16 06:50:58 +00001716
Anders Carlssonc1c99712011-04-11 01:45:29 +00001717static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1718 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001719 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001720 if (DestTy->isPointerType())
1721 return llvm::Constant::getNullValue(DestLTy);
1722
1723 /// C++ [expr.dynamic.cast]p9:
1724 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001725 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1726 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001727
1728 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1729 return llvm::UndefValue::get(DestLTy);
1730}
1731
Anders Carlsson882d7902011-04-11 00:46:40 +00001732llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001733 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001734 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001735
Anders Carlssonc1c99712011-04-11 01:45:29 +00001736 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001737 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1738 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001739
1740 QualType SrcTy = DCE->getSubExpr()->getType();
1741
David Majnemer1162d252014-06-22 19:05:33 +00001742 // C++ [expr.dynamic.cast]p7:
1743 // If T is "pointer to cv void," then the result is a pointer to the most
1744 // derived object pointed to by v.
1745 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1746
1747 bool isDynamicCastToVoid;
1748 QualType SrcRecordTy;
1749 QualType DestRecordTy;
1750 if (DestPTy) {
1751 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1752 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1753 DestRecordTy = DestPTy->getPointeeType();
1754 } else {
1755 isDynamicCastToVoid = false;
1756 SrcRecordTy = SrcTy;
1757 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1758 }
1759
1760 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1761
Anders Carlsson882d7902011-04-11 00:46:40 +00001762 // C++ [expr.dynamic.cast]p4:
1763 // If the value of v is a null pointer value in the pointer case, the result
1764 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001765 bool ShouldNullCheckSrcValue =
1766 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1767 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001768
1769 llvm::BasicBlock *CastNull = nullptr;
1770 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001771 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001772
Anders Carlsson882d7902011-04-11 00:46:40 +00001773 if (ShouldNullCheckSrcValue) {
1774 CastNull = createBasicBlock("dynamic_cast.null");
1775 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1776
1777 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1778 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1779 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001780 }
1781
David Majnemer1162d252014-06-22 19:05:33 +00001782 if (isDynamicCastToVoid) {
1783 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1784 DestTy);
1785 } else {
1786 assert(DestRecordTy->isRecordType() &&
1787 "destination type must be a record type!");
1788 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1789 DestTy, DestRecordTy, CastEnd);
1790 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001791
1792 if (ShouldNullCheckSrcValue) {
1793 EmitBranch(CastEnd);
1794
1795 EmitBlock(CastNull);
1796 EmitBranch(CastEnd);
1797 }
1798
1799 EmitBlock(CastEnd);
1800
1801 if (ShouldNullCheckSrcValue) {
1802 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1803 PHI->addIncoming(Value, CastNotNull);
1804 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1805
1806 Value = PHI;
1807 }
1808
1809 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001810}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001811
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001812void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001813 RunCleanupsScope Scope(*this);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001814 LValue SlotLV =
1815 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001816
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001817 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1818 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1819 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001820 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001821 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00001822 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001823 if (CurField->hasCapturedVLAType()) {
1824 auto VAT = CurField->getCapturedVLAType();
1825 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1826 } else {
1827 ArrayRef<VarDecl *> ArrayIndexes;
1828 if (CurField->getType()->isArrayType())
1829 ArrayIndexes = E->getCaptureInitIndexVars(i);
1830 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1831 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001832 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001833}