blob: 371f44fcc95f18a25d850b38d146833b87c246fc [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
David Majnemer0c0b6d92014-10-31 20:09:12 +000027static RequiredArgs commonEmitCXXMemberOrOperatorCall(
28 CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
29 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000031 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson27da15b2010-01-01 20:29:01 +000035
Richard Smith69d0d262012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
David Majnemer0c0b6d92014-10-31 20:09:12 +000042 CGF.EmitTypeCheck(
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000046
47 // Push the this ptr.
David Majnemer0c0b6d92014-10-31 20:09:12 +000048 Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000049
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000050 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000053 }
John McCalla729c622012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000057
John McCalla729c622012-02-17 03:33:10 +000058 // And the rest of the call args.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000059 if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000060 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000061 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Majnemer0c0b6d92014-10-31 20:09:12 +000062 CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
63 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000064 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000065 assert(
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000068 }
David Majnemer0c0b6d92014-10-31 20:09:12 +000069 return required;
70}
Anders Carlsson27da15b2010-01-01 20:29:01 +000071
David Majnemer0c0b6d92014-10-31 20:09:12 +000072RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
73 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
75 const CallExpr *CE) {
76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77 CallArgList Args;
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79 *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
80 Args);
John McCall8dda7b22012-07-07 06:41:13 +000081 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000082 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000083}
84
David Majnemer0c0b6d92014-10-31 20:09:12 +000085RValue CodeGenFunction::EmitCXXStructorCall(
86 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
87 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
88 const CallExpr *CE, StructorType Type) {
89 CallArgList Args;
90 commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
91 ImplicitParam, ImplicitParamTy, CE, Args);
92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
93 Callee, ReturnValue, Args, MD);
94}
95
Rafael Espindola3b33c4e2012-06-28 14:28:57 +000096static CXXRecordDecl *getCXXRecord(const Expr *E) {
97 QualType T = E->getType();
98 if (const PointerType *PTy = T->getAs<PointerType>())
99 T = PTy->getPointeeType();
100 const RecordType *Ty = T->castAs<RecordType>();
101 return cast<CXXRecordDecl>(Ty->getDecl());
102}
103
Francois Pichet64225792011-01-18 05:04:39 +0000104// Note: This function also emit constructor calls to support a MSVC
105// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000106RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000108 const Expr *callee = CE->getCallee()->IgnoreParens();
109
110 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000112
113 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
115
116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
120 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000121 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000122
Nico Weberaad4af62014-12-03 01:21:41 +0000123 bool HasQualifier = ME->hasQualifier();
124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000126 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000127
128 return EmitCXXMemberOrOperatorMemberCallExpr(
129 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
130}
131
132RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
133 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
134 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
135 const Expr *Base) {
136 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
137
138 // Compute the object pointer.
139 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000140
Craig Topper8a13c412014-05-21 05:09:00 +0000141 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000143 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
144 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
145 assert(DevirtualizedMethod);
146 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
147 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000148 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
149 MD->getReturnType().getCanonicalType())
150 // If the return types are not the same, this might be a case where more
151 // code needs to run to compensate for it. For example, the derived
152 // method might return a type that inherits form from the return
153 // type of MD and has a prefix.
154 // For now we just avoid devirtualizing these covariant cases.
155 DevirtualizedMethod = nullptr;
156 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000157 // If the class of the Inner expression is where the dynamic method
158 // is defined, build the this pointer from it.
159 Base = Inner;
160 else if (getCXXRecord(Base) != DevirtualizedClass) {
161 // If the method is defined in a class that is not the best dynamic
162 // one or the one of the full expression, we would have to build
163 // a derived-to-base cast to compute the correct this pointer, but
164 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000165 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000166 }
167 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000168
Anders Carlsson27da15b2010-01-01 20:29:01 +0000169 llvm::Value *This;
Nico Weberaad4af62014-12-03 01:21:41 +0000170 if (IsArrow)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000171 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000172 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000173 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000174
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175
Richard Smith419bd092015-04-29 19:26:57 +0000176 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
Craig Topper8a13c412014-05-21 05:09:00 +0000177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000178 if (isa<CXXConstructorDecl>(MD) &&
179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000180 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000181
Nico Weberaad4af62014-12-03 01:21:41 +0000182 if (!MD->getParent()->mayInsertExtraPadding()) {
183 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
184 // We don't like to generate the trivial copy/move assignment operator
185 // when it isn't necessary; just produce the proper effect here.
186 // Special case: skip first argument of CXXOperatorCall (it is "this").
187 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
188 llvm::Value *RHS =
189 EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
190 EmitAggregateAssign(This, RHS, CE->getType());
191 return RValue::get(This);
192 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000193
Nico Weberaad4af62014-12-03 01:21:41 +0000194 if (isa<CXXConstructorDecl>(MD) &&
195 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
196 // Trivial move and copy ctor are the same.
197 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
198 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
199 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
200 return RValue::get(This);
201 }
202 llvm_unreachable("unknown trivial member function");
Francois Pichet64225792011-01-18 05:04:39 +0000203 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000204 }
205
John McCall0d635f52010-09-03 01:26:39 +0000206 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000207 const CXXMethodDecl *CalleeDecl =
208 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000209 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000210 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000211 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
212 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000213 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000214 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
215 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000216 else
Eli Friedmanade60972012-10-25 00:12:49 +0000217 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000218
Reid Klecknere7de47e2013-07-22 13:51:44 +0000219 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000220
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 // C++ [class.virtual]p12:
222 // Explicit qualification with the scope operator (5.1) suppresses the
223 // virtual call mechanism.
224 //
225 // We also don't emit a virtual call if the base expression has a record type
226 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000227 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000228 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000229
John McCall0d635f52010-09-03 01:26:39 +0000230 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000231 assert(CE->arg_begin() == CE->arg_end() &&
232 "Destructor shouldn't have explicit parameters");
233 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000234 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000235 CGM.getCXXABI().EmitVirtualDestructorCall(
236 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000237 } else {
Nico Weberaad4af62014-12-03 01:21:41 +0000238 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
239 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000240 else if (!DevirtualizedMethod)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000241 Callee =
242 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000243 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000244 const CXXDestructorDecl *DDtor =
245 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000246 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
247 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000248 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
249 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000250 }
Craig Topper8a13c412014-05-21 05:09:00 +0000251 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000252 }
253
254 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000255 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000256 } else if (UseVirtualCall) {
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000257 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
258 CE->getLocStart());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000259 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000260 if (SanOpts.has(SanitizerKind::CFINVCall) &&
261 MD->getParent()->isDynamicClass()) {
262 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000263 EmitVTablePtrCheckForCall(MD, VTable, CFITCK_NVCall, CE->getLocStart());
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000264 }
265
Nico Weberaad4af62014-12-03 01:21:41 +0000266 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
267 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000268 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000269 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000270 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000271 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000272 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000273 }
274
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000275 if (MD->isVirtual()) {
276 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
277 *this, MD, This, UseVirtualCall);
278 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000279
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000280 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
281 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000282}
283
284RValue
285CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
286 ReturnValueSlot ReturnValue) {
287 const BinaryOperator *BO =
288 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
289 const Expr *BaseExpr = BO->getLHS();
290 const Expr *MemFnExpr = BO->getRHS();
291
292 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000293 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000294
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000296 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000297 const CXXRecordDecl *RD =
298 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
299
Anders Carlsson27da15b2010-01-01 20:29:01 +0000300 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000301 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000302
303 // Emit the 'this' pointer.
304 llvm::Value *This;
305
John McCalle3027922010-08-25 11:45:40 +0000306 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000307 This = EmitScalarExpr(BaseExpr);
308 else
309 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000310
Richard Smithe30752c2012-10-09 19:52:38 +0000311 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
312 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000313
John McCall475999d2010-08-22 00:05:51 +0000314 // Ask the ABI to load the callee. Note that This is modified.
315 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000316 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000317
Anders Carlsson27da15b2010-01-01 20:29:01 +0000318 CallArgList Args;
319
320 QualType ThisType =
321 getContext().getPointerType(getContext().getTagDeclType(RD));
322
323 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000324 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000325
326 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000327
328 // And the rest of the call args
Alexey Samsonov8e1162c2014-09-08 17:22:45 +0000329 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000330 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
331 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000332}
333
334RValue
335CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
336 const CXXMethodDecl *MD,
337 ReturnValueSlot ReturnValue) {
338 assert(MD->isInstance() &&
339 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000340 return EmitCXXMemberOrOperatorMemberCallExpr(
341 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
342 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000343}
344
Peter Collingbournefe883422011-10-06 18:29:37 +0000345RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
346 ReturnValueSlot ReturnValue) {
347 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
348}
349
Eli Friedmanfde961d2011-10-14 02:27:24 +0000350static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
351 llvm::Value *DestPtr,
352 const CXXRecordDecl *Base) {
353 if (Base->isEmpty())
354 return;
355
356 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
357
358 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
359 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000360 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000361
362 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
363
364 // If the type contains a pointer to data member we can't memset it to zero.
365 // Instead, create a null constant and copy it to the destination.
366 // TODO: there are other patterns besides zero that we can usefully memset,
367 // like -1, which happens to be the pattern used by member-pointers.
368 // TODO: isZeroInitializable can be over-conservative in the case where a
369 // virtual base contains a member pointer.
370 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
371 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
372
373 llvm::GlobalVariable *NullVariable =
374 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
375 /*isConstant=*/true,
376 llvm::GlobalVariable::PrivateLinkage,
377 NullConstant, Twine());
378 NullVariable->setAlignment(Align.getQuantity());
379 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
380
381 // Get and call the appropriate llvm.memcpy overload.
382 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
383 return;
384 }
385
386 // Otherwise, just memset the whole thing to zero. This is legal
387 // because in LLVM, all default initializers (other than the ones we just
388 // handled above) are guaranteed to have a bit pattern of all zeros.
389 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
390 Align.getQuantity());
391}
392
Anders Carlsson27da15b2010-01-01 20:29:01 +0000393void
John McCall7a626f62010-09-15 10:14:12 +0000394CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
395 AggValueSlot Dest) {
396 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000397 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000398
399 // If we require zero initialization before (or instead of) calling the
400 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000401 // constructor, emit the zero initialization now, unless destination is
402 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000403 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
404 switch (E->getConstructionKind()) {
405 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000406 case CXXConstructExpr::CK_Complete:
407 EmitNullInitialization(Dest.getAddr(), E->getType());
408 break;
409 case CXXConstructExpr::CK_VirtualBase:
410 case CXXConstructExpr::CK_NonVirtualBase:
411 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
412 break;
413 }
414 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000415
416 // If this is a call to a trivial default constructor, do nothing.
417 if (CD->isTrivial() && CD->isDefaultConstructor())
418 return;
419
John McCall8ea46b62010-09-18 00:58:34 +0000420 // Elide the constructor if we're constructing from a temporary.
421 // The temporary check is required because Sema sets this on NRVO
422 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000423 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000424 assert(getContext().hasSameUnqualifiedType(E->getType(),
425 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000426 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
427 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000428 return;
429 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000430 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000431
John McCallf677a8e2011-07-13 06:10:41 +0000432 if (const ConstantArrayType *arrayType
433 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000434 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000435 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000436 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000437 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000438 bool Delegating = false;
439
Alexis Hunt271c3682011-05-03 20:19:28 +0000440 switch (E->getConstructionKind()) {
441 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000442 // We should be emitting a constructor; GlobalDecl will assert this
443 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000444 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000445 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000446
Alexis Hunt271c3682011-05-03 20:19:28 +0000447 case CXXConstructExpr::CK_Complete:
448 Type = Ctor_Complete;
449 break;
450
451 case CXXConstructExpr::CK_VirtualBase:
452 ForVirtualBase = true;
453 // fall-through
454
455 case CXXConstructExpr::CK_NonVirtualBase:
456 Type = Ctor_Base;
457 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000458
Anders Carlsson27da15b2010-01-01 20:29:01 +0000459 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000460 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000461 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000462 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000463}
464
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000465void
466CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
467 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000468 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000469 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000470 Exp = E->getSubExpr();
471 assert(isa<CXXConstructExpr>(Exp) &&
472 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
473 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
474 const CXXConstructorDecl *CD = E->getConstructor();
475 RunCleanupsScope Scope(*this);
476
477 // If we require zero initialization before (or instead of) calling the
478 // constructor, as can be the case with a non-user-provided default
479 // constructor, emit the zero initialization now.
480 // FIXME. Do I still need this for a copy ctor synthesis?
481 if (E->requiresZeroInitialization())
482 EmitNullInitialization(Dest, E->getType());
483
Chandler Carruth99da11c2010-11-15 13:54:43 +0000484 assert(!getContext().getAsConstantArrayType(E->getType())
485 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000486 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000487}
488
John McCall8ed55a52010-09-02 09:58:18 +0000489static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
490 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000491 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000492 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000493
John McCall7ec4b432011-05-16 01:05:12 +0000494 // No cookie is required if the operator new[] being used is the
495 // reserved placement operator new[].
496 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000497 return CharUnits::Zero();
498
John McCall284c48f2011-01-27 09:37:56 +0000499 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000500}
501
John McCall036f2f62011-05-15 07:14:44 +0000502static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
503 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000504 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000505 llvm::Value *&numElements,
506 llvm::Value *&sizeWithoutCookie) {
507 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000508
John McCall036f2f62011-05-15 07:14:44 +0000509 if (!e->isArray()) {
510 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
511 sizeWithoutCookie
512 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
513 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000514 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000515
John McCall036f2f62011-05-15 07:14:44 +0000516 // The width of size_t.
517 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
518
John McCall8ed55a52010-09-02 09:58:18 +0000519 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000520 llvm::APInt cookieSize(sizeWidth,
521 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000522
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000523 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000524 // We multiply the size of all dimensions for NumElements.
525 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000526 numElements = CGF.EmitScalarExpr(e->getArraySize());
527 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000528
John McCall036f2f62011-05-15 07:14:44 +0000529 // The number of elements can be have an arbitrary integer type;
530 // essentially, we need to multiply it by a constant factor, add a
531 // cookie size, and verify that the result is representable as a
532 // size_t. That's just a gloss, though, and it's wrong in one
533 // important way: if the count is negative, it's an error even if
534 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000535 bool isSigned
536 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000537 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000538 = cast<llvm::IntegerType>(numElements->getType());
539 unsigned numElementsWidth = numElementsType->getBitWidth();
540
541 // Compute the constant factor.
542 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000543 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000544 = CGF.getContext().getAsConstantArrayType(type)) {
545 type = CAT->getElementType();
546 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000547 }
548
John McCall036f2f62011-05-15 07:14:44 +0000549 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
550 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
551 typeSizeMultiplier *= arraySizeMultiplier;
552
553 // This will be a size_t.
554 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000555
Chris Lattner32ac5832010-07-20 21:55:52 +0000556 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
557 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000558 if (llvm::ConstantInt *numElementsC =
559 dyn_cast<llvm::ConstantInt>(numElements)) {
560 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000561
John McCall036f2f62011-05-15 07:14:44 +0000562 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000563
John McCall036f2f62011-05-15 07:14:44 +0000564 // If 'count' was a negative number, it's an overflow.
565 if (isSigned && count.isNegative())
566 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000567
John McCall036f2f62011-05-15 07:14:44 +0000568 // We want to do all this arithmetic in size_t. If numElements is
569 // wider than that, check whether it's already too big, and if so,
570 // overflow.
571 else if (numElementsWidth > sizeWidth &&
572 numElementsWidth - sizeWidth > count.countLeadingZeros())
573 hasAnyOverflow = true;
574
575 // Okay, compute a count at the right width.
576 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
577
Sebastian Redlf862eb62012-02-22 17:37:52 +0000578 // If there is a brace-initializer, we cannot allocate fewer elements than
579 // there are initializers. If we do, that's treated like an overflow.
580 if (adjustedCount.ult(minElements))
581 hasAnyOverflow = true;
582
John McCall036f2f62011-05-15 07:14:44 +0000583 // Scale numElements by that. This might overflow, but we don't
584 // care because it only overflows if allocationSize does, too, and
585 // if that overflows then we shouldn't use this.
586 numElements = llvm::ConstantInt::get(CGF.SizeTy,
587 adjustedCount * arraySizeMultiplier);
588
589 // Compute the size before cookie, and track whether it overflowed.
590 bool overflow;
591 llvm::APInt allocationSize
592 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
593 hasAnyOverflow |= overflow;
594
595 // Add in the cookie, and check whether it's overflowed.
596 if (cookieSize != 0) {
597 // Save the current size without a cookie. This shouldn't be
598 // used if there was overflow.
599 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
600
601 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
602 hasAnyOverflow |= overflow;
603 }
604
605 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000606 if (hasAnyOverflow) {
607 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
608 } else {
John McCall036f2f62011-05-15 07:14:44 +0000609 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000610 }
John McCall036f2f62011-05-15 07:14:44 +0000611
612 // Otherwise, we might need to use the overflow intrinsics.
613 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000614 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000615 // 1) if isSigned, we need to check whether numElements is negative;
616 // 2) if numElementsWidth > sizeWidth, we need to check whether
617 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000618 // 3) if minElements > 0, we need to check whether numElements is smaller
619 // than that.
620 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000621 // sizeWithoutCookie := numElements * typeSizeMultiplier
622 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000623 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000624 // size := sizeWithoutCookie + cookieSize
625 // and check whether it overflows.
626
Craig Topper8a13c412014-05-21 05:09:00 +0000627 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000628
629 // If numElementsWidth > sizeWidth, then one way or another, we're
630 // going to have to do a comparison for (2), and this happens to
631 // take care of (1), too.
632 if (numElementsWidth > sizeWidth) {
633 llvm::APInt threshold(numElementsWidth, 1);
634 threshold <<= sizeWidth;
635
636 llvm::Value *thresholdV
637 = llvm::ConstantInt::get(numElementsType, threshold);
638
639 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
640 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
641
642 // Otherwise, if we're signed, we want to sext up to size_t.
643 } else if (isSigned) {
644 if (numElementsWidth < sizeWidth)
645 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
646
647 // If there's a non-1 type size multiplier, then we can do the
648 // signedness check at the same time as we do the multiply
649 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000650 // unsigned overflow. Otherwise, we have to do it here. But at least
651 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000652 if (typeSizeMultiplier == 1)
653 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000654 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000655
656 // Otherwise, zext up to size_t if necessary.
657 } else if (numElementsWidth < sizeWidth) {
658 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
659 }
660
661 assert(numElements->getType() == CGF.SizeTy);
662
Sebastian Redlf862eb62012-02-22 17:37:52 +0000663 if (minElements) {
664 // Don't allow allocation of fewer elements than we have initializers.
665 if (!hasOverflow) {
666 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
667 llvm::ConstantInt::get(CGF.SizeTy, minElements));
668 } else if (numElementsWidth > sizeWidth) {
669 // The other existing overflow subsumes this check.
670 // We do an unsigned comparison, since any signed value < -1 is
671 // taken care of either above or below.
672 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
673 CGF.Builder.CreateICmpULT(numElements,
674 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
675 }
676 }
677
John McCall036f2f62011-05-15 07:14:44 +0000678 size = numElements;
679
680 // Multiply by the type size if necessary. This multiplier
681 // includes all the factors for nested arrays.
682 //
683 // This step also causes numElements to be scaled up by the
684 // nested-array factor if necessary. Overflow on this computation
685 // can be ignored because the result shouldn't be used if
686 // allocation fails.
687 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000688 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000689 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000690
691 llvm::Value *tsmV =
692 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
693 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000694 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall036f2f62011-05-15 07:14:44 +0000695
696 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
697 if (hasOverflow)
698 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
699 else
700 hasOverflow = overflowed;
701
702 size = CGF.Builder.CreateExtractValue(result, 0);
703
704 // Also scale up numElements by the array size multiplier.
705 if (arraySizeMultiplier != 1) {
706 // If the base element type size is 1, then we can re-use the
707 // multiply we just did.
708 if (typeSize.isOne()) {
709 assert(arraySizeMultiplier == typeSizeMultiplier);
710 numElements = size;
711
712 // Otherwise we need a separate multiply.
713 } else {
714 llvm::Value *asmV =
715 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
716 numElements = CGF.Builder.CreateMul(numElements, asmV);
717 }
718 }
719 } else {
720 // numElements doesn't need to be scaled.
721 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000722 }
723
John McCall036f2f62011-05-15 07:14:44 +0000724 // Add in the cookie size if necessary.
725 if (cookieSize != 0) {
726 sizeWithoutCookie = size;
727
John McCall036f2f62011-05-15 07:14:44 +0000728 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000729 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000730
731 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
732 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000733 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall036f2f62011-05-15 07:14:44 +0000734
735 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
736 if (hasOverflow)
737 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
738 else
739 hasOverflow = overflowed;
740
741 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000742 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000743
John McCall036f2f62011-05-15 07:14:44 +0000744 // If we had any possibility of dynamic overflow, make a select to
745 // overwrite 'size' with an all-ones value, which should cause
746 // operator new to throw.
747 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000748 size = CGF.Builder.CreateSelect(hasOverflow,
749 llvm::Constant::getAllOnesValue(CGF.SizeTy),
750 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000751 }
John McCall8ed55a52010-09-02 09:58:18 +0000752
John McCall036f2f62011-05-15 07:14:44 +0000753 if (cookieSize == 0)
754 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000755 else
John McCall036f2f62011-05-15 07:14:44 +0000756 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000757
John McCall036f2f62011-05-15 07:14:44 +0000758 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000759}
760
Sebastian Redlf862eb62012-02-22 17:37:52 +0000761static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
David Blaikie66e41972015-01-14 07:38:27 +0000762 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000763 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000764 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000765 switch (CGF.getEvaluationKind(AllocType)) {
766 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000767 CGF.EmitScalarInit(Init, nullptr,
David Blaikie66e41972015-01-14 07:38:27 +0000768 CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
John McCall47fb9502013-03-07 21:37:08 +0000769 return;
770 case TEK_Complex:
771 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
772 Alignment),
773 /*isInit*/ true);
774 return;
775 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000776 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000777 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000778 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000779 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000780 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000781 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000782 return;
John McCall7a626f62010-09-15 10:14:12 +0000783 }
John McCall47fb9502013-03-07 21:37:08 +0000784 }
785 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000786}
787
David Blaikiefb901c7a2015-04-04 15:12:29 +0000788void CodeGenFunction::EmitNewArrayInitializer(
789 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
790 llvm::Value *BeginPtr, llvm::Value *NumElements,
791 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000792 // If we have a type with trivial initialization and no initializer,
793 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000794 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000795 return;
John McCall99210dc2011-09-15 06:49:18 +0000796
Richard Smith06a67e22014-06-03 06:58:52 +0000797 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000798
Richard Smith06a67e22014-06-03 06:58:52 +0000799 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000800
801 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000802 llvm::AllocaInst *EndOfInit = nullptr;
803 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
804 EHScopeStack::stable_iterator Cleanup;
805 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000806
Sebastian Redlf862eb62012-02-22 17:37:52 +0000807 // If the initializer is an initializer list, first do the explicit elements.
808 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000809 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000810
Richard Smith1c96bc52013-12-11 01:40:16 +0000811 // If this is a multi-dimensional array new, we will initialize multiple
812 // elements with each init list element.
813 QualType AllocType = E->getAllocatedType();
814 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
815 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000816 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
David Blaikiefb901c7a2015-04-04 15:12:29 +0000817 ElementTy = ConvertTypeForMem(AllocType);
818 llvm::Type *AllocPtrTy = ElementTy->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000819 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
820 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000821 }
822
Richard Smith06a67e22014-06-03 06:58:52 +0000823 // Enter a partial-destruction Cleanup if necessary.
824 if (needsEHCleanup(DtorKind)) {
825 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000826 // directly, but the control flow can get so varied here that it
827 // would actually be quite complex. Therefore we go through an
828 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000829 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
830 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
831 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
832 getDestroyer(DtorKind));
833 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000834 }
835
Sebastian Redlf862eb62012-02-22 17:37:52 +0000836 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000837 // Tell the cleanup that it needs to destroy up to this
838 // element. TODO: some of these stores can be trivially
839 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000840 if (EndOfInit)
841 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
842 EndOfInit);
843 // FIXME: If the last initializer is an incomplete initializer list for
844 // an array, and we have an array filler, we can fold together the two
845 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000846 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000847 ILE->getInit(i)->getType(), CurPtr);
David Blaikiefb901c7a2015-04-04 15:12:29 +0000848 CurPtr = Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr, 1,
849 "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000850 }
851
852 // The remaining elements are filled with the array filler expression.
853 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000854
Richard Smith06a67e22014-06-03 06:58:52 +0000855 // Extract the initializer for the individual array elements by pulling
856 // out the array filler from all the nested initializer lists. This avoids
857 // generating a nested loop for the initialization.
858 while (Init && Init->getType()->isConstantArrayType()) {
859 auto *SubILE = dyn_cast<InitListExpr>(Init);
860 if (!SubILE)
861 break;
862 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
863 Init = SubILE->getArrayFiller();
864 }
865
866 // Switch back to initializing one base element at a time.
867 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000868 }
869
Richard Smith06a67e22014-06-03 06:58:52 +0000870 // Attempt to perform zero-initialization using memset.
871 auto TryMemsetInitialization = [&]() -> bool {
872 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
873 // we can initialize with a memset to -1.
874 if (!CGM.getTypes().isZeroInitializable(ElementType))
875 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000876
Richard Smith06a67e22014-06-03 06:58:52 +0000877 // Optimization: since zero initialization will just set the memory
878 // to all zeroes, generate a single memset to do it in one shot.
879
880 // Subtract out the size of any elements we've already initialized.
881 auto *RemainingSize = AllocSizeWithoutCookie;
882 if (InitListElements) {
883 // We know this can't overflow; we check this when doing the allocation.
884 auto *InitializedSize = llvm::ConstantInt::get(
885 RemainingSize->getType(),
886 getContext().getTypeSizeInChars(ElementType).getQuantity() *
887 InitListElements);
888 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
889 }
890
891 // Create the memset.
892 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
893 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
894 Alignment.getQuantity(), false);
895 return true;
896 };
897
Richard Smith454a7cd2014-06-03 08:26:00 +0000898 // If all elements have already been initialized, skip any further
899 // initialization.
900 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
901 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
902 // If there was a Cleanup, deactivate it.
903 if (CleanupDominator)
904 DeactivateCleanupBlock(Cleanup, CleanupDominator);
905 return;
906 }
907
908 assert(Init && "have trailing elements to initialize but no initializer");
909
Richard Smith06a67e22014-06-03 06:58:52 +0000910 // If this is a constructor call, try to optimize it out, and failing that
911 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000912 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000913 CXXConstructorDecl *Ctor = CCE->getConstructor();
914 if (Ctor->isTrivial()) {
915 // If new expression did not specify value-initialization, then there
916 // is no initialization.
917 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
918 return;
919
920 if (TryMemsetInitialization())
921 return;
922 }
923
924 // Store the new Cleanup position for irregular Cleanups.
925 //
926 // FIXME: Share this cleanup with the constructor call emission rather than
927 // having it create a cleanup of its own.
928 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
929
930 // Emit a constructor call loop to initialize the remaining elements.
931 if (InitListElements)
932 NumElements = Builder.CreateSub(
933 NumElements,
934 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000935 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000936 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000937 return;
938 }
939
Richard Smith06a67e22014-06-03 06:58:52 +0000940 // If this is value-initialization, we can usually use memset.
941 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000942 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000943 if (TryMemsetInitialization())
944 return;
945
946 // Switch to an ImplicitValueInitExpr for the element type. This handles
947 // only one case: multidimensional array new of pointers to members. In
948 // all other cases, we already have an initializer for the array element.
949 Init = &IVIE;
950 }
951
952 // At this point we should have found an initializer for the individual
953 // elements of the array.
954 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
955 "got wrong type of element to initialize");
956
Richard Smith454a7cd2014-06-03 08:26:00 +0000957 // If we have an empty initializer list, we can usually use memset.
958 if (auto *ILE = dyn_cast<InitListExpr>(Init))
959 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
960 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000961
Yunzhong Gaocb779302015-06-10 00:27:52 +0000962 // If we have a struct whose every field is value-initialized, we can
963 // usually use memset.
964 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
965 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
966 if (RType->getDecl()->isStruct()) {
967 unsigned NumFields = 0;
968 for (auto *Field : RType->getDecl()->fields())
969 if (!Field->isUnnamedBitfield())
970 ++NumFields;
971 if (ILE->getNumInits() == NumFields)
972 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
973 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
974 --NumFields;
975 if (ILE->getNumInits() == NumFields && TryMemsetInitialization())
976 return;
977 }
978 }
979 }
980
Richard Smith06a67e22014-06-03 06:58:52 +0000981 // Create the loop blocks.
982 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
983 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
984 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
985
986 // Find the end of the array, hoisted out of the loop.
987 llvm::Value *EndPtr =
988 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000989
Sebastian Redlf862eb62012-02-22 17:37:52 +0000990 // If the number of elements isn't constant, we have to now check if there is
991 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000992 if (!ConstNum) {
993 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000994 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000995 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000996 }
997
998 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000999 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001000
1001 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +00001002 llvm::PHINode *CurPtrPhi =
1003 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
1004 CurPtrPhi->addIncoming(CurPtr, EntryBB);
1005 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +00001006
Richard Smith06a67e22014-06-03 06:58:52 +00001007 // Store the new Cleanup position for irregular Cleanups.
1008 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +00001009
Richard Smith06a67e22014-06-03 06:58:52 +00001010 // Enter a partial-destruction Cleanup if necessary.
1011 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1012 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
1013 getDestroyer(DtorKind));
1014 Cleanup = EHStack.stable_begin();
1015 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +00001016 }
1017
1018 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +00001019 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +00001020
Richard Smith06a67e22014-06-03 06:58:52 +00001021 // Leave the Cleanup if we entered one.
1022 if (CleanupDominator) {
1023 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1024 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001025 }
John McCall99210dc2011-09-15 06:49:18 +00001026
Faisal Vali57ae0562013-12-14 00:40:05 +00001027 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001028 llvm::Value *NextPtr =
David Blaikiefb901c7a2015-04-04 15:12:29 +00001029 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr, 1, "array.next");
Richard Smith06a67e22014-06-03 06:58:52 +00001030
John McCall99210dc2011-09-15 06:49:18 +00001031 // Check whether we've gotten to the end of the array and, if so,
1032 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001033 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1034 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1035 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001036
Richard Smith06a67e22014-06-03 06:58:52 +00001037 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001038}
1039
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001040static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
David Blaikiefb901c7a2015-04-04 15:12:29 +00001041 QualType ElementType, llvm::Type *ElementTy,
1042 llvm::Value *NewPtr, llvm::Value *NumElements,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001043 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001044 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001045 if (E->isArray())
David Blaikiefb901c7a2015-04-04 15:12:29 +00001046 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00001047 AllocSizeWithoutCookie);
1048 else if (const Expr *Init = E->getInitializer())
David Blaikie66e41972015-01-14 07:38:27 +00001049 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001050}
1051
Richard Smith8d0dc312013-07-21 23:12:18 +00001052/// Emit a call to an operator new or operator delete function, as implicitly
1053/// created by new-expressions and delete-expressions.
1054static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1055 const FunctionDecl *Callee,
1056 const FunctionProtoType *CalleeType,
1057 const CallArgList &Args) {
1058 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001059 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001060 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001061 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1062 Args, CalleeType, /*chainCall=*/false),
1063 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001064
1065 /// C++1y [expr.new]p10:
1066 /// [In a new-expression,] an implementation is allowed to omit a call
1067 /// to a replaceable global allocation function.
1068 ///
1069 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001070 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001071 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001072 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001073 // FIXME: Add addAttribute to CallSite.
1074 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1075 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1076 llvm::Attribute::Builtin);
1077 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1078 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1079 llvm::Attribute::Builtin);
1080 else
1081 llvm_unreachable("unexpected kind of call instruction");
1082 }
1083
1084 return RV;
1085}
1086
Richard Smith760520b2014-06-03 23:27:44 +00001087RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1088 const Expr *Arg,
1089 bool IsDelete) {
1090 CallArgList Args;
1091 const Stmt *ArgS = Arg;
1092 EmitCallArgs(Args, *Type->param_type_begin(),
1093 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1094 // Find the allocation or deallocation function that we're calling.
1095 ASTContext &Ctx = getContext();
1096 DeclarationName Name = Ctx.DeclarationNames
1097 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1098 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001099 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1100 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1101 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001102 llvm_unreachable("predeclared global operator new/delete is missing");
1103}
1104
John McCall824c2f52010-09-14 07:57:04 +00001105namespace {
1106 /// A cleanup to call the given 'operator delete' function upon
1107 /// abnormal exit from a new expression.
1108 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1109 size_t NumPlacementArgs;
1110 const FunctionDecl *OperatorDelete;
1111 llvm::Value *Ptr;
1112 llvm::Value *AllocSize;
1113
1114 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1115
1116 public:
1117 static size_t getExtraSize(size_t NumPlacementArgs) {
1118 return NumPlacementArgs * sizeof(RValue);
1119 }
1120
1121 CallDeleteDuringNew(size_t NumPlacementArgs,
1122 const FunctionDecl *OperatorDelete,
1123 llvm::Value *Ptr,
1124 llvm::Value *AllocSize)
1125 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1126 Ptr(Ptr), AllocSize(AllocSize) {}
1127
1128 void setPlacementArg(unsigned I, RValue Arg) {
1129 assert(I < NumPlacementArgs && "index out of range");
1130 getPlacementArgs()[I] = Arg;
1131 }
1132
Craig Topper4f12f102014-03-12 06:41:41 +00001133 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001134 const FunctionProtoType *FPT
1135 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001136 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1137 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001138
1139 CallArgList DeleteArgs;
1140
1141 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001142 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001143 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001144
1145 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001146 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001147 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001148
1149 // Pass the rest of the arguments, which must match exactly.
1150 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001151 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001152
1153 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001154 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001155 }
1156 };
John McCall7f9c92a2010-09-17 00:50:28 +00001157
1158 /// A cleanup to call the given 'operator delete' function upon
1159 /// abnormal exit from a new expression when the new expression is
1160 /// conditional.
1161 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1162 size_t NumPlacementArgs;
1163 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001164 DominatingValue<RValue>::saved_type Ptr;
1165 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001166
John McCallcb5f77f2011-01-28 10:53:53 +00001167 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1168 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001169 }
1170
1171 public:
1172 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001173 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001174 }
1175
1176 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1177 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001178 DominatingValue<RValue>::saved_type Ptr,
1179 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001180 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1181 Ptr(Ptr), AllocSize(AllocSize) {}
1182
John McCallcb5f77f2011-01-28 10:53:53 +00001183 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001184 assert(I < NumPlacementArgs && "index out of range");
1185 getPlacementArgs()[I] = Arg;
1186 }
1187
Craig Topper4f12f102014-03-12 06:41:41 +00001188 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001189 const FunctionProtoType *FPT
1190 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001191 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1192 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001193
1194 CallArgList DeleteArgs;
1195
1196 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001197 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001198 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001199
1200 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001201 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001202 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001203 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001204 }
1205
1206 // Pass the rest of the arguments, which must match exactly.
1207 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001208 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001209 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001210 }
1211
1212 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001213 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001214 }
1215 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001216}
John McCall7f9c92a2010-09-17 00:50:28 +00001217
1218/// Enter a cleanup to call 'operator delete' if the initializer in a
1219/// new-expression throws.
1220static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1221 const CXXNewExpr *E,
1222 llvm::Value *NewPtr,
1223 llvm::Value *AllocSize,
1224 const CallArgList &NewArgs) {
1225 // If we're not inside a conditional branch, then the cleanup will
1226 // dominate and we can do the easier (and more efficient) thing.
1227 if (!CGF.isInConditionalBranch()) {
1228 CallDeleteDuringNew *Cleanup = CGF.EHStack
1229 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1230 E->getNumPlacementArgs(),
1231 E->getOperatorDelete(),
1232 NewPtr, AllocSize);
1233 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001234 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001235
1236 return;
1237 }
1238
1239 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001240 DominatingValue<RValue>::saved_type SavedNewPtr =
1241 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1242 DominatingValue<RValue>::saved_type SavedAllocSize =
1243 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001244
1245 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001246 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001247 E->getNumPlacementArgs(),
1248 E->getOperatorDelete(),
1249 SavedNewPtr,
1250 SavedAllocSize);
1251 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001252 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001253 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001254
John McCallf4beacd2011-11-10 10:43:54 +00001255 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001256}
1257
Anders Carlssoncc52f652009-09-22 22:53:17 +00001258llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001259 // The element type being allocated.
1260 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001261
John McCall75f94982011-03-07 03:12:35 +00001262 // 1. Build a call to the allocation function.
1263 FunctionDecl *allocator = E->getOperatorNew();
1264 const FunctionProtoType *allocatorType =
1265 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001266
John McCall75f94982011-03-07 03:12:35 +00001267 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001268
1269 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001270 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001271
Sebastian Redlf862eb62012-02-22 17:37:52 +00001272 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1273 unsigned minElements = 0;
1274 if (E->isArray() && E->hasInitializer()) {
1275 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1276 minElements = ILE->getNumInits();
1277 }
1278
Craig Topper8a13c412014-05-21 05:09:00 +00001279 llvm::Value *numElements = nullptr;
1280 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001281 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001282 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1283 allocSizeWithoutCookie);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001284
Eli Friedman43dca6a2011-05-02 17:57:46 +00001285 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001286
Anders Carlssoncc52f652009-09-22 22:53:17 +00001287 // We start at 1 here because the first argument (the allocation size)
1288 // has already been emitted.
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001289 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001290 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1291 /*ParamsToSkip*/ 1);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001292
John McCall7ec4b432011-05-16 01:05:12 +00001293 // Emit the allocation call. If the allocator is a global placement
1294 // operator, just "inline" it directly.
1295 RValue RV;
1296 if (allocator->isReservedGlobalPlacementOperator()) {
1297 assert(allocatorArgs.size() == 2);
1298 RV = allocatorArgs[1].RV;
1299 // TODO: kill any unnecessary computations done for the size
1300 // argument.
1301 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001302 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001303 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001304
John McCall75f94982011-03-07 03:12:35 +00001305 // Emit a null check on the allocation result if the allocation
1306 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001307 // exception spec or is the reserved placement new) and we have an
John McCall75f94982011-03-07 03:12:35 +00001308 // interesting initializer.
Richard Smith902a0232015-02-14 01:52:20 +00001309 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001310 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001311
Craig Topper8a13c412014-05-21 05:09:00 +00001312 llvm::BasicBlock *nullCheckBB = nullptr;
1313 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001314
John McCall75f94982011-03-07 03:12:35 +00001315 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001316 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001317
John McCallf7dcf322011-03-07 01:52:56 +00001318 // The null-check means that the initializer is conditionally
1319 // evaluated.
1320 ConditionalEvaluation conditional(*this);
1321
John McCall75f94982011-03-07 03:12:35 +00001322 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001323 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001324
1325 nullCheckBB = Builder.GetInsertBlock();
1326 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1327 contBB = createBasicBlock("new.cont");
1328
1329 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1330 Builder.CreateCondBr(isNull, contBB, notNullBB);
1331 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001332 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001333
John McCall824c2f52010-09-14 07:57:04 +00001334 // If there's an operator delete, enter a cleanup to call it if an
1335 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001336 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001337 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001338 if (E->getOperatorDelete() &&
1339 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001340 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1341 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001342 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001343 }
1344
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001345 assert((allocSize == allocSizeWithoutCookie) ==
1346 CalculateCookiePadding(*this, E).isZero());
1347 if (allocSize != allocSizeWithoutCookie) {
1348 assert(E->isArray());
1349 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1350 numElements,
1351 E, allocType);
1352 }
1353
David Blaikiefb901c7a2015-04-04 15:12:29 +00001354 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1355 llvm::Type *elementPtrTy = elementTy->getPointerTo(AS);
John McCall75f94982011-03-07 03:12:35 +00001356 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001357
David Blaikiefb901c7a2015-04-04 15:12:29 +00001358 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall99210dc2011-09-15 06:49:18 +00001359 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001360 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001361 // NewPtr is a pointer to the base element type. If we're
1362 // allocating an array of arrays, we'll need to cast back to the
1363 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001364 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001365 if (result->getType() != resultType)
1366 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001367 }
John McCall824c2f52010-09-14 07:57:04 +00001368
1369 // Deactivate the 'operator delete' cleanup if we finished
1370 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001371 if (operatorDeleteCleanup.isValid()) {
1372 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1373 cleanupDominator->eraseFromParent();
1374 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001375
John McCall75f94982011-03-07 03:12:35 +00001376 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001377 conditional.end(*this);
1378
John McCall75f94982011-03-07 03:12:35 +00001379 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1380 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001381
Jay Foad20c0f022011-03-30 11:28:58 +00001382 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001383 PHI->addIncoming(result, notNullBB);
1384 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1385 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001386
John McCall75f94982011-03-07 03:12:35 +00001387 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001388 }
John McCall8ed55a52010-09-02 09:58:18 +00001389
John McCall75f94982011-03-07 03:12:35 +00001390 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001391}
1392
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001393void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1394 llvm::Value *Ptr,
1395 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001396 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1397
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001398 const FunctionProtoType *DeleteFTy =
1399 DeleteFD->getType()->getAs<FunctionProtoType>();
1400
1401 CallArgList DeleteArgs;
1402
Anders Carlsson21122cf2009-12-13 20:04:38 +00001403 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001404 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001405 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001406 if (DeleteFTy->getNumParams() == 2) {
1407 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001408 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1409 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1410 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001411 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001412
1413 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001414 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001415 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001416
Anders Carlsson21122cf2009-12-13 20:04:38 +00001417 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001418 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001419
1420 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001421 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001422}
1423
John McCall8ed55a52010-09-02 09:58:18 +00001424namespace {
1425 /// Calls the given 'operator delete' on a single object.
1426 struct CallObjectDelete : EHScopeStack::Cleanup {
1427 llvm::Value *Ptr;
1428 const FunctionDecl *OperatorDelete;
1429 QualType ElementType;
1430
1431 CallObjectDelete(llvm::Value *Ptr,
1432 const FunctionDecl *OperatorDelete,
1433 QualType ElementType)
1434 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1435
Craig Topper4f12f102014-03-12 06:41:41 +00001436 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001437 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1438 }
1439 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001440}
John McCall8ed55a52010-09-02 09:58:18 +00001441
David Majnemer0c0b6d92014-10-31 20:09:12 +00001442void
1443CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1444 llvm::Value *CompletePtr,
1445 QualType ElementType) {
1446 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1447 OperatorDelete, ElementType);
1448}
1449
John McCall8ed55a52010-09-02 09:58:18 +00001450/// Emit the code for deleting a single object.
1451static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001452 const CXXDeleteExpr *DE,
John McCall8ed55a52010-09-02 09:58:18 +00001453 llvm::Value *Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001454 QualType ElementType) {
John McCall8ed55a52010-09-02 09:58:18 +00001455 // Find the destructor for the type, if applicable. If the
1456 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001457 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001458 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1459 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001460 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001461 Dtor = RD->getDestructor();
1462
1463 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001464 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1465 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001466 return;
1467 }
1468 }
1469 }
1470
1471 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001472 // This doesn't have to a conditional cleanup because we're going
1473 // to pop it off in a second.
David Majnemer08681372014-11-01 07:37:17 +00001474 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001475 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1476 Ptr, OperatorDelete, ElementType);
1477
1478 if (Dtor)
1479 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001480 /*ForVirtualBase=*/false,
1481 /*Delegating=*/false,
1482 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001483 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001484 ElementType->isObjCLifetimeType()) {
1485 switch (ElementType.getObjCLifetime()) {
1486 case Qualifiers::OCL_None:
1487 case Qualifiers::OCL_ExplicitNone:
1488 case Qualifiers::OCL_Autoreleasing:
1489 break;
John McCall8ed55a52010-09-02 09:58:18 +00001490
John McCall31168b02011-06-15 23:02:42 +00001491 case Qualifiers::OCL_Strong: {
1492 // Load the pointer value.
1493 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1494 ElementType.isVolatileQualified());
1495
John McCallcdda29c2013-03-13 03:10:54 +00001496 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001497 break;
1498 }
1499
1500 case Qualifiers::OCL_Weak:
1501 CGF.EmitARCDestroyWeak(Ptr);
1502 break;
1503 }
1504 }
1505
John McCall8ed55a52010-09-02 09:58:18 +00001506 CGF.PopCleanupBlock();
1507}
1508
1509namespace {
1510 /// Calls the given 'operator delete' on an array of objects.
1511 struct CallArrayDelete : EHScopeStack::Cleanup {
1512 llvm::Value *Ptr;
1513 const FunctionDecl *OperatorDelete;
1514 llvm::Value *NumElements;
1515 QualType ElementType;
1516 CharUnits CookieSize;
1517
1518 CallArrayDelete(llvm::Value *Ptr,
1519 const FunctionDecl *OperatorDelete,
1520 llvm::Value *NumElements,
1521 QualType ElementType,
1522 CharUnits CookieSize)
1523 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1524 ElementType(ElementType), CookieSize(CookieSize) {}
1525
Craig Topper4f12f102014-03-12 06:41:41 +00001526 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001527 const FunctionProtoType *DeleteFTy =
1528 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001529 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001530
1531 CallArgList Args;
1532
1533 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001534 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001535 llvm::Value *DeletePtr
1536 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001537 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001538
1539 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001540 if (DeleteFTy->getNumParams() == 2) {
1541 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001542 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001543 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1544
1545 CharUnits ElementTypeSize =
1546 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1547
1548 // The size of an element, multiplied by the number of elements.
1549 llvm::Value *Size
1550 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
David Majnemer149e6032015-06-30 03:30:26 +00001551 if (NumElements)
1552 Size = CGF.Builder.CreateMul(Size, NumElements);
John McCall8ed55a52010-09-02 09:58:18 +00001553
1554 // Plus the size of the cookie if applicable.
1555 if (!CookieSize.isZero()) {
1556 llvm::Value *CookieSizeV
1557 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1558 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1559 }
1560
Eli Friedman43dca6a2011-05-02 17:57:46 +00001561 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001562 }
1563
1564 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001565 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001566 }
1567 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001568}
John McCall8ed55a52010-09-02 09:58:18 +00001569
1570/// Emit the code for deleting an array of objects.
1571static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001572 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001573 llvm::Value *deletedPtr,
1574 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001575 llvm::Value *numElements = nullptr;
1576 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001577 CharUnits cookieSize;
1578 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1579 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001580
John McCallca2c56f2011-07-13 01:41:37 +00001581 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001582
1583 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001584 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001585 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001586 allocatedPtr, operatorDelete,
1587 numElements, elementType,
1588 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001589
John McCallca2c56f2011-07-13 01:41:37 +00001590 // Destroy the elements.
1591 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1592 assert(numElements && "no element count for a type with a destructor!");
1593
John McCallca2c56f2011-07-13 01:41:37 +00001594 llvm::Value *arrayEnd =
1595 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001596
1597 // Note that it is legal to allocate a zero-length array, and we
1598 // can never fold the check away because the length should always
1599 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001600 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1601 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001602 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001603 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001604 }
1605
John McCallca2c56f2011-07-13 01:41:37 +00001606 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001607 CGF.PopCleanupBlock();
1608}
1609
Anders Carlssoncc52f652009-09-22 22:53:17 +00001610void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001611 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001612 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001613
1614 // Null check the pointer.
1615 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1616 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1617
Anders Carlsson98981b12011-04-11 00:30:07 +00001618 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001619
1620 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1621 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001622
John McCall8ed55a52010-09-02 09:58:18 +00001623 // We might be deleting a pointer to array. If so, GEP down to the
1624 // first non-array element.
1625 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1626 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1627 if (DeleteTy->isConstantArrayType()) {
1628 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001629 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001630
1631 GEP.push_back(Zero); // point at the outermost array
1632
1633 // For each layer of array type we're pointing at:
1634 while (const ConstantArrayType *Arr
1635 = getContext().getAsConstantArrayType(DeleteTy)) {
1636 // 1. Unpeel the array type.
1637 DeleteTy = Arr->getElementType();
1638
1639 // 2. GEP to the first element of the array.
1640 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001641 }
John McCall8ed55a52010-09-02 09:58:18 +00001642
Jay Foad040dd822011-07-22 08:16:57 +00001643 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001644 }
1645
Douglas Gregor04f36212010-09-02 17:38:50 +00001646 assert(ConvertTypeForMem(DeleteTy) ==
1647 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001648
Reid Kleckner7270ef52015-03-19 17:03:58 +00001649 if (E->isArrayForm()) {
1650 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1651 } else {
1652 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1653 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001654
Anders Carlssoncc52f652009-09-22 22:53:17 +00001655 EmitBlock(DeleteEnd);
1656}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001657
David Majnemer1c3d95e2014-07-19 00:17:06 +00001658static bool isGLValueFromPointerDeref(const Expr *E) {
1659 E = E->IgnoreParens();
1660
1661 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1662 if (!CE->getSubExpr()->isGLValue())
1663 return false;
1664 return isGLValueFromPointerDeref(CE->getSubExpr());
1665 }
1666
1667 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1668 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1669
1670 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1671 if (BO->getOpcode() == BO_Comma)
1672 return isGLValueFromPointerDeref(BO->getRHS());
1673
1674 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1675 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1676 isGLValueFromPointerDeref(ACO->getFalseExpr());
1677
1678 // C++11 [expr.sub]p1:
1679 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1680 if (isa<ArraySubscriptExpr>(E))
1681 return true;
1682
1683 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1684 if (UO->getOpcode() == UO_Deref)
1685 return true;
1686
1687 return false;
1688}
1689
Warren Hunt747e3012014-06-18 21:15:55 +00001690static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001691 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001692 // Get the vtable pointer.
1693 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1694
1695 // C++ [expr.typeid]p2:
1696 // If the glvalue expression is obtained by applying the unary * operator to
1697 // a pointer and the pointer is a null pointer value, the typeid expression
1698 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001699 //
1700 // However, this paragraph's intent is not clear. We choose a very generous
1701 // interpretation which implores us to consider comma operators, conditional
1702 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001703 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001704 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1705 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001706 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001707 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001708 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001709
David Majnemer1162d252014-06-22 19:05:33 +00001710 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1711 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001712
David Majnemer1162d252014-06-22 19:05:33 +00001713 CGF.EmitBlock(BadTypeidBlock);
1714 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1715 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001716 }
1717
David Majnemer1162d252014-06-22 19:05:33 +00001718 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1719 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001720}
1721
John McCalle4df6c82011-01-28 08:37:24 +00001722llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001723 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001724 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001725
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001726 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001727 llvm::Constant *TypeInfo =
1728 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001729 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001730 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001731
Anders Carlsson940f02d2011-04-18 00:57:03 +00001732 // C++ [expr.typeid]p2:
1733 // When typeid is applied to a glvalue expression whose type is a
1734 // polymorphic class type, the result refers to a std::type_info object
1735 // representing the type of the most derived object (that is, the dynamic
1736 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001737 if (E->isPotentiallyEvaluated())
1738 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1739 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001740
1741 QualType OperandTy = E->getExprOperand()->getType();
1742 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1743 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001744}
Mike Stump65511702009-11-16 06:50:58 +00001745
Anders Carlssonc1c99712011-04-11 01:45:29 +00001746static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1747 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001748 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001749 if (DestTy->isPointerType())
1750 return llvm::Constant::getNullValue(DestLTy);
1751
1752 /// C++ [expr.dynamic.cast]p9:
1753 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001754 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1755 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001756
1757 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1758 return llvm::UndefValue::get(DestLTy);
1759}
1760
Anders Carlsson882d7902011-04-11 00:46:40 +00001761llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001762 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001763 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001764
Anders Carlssonc1c99712011-04-11 01:45:29 +00001765 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001766 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1767 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001768
1769 QualType SrcTy = DCE->getSubExpr()->getType();
1770
David Majnemer1162d252014-06-22 19:05:33 +00001771 // C++ [expr.dynamic.cast]p7:
1772 // If T is "pointer to cv void," then the result is a pointer to the most
1773 // derived object pointed to by v.
1774 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1775
1776 bool isDynamicCastToVoid;
1777 QualType SrcRecordTy;
1778 QualType DestRecordTy;
1779 if (DestPTy) {
1780 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1781 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1782 DestRecordTy = DestPTy->getPointeeType();
1783 } else {
1784 isDynamicCastToVoid = false;
1785 SrcRecordTy = SrcTy;
1786 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1787 }
1788
1789 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1790
Anders Carlsson882d7902011-04-11 00:46:40 +00001791 // C++ [expr.dynamic.cast]p4:
1792 // If the value of v is a null pointer value in the pointer case, the result
1793 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001794 bool ShouldNullCheckSrcValue =
1795 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1796 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001797
1798 llvm::BasicBlock *CastNull = nullptr;
1799 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001800 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001801
Anders Carlsson882d7902011-04-11 00:46:40 +00001802 if (ShouldNullCheckSrcValue) {
1803 CastNull = createBasicBlock("dynamic_cast.null");
1804 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1805
1806 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1807 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1808 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001809 }
1810
David Majnemer1162d252014-06-22 19:05:33 +00001811 if (isDynamicCastToVoid) {
1812 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1813 DestTy);
1814 } else {
1815 assert(DestRecordTy->isRecordType() &&
1816 "destination type must be a record type!");
1817 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1818 DestTy, DestRecordTy, CastEnd);
1819 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001820
1821 if (ShouldNullCheckSrcValue) {
1822 EmitBranch(CastEnd);
1823
1824 EmitBlock(CastNull);
1825 EmitBranch(CastEnd);
1826 }
1827
1828 EmitBlock(CastEnd);
1829
1830 if (ShouldNullCheckSrcValue) {
1831 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1832 PHI->addIncoming(Value, CastNotNull);
1833 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1834
1835 Value = PHI;
1836 }
1837
1838 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001839}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001840
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001841void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001842 RunCleanupsScope Scope(*this);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001843 LValue SlotLV =
1844 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001845
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001846 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
James Y Knight53c76162015-07-17 18:21:37 +00001847 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1848 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001849 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001850 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00001851 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001852 if (CurField->hasCapturedVLAType()) {
1853 auto VAT = CurField->getCapturedVLAType();
1854 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1855 } else {
1856 ArrayRef<VarDecl *> ArrayIndexes;
1857 if (CurField->getType()->isArrayType())
1858 ArrayIndexes = E->getCaptureInitIndexVars(i);
1859 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1860 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001861 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001862}