blob: 47dc9fbbc7305753617264d02a43119f27a8f6ab [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Lacey8b549992013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070021#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000023
Anders Carlsson16d81b82009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Anders Carlsson3b5ad222010-01-01 20:29:01 +000027RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
Richard Smith4def70d2012-10-09 19:52:38 +000028 SourceLocation CallLoc,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000029 llvm::Value *Callee,
30 ReturnValueSlot ReturnValue,
31 llvm::Value *This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000032 llvm::Value *ImplicitParam,
33 QualType ImplicitParamTy,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000034 CallExpr::const_arg_iterator ArgBeg,
35 CallExpr::const_arg_iterator ArgEnd) {
36 assert(MD->isInstance() &&
37 "Trying to emit a member call expr on a static method!");
38
Richard Smith2c9f87c2012-08-24 00:54:33 +000039 // C++11 [class.mfct.non-static]p2:
40 // If a non-static member function of a class X is called for an object that
41 // is not of type X, or of a type derived from X, the behavior is undefined.
Richard Smith8e1cee62012-10-25 02:14:12 +000042 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
43 : TCK_MemberCall,
44 CallLoc, This, getContext().getRecordType(MD->getParent()));
Richard Smith2c9f87c2012-08-24 00:54:33 +000045
Anders Carlsson3b5ad222010-01-01 20:29:01 +000046 CallArgList Args;
47
48 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000049 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000050
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000051 // If there is an implicit parameter (e.g. VTT), emit it.
52 if (ImplicitParam) {
53 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssonc997d422010-01-02 01:01:18 +000054 }
John McCallde5d3c72012-02-17 03:33:10 +000055
56 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssonc997d422010-01-02 01:01:18 +000058
John McCallde5d3c72012-02-17 03:33:10 +000059 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000060 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
61
John McCall0f3d0972012-07-07 06:41:13 +000062 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000063 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000064}
65
Rafael Espindolaea01d762012-06-28 14:28:57 +000066static CXXRecordDecl *getCXXRecord(const Expr *E) {
67 QualType T = E->getType();
68 if (const PointerType *PTy = T->getAs<PointerType>())
69 T = PTy->getPointeeType();
70 const RecordType *Ty = T->castAs<RecordType>();
71 return cast<CXXRecordDecl>(Ty->getDecl());
72}
73
Francois Pichetdbee3412011-01-18 05:04:39 +000074// Note: This function also emit constructor calls to support a MSVC
75// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000076RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
77 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +000078 const Expr *callee = CE->getCallee()->IgnoreParens();
79
80 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +000081 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +000082
83 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000084 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
85
86 if (MD->isStatic()) {
87 // The method is static, emit it as we would a regular call.
88 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
89 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
Peter Collingbourneb914e872013-10-20 21:29:19 +000090 CE->getLocStart(), ReturnValue, CE->arg_begin(),
91 CE->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +000092 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +000093
John McCallfc400282010-09-03 01:26:39 +000094 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +000095 const Expr *Base = ME->getBase();
96 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +000097
Stephen Hines6bcf27b2014-05-29 04:14:42 -070098 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer9581ed02013-08-25 22:46:27 +000099 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000100 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
101 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
102 assert(DevirtualizedMethod);
103 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
104 const Expr *Inner = Base->ignoreParenBaseCasts();
105 if (getCXXRecord(Inner) == DevirtualizedClass)
106 // If the class of the Inner expression is where the dynamic method
107 // is defined, build the this pointer from it.
108 Base = Inner;
109 else if (getCXXRecord(Base) != DevirtualizedClass) {
110 // If the method is defined in a class that is not the best dynamic
111 // one or the one of the full expression, we would have to build
112 // a derived-to-base cast to compute the correct this pointer, but
113 // we don't have support for that yet, so do a virtual call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700114 DevirtualizedMethod = nullptr;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000115 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000116 // If the return types are not the same, this might be a case where more
117 // code needs to run to compensate for it. For example, the derived
118 // method might return a type that inherits form from the return
119 // type of MD and has a prefix.
120 // For now we just avoid devirtualizing these covariant cases.
121 if (DevirtualizedMethod &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700122 DevirtualizedMethod->getReturnType().getCanonicalType() !=
123 MD->getReturnType().getCanonicalType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700124 DevirtualizedMethod = nullptr;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000125 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000126
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000127 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000128 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000129 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000130 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000131 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000132
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000133
John McCallfc400282010-09-03 01:26:39 +0000134 if (MD->isTrivial()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700135 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichetdbee3412011-01-18 05:04:39 +0000136 if (isa<CXXConstructorDecl>(MD) &&
137 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700138 return RValue::get(nullptr);
John McCallfc400282010-09-03 01:26:39 +0000139
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000140 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
141 // We don't like to generate the trivial copy/move assignment operator
142 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000143 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000144 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichetdbee3412011-01-18 05:04:39 +0000145 return RValue::get(This);
146 }
147
148 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000149 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
150 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000151 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
152 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
153 CE->arg_begin(), CE->arg_end());
154 return RValue::get(This);
155 }
156 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000157 }
158
John McCallfc400282010-09-03 01:26:39 +0000159 // Compute the function type we're calling.
Eli Friedman465e89e2012-10-25 00:12:49 +0000160 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700161 const CGFunctionInfo *FInfo = nullptr;
Eli Friedman465e89e2012-10-25 00:12:49 +0000162 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
163 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCallde5d3c72012-02-17 03:33:10 +0000164 Dtor_Complete);
Eli Friedman465e89e2012-10-25 00:12:49 +0000165 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
166 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
167 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000168 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000169 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000170
Reid Klecknera4130ba2013-07-22 13:51:44 +0000171 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000172
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173 // C++ [class.virtual]p12:
174 // Explicit qualification with the scope operator (5.1) suppresses the
175 // virtual call mechanism.
176 //
177 // We also don't emit a virtual call if the base expression has a record type
178 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000179 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin3258abc2013-06-19 23:23:19 +0000180 llvm::Value *Callee;
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000181
John McCallfc400282010-09-03 01:26:39 +0000182 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000183 assert(CE->arg_begin() == CE->arg_end() &&
184 "Destructor shouldn't have explicit parameters");
185 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCallfc400282010-09-03 01:26:39 +0000186 if (UseVirtualCall) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000187 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
188 CE->getExprLoc(), This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000189 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000190 if (getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000191 MD->isVirtual() &&
192 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000193 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000194 else if (!DevirtualizedMethod)
Reid Klecknera4130ba2013-07-22 13:51:44 +0000195 Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000196 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000197 const CXXDestructorDecl *DDtor =
198 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000199 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
200 }
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000201 EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700202 /*ImplicitParam=*/nullptr, QualType(), nullptr,nullptr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000203 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700204 return RValue::get(nullptr);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000205 }
206
207 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichetdbee3412011-01-18 05:04:39 +0000208 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000209 } else if (UseVirtualCall) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000210 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000211 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000212 if (getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000213 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000214 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000215 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000216 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000217 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000218 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000219 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000220 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000221 }
222
Stephen Hines651f13c2014-04-23 16:59:28 -0700223 if (MD->isVirtual()) {
224 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
225 *this, MD, This, UseVirtualCall);
226 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000227
Richard Smith4def70d2012-10-09 19:52:38 +0000228 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700229 /*ImplicitParam=*/nullptr, QualType(),
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000230 CE->arg_begin(), CE->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000231}
232
233RValue
234CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
235 ReturnValueSlot ReturnValue) {
236 const BinaryOperator *BO =
237 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
238 const Expr *BaseExpr = BO->getLHS();
239 const Expr *MemFnExpr = BO->getRHS();
240
241 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000242 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000243
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000244 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000245 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000246 const CXXRecordDecl *RD =
247 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
248
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000249 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000250 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000251
252 // Emit the 'this' pointer.
253 llvm::Value *This;
254
John McCall2de56d12010-08-25 11:45:40 +0000255 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000256 This = EmitScalarExpr(BaseExpr);
257 else
258 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000259
Richard Smith4def70d2012-10-09 19:52:38 +0000260 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
261 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000262
John McCall93d557b2010-08-22 00:05:51 +0000263 // Ask the ABI to load the callee. Note that This is modified.
264 llvm::Value *Callee =
Stephen Hines651f13c2014-04-23 16:59:28 -0700265 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000266
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000267 CallArgList Args;
268
269 QualType ThisType =
270 getContext().getPointerType(getContext().getTagDeclType(RD));
271
272 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000273 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000274
275 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276
277 // And the rest of the call args
278 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
Nick Lewycky5d4a7552013-10-01 21:51:38 +0000279 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
280 Callee, ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000281}
282
283RValue
284CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
285 const CXXMethodDecl *MD,
286 ReturnValueSlot ReturnValue) {
287 assert(MD->isInstance() &&
288 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000289 LValue LV = EmitLValue(E->getArg(0));
290 llvm::Value *This = LV.getAddress();
291
Douglas Gregorb2b56582011-09-06 16:26:56 +0000292 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
293 MD->isTrivial()) {
294 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
295 QualType Ty = E->getType();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000296 EmitAggregateAssign(This, Src, Ty);
Douglas Gregorb2b56582011-09-06 16:26:56 +0000297 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000298 }
299
Anders Carlssona2447e02011-05-08 20:32:23 +0000300 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smith4def70d2012-10-09 19:52:38 +0000301 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700302 /*ImplicitParam=*/nullptr, QualType(),
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000303 E->arg_begin() + 1, E->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000304}
305
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000306RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
307 ReturnValueSlot ReturnValue) {
308 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
309}
310
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000311static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
312 llvm::Value *DestPtr,
313 const CXXRecordDecl *Base) {
314 if (Base->isEmpty())
315 return;
316
317 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
318
319 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
320 CharUnits Size = Layout.getNonVirtualSize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700321 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000322
323 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
324
325 // If the type contains a pointer to data member we can't memset it to zero.
326 // Instead, create a null constant and copy it to the destination.
327 // TODO: there are other patterns besides zero that we can usefully memset,
328 // like -1, which happens to be the pattern used by member-pointers.
329 // TODO: isZeroInitializable can be over-conservative in the case where a
330 // virtual base contains a member pointer.
331 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
332 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
333
334 llvm::GlobalVariable *NullVariable =
335 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
336 /*isConstant=*/true,
337 llvm::GlobalVariable::PrivateLinkage,
338 NullConstant, Twine());
339 NullVariable->setAlignment(Align.getQuantity());
340 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
341
342 // Get and call the appropriate llvm.memcpy overload.
343 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
344 return;
345 }
346
347 // Otherwise, just memset the whole thing to zero. This is legal
348 // because in LLVM, all default initializers (other than the ones we just
349 // handled above) are guaranteed to have a bit pattern of all zeros.
350 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
351 Align.getQuantity());
352}
353
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000354void
John McCall558d2ab2010-09-15 10:14:12 +0000355CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
356 AggValueSlot Dest) {
357 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000358 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000359
360 // If we require zero initialization before (or instead of) calling the
361 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000362 // constructor, emit the zero initialization now, unless destination is
363 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000364 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
365 switch (E->getConstructionKind()) {
366 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000367 case CXXConstructExpr::CK_Complete:
368 EmitNullInitialization(Dest.getAddr(), E->getType());
369 break;
370 case CXXConstructExpr::CK_VirtualBase:
371 case CXXConstructExpr::CK_NonVirtualBase:
372 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
373 break;
374 }
375 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000376
377 // If this is a call to a trivial default constructor, do nothing.
378 if (CD->isTrivial() && CD->isDefaultConstructor())
379 return;
380
John McCallfc1e6c72010-09-18 00:58:34 +0000381 // Elide the constructor if we're constructing from a temporary.
382 // The temporary check is required because Sema sets this on NRVO
383 // returns.
Richard Smith7edf9e32012-11-01 22:30:59 +0000384 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000385 assert(getContext().hasSameUnqualifiedType(E->getType(),
386 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000387 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
388 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000389 return;
390 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000391 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000392
John McCallc3c07662011-07-13 06:10:41 +0000393 if (const ConstantArrayType *arrayType
394 = getContext().getAsConstantArrayType(E->getType())) {
395 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000396 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000397 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000398 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000399 bool ForVirtualBase = false;
Douglas Gregor378e1e72013-01-31 05:50:40 +0000400 bool Delegating = false;
401
Sean Huntd49bd552011-05-03 20:19:28 +0000402 switch (E->getConstructionKind()) {
403 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000404 // We should be emitting a constructor; GlobalDecl will assert this
405 Type = CurGD.getCtorType();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000406 Delegating = true;
Sean Huntd49bd552011-05-03 20:19:28 +0000407 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000408
Sean Huntd49bd552011-05-03 20:19:28 +0000409 case CXXConstructExpr::CK_Complete:
410 Type = Ctor_Complete;
411 break;
412
413 case CXXConstructExpr::CK_VirtualBase:
414 ForVirtualBase = true;
415 // fall-through
416
417 case CXXConstructExpr::CK_NonVirtualBase:
418 Type = Ctor_Base;
419 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000420
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000421 // Call the constructor.
Douglas Gregor378e1e72013-01-31 05:50:40 +0000422 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000423 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000424 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000425}
426
Fariborz Jahanian34999872010-11-13 21:53:34 +0000427void
428CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
429 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000430 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000431 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000432 Exp = E->getSubExpr();
433 assert(isa<CXXConstructExpr>(Exp) &&
434 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
435 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
436 const CXXConstructorDecl *CD = E->getConstructor();
437 RunCleanupsScope Scope(*this);
438
439 // If we require zero initialization before (or instead of) calling the
440 // constructor, as can be the case with a non-user-provided default
441 // constructor, emit the zero initialization now.
442 // FIXME. Do I still need this for a copy ctor synthesis?
443 if (E->requiresZeroInitialization())
444 EmitNullInitialization(Dest, E->getType());
445
Chandler Carruth858a5462010-11-15 13:54:43 +0000446 assert(!getContext().getAsConstantArrayType(E->getType())
447 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Nick Lewycky5d4a7552013-10-01 21:51:38 +0000448 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E->arg_begin(), E->arg_end());
Fariborz Jahanian34999872010-11-13 21:53:34 +0000449}
450
John McCall1e7fe752010-09-02 09:58:18 +0000451static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
452 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000453 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000454 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000455
John McCallb1c98a32011-05-16 01:05:12 +0000456 // No cookie is required if the operator new[] being used is the
457 // reserved placement operator new[].
458 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000459 return CharUnits::Zero();
460
John McCall6ec278d2011-01-27 09:37:56 +0000461 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000462}
463
John McCall7d166272011-05-15 07:14:44 +0000464static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
465 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000466 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000467 llvm::Value *&numElements,
468 llvm::Value *&sizeWithoutCookie) {
469 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000470
John McCall7d166272011-05-15 07:14:44 +0000471 if (!e->isArray()) {
472 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
473 sizeWithoutCookie
474 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
475 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000476 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000477
John McCall7d166272011-05-15 07:14:44 +0000478 // The width of size_t.
479 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
480
John McCall1e7fe752010-09-02 09:58:18 +0000481 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000482 llvm::APInt cookieSize(sizeWidth,
483 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000484
Anders Carlssona4d4c012009-09-23 16:07:23 +0000485 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000486 // We multiply the size of all dimensions for NumElements.
487 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000488 numElements = CGF.EmitScalarExpr(e->getArraySize());
489 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000490
John McCall7d166272011-05-15 07:14:44 +0000491 // The number of elements can be have an arbitrary integer type;
492 // essentially, we need to multiply it by a constant factor, add a
493 // cookie size, and verify that the result is representable as a
494 // size_t. That's just a gloss, though, and it's wrong in one
495 // important way: if the count is negative, it's an error even if
496 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000497 bool isSigned
498 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000499 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000500 = cast<llvm::IntegerType>(numElements->getType());
501 unsigned numElementsWidth = numElementsType->getBitWidth();
502
503 // Compute the constant factor.
504 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000505 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000506 = CGF.getContext().getAsConstantArrayType(type)) {
507 type = CAT->getElementType();
508 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000509 }
510
John McCall7d166272011-05-15 07:14:44 +0000511 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
512 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
513 typeSizeMultiplier *= arraySizeMultiplier;
514
515 // This will be a size_t.
516 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000517
Chris Lattner806941e2010-07-20 21:55:52 +0000518 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
519 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000520 if (llvm::ConstantInt *numElementsC =
521 dyn_cast<llvm::ConstantInt>(numElements)) {
522 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000523
John McCall7d166272011-05-15 07:14:44 +0000524 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000525
John McCall7d166272011-05-15 07:14:44 +0000526 // If 'count' was a negative number, it's an overflow.
527 if (isSigned && count.isNegative())
528 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000529
John McCall7d166272011-05-15 07:14:44 +0000530 // We want to do all this arithmetic in size_t. If numElements is
531 // wider than that, check whether it's already too big, and if so,
532 // overflow.
533 else if (numElementsWidth > sizeWidth &&
534 numElementsWidth - sizeWidth > count.countLeadingZeros())
535 hasAnyOverflow = true;
536
537 // Okay, compute a count at the right width.
538 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
539
Sebastian Redl92036472012-02-22 17:37:52 +0000540 // If there is a brace-initializer, we cannot allocate fewer elements than
541 // there are initializers. If we do, that's treated like an overflow.
542 if (adjustedCount.ult(minElements))
543 hasAnyOverflow = true;
544
John McCall7d166272011-05-15 07:14:44 +0000545 // Scale numElements by that. This might overflow, but we don't
546 // care because it only overflows if allocationSize does, too, and
547 // if that overflows then we shouldn't use this.
548 numElements = llvm::ConstantInt::get(CGF.SizeTy,
549 adjustedCount * arraySizeMultiplier);
550
551 // Compute the size before cookie, and track whether it overflowed.
552 bool overflow;
553 llvm::APInt allocationSize
554 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
555 hasAnyOverflow |= overflow;
556
557 // Add in the cookie, and check whether it's overflowed.
558 if (cookieSize != 0) {
559 // Save the current size without a cookie. This shouldn't be
560 // used if there was overflow.
561 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
562
563 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
564 hasAnyOverflow |= overflow;
565 }
566
567 // On overflow, produce a -1 so operator new will fail.
568 if (hasAnyOverflow) {
569 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
570 } else {
571 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
572 }
573
574 // Otherwise, we might need to use the overflow intrinsics.
575 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000576 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000577 // 1) if isSigned, we need to check whether numElements is negative;
578 // 2) if numElementsWidth > sizeWidth, we need to check whether
579 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000580 // 3) if minElements > 0, we need to check whether numElements is smaller
581 // than that.
582 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000583 // sizeWithoutCookie := numElements * typeSizeMultiplier
584 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000585 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000586 // size := sizeWithoutCookie + cookieSize
587 // and check whether it overflows.
588
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700589 llvm::Value *hasOverflow = nullptr;
John McCall7d166272011-05-15 07:14:44 +0000590
591 // If numElementsWidth > sizeWidth, then one way or another, we're
592 // going to have to do a comparison for (2), and this happens to
593 // take care of (1), too.
594 if (numElementsWidth > sizeWidth) {
595 llvm::APInt threshold(numElementsWidth, 1);
596 threshold <<= sizeWidth;
597
598 llvm::Value *thresholdV
599 = llvm::ConstantInt::get(numElementsType, threshold);
600
601 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
602 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
603
604 // Otherwise, if we're signed, we want to sext up to size_t.
605 } else if (isSigned) {
606 if (numElementsWidth < sizeWidth)
607 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
608
609 // If there's a non-1 type size multiplier, then we can do the
610 // signedness check at the same time as we do the multiply
611 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000612 // unsigned overflow. Otherwise, we have to do it here. But at least
613 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000614 if (typeSizeMultiplier == 1)
615 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000616 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000617
618 // Otherwise, zext up to size_t if necessary.
619 } else if (numElementsWidth < sizeWidth) {
620 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
621 }
622
623 assert(numElements->getType() == CGF.SizeTy);
624
Sebastian Redl92036472012-02-22 17:37:52 +0000625 if (minElements) {
626 // Don't allow allocation of fewer elements than we have initializers.
627 if (!hasOverflow) {
628 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
629 llvm::ConstantInt::get(CGF.SizeTy, minElements));
630 } else if (numElementsWidth > sizeWidth) {
631 // The other existing overflow subsumes this check.
632 // We do an unsigned comparison, since any signed value < -1 is
633 // taken care of either above or below.
634 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
635 CGF.Builder.CreateICmpULT(numElements,
636 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
637 }
638 }
639
John McCall7d166272011-05-15 07:14:44 +0000640 size = numElements;
641
642 // Multiply by the type size if necessary. This multiplier
643 // includes all the factors for nested arrays.
644 //
645 // This step also causes numElements to be scaled up by the
646 // nested-array factor if necessary. Overflow on this computation
647 // can be ignored because the result shouldn't be used if
648 // allocation fails.
649 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000650 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000651 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000652
653 llvm::Value *tsmV =
654 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
655 llvm::Value *result =
656 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
657
658 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
659 if (hasOverflow)
660 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
661 else
662 hasOverflow = overflowed;
663
664 size = CGF.Builder.CreateExtractValue(result, 0);
665
666 // Also scale up numElements by the array size multiplier.
667 if (arraySizeMultiplier != 1) {
668 // If the base element type size is 1, then we can re-use the
669 // multiply we just did.
670 if (typeSize.isOne()) {
671 assert(arraySizeMultiplier == typeSizeMultiplier);
672 numElements = size;
673
674 // Otherwise we need a separate multiply.
675 } else {
676 llvm::Value *asmV =
677 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
678 numElements = CGF.Builder.CreateMul(numElements, asmV);
679 }
680 }
681 } else {
682 // numElements doesn't need to be scaled.
683 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000684 }
685
John McCall7d166272011-05-15 07:14:44 +0000686 // Add in the cookie size if necessary.
687 if (cookieSize != 0) {
688 sizeWithoutCookie = size;
689
John McCall7d166272011-05-15 07:14:44 +0000690 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000691 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000692
693 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
694 llvm::Value *result =
695 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
696
697 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
698 if (hasOverflow)
699 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
700 else
701 hasOverflow = overflowed;
702
703 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000704 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000705
John McCall7d166272011-05-15 07:14:44 +0000706 // If we had any possibility of dynamic overflow, make a select to
707 // overwrite 'size' with an all-ones value, which should cause
708 // operator new to throw.
709 if (hasOverflow)
710 size = CGF.Builder.CreateSelect(hasOverflow,
711 llvm::Constant::getAllOnesValue(CGF.SizeTy),
712 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000713 }
John McCall1e7fe752010-09-02 09:58:18 +0000714
John McCall7d166272011-05-15 07:14:44 +0000715 if (cookieSize == 0)
716 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000717 else
John McCall7d166272011-05-15 07:14:44 +0000718 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000719
John McCall7d166272011-05-15 07:14:44 +0000720 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000721}
722
Sebastian Redl92036472012-02-22 17:37:52 +0000723static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
724 QualType AllocType, llvm::Value *NewPtr) {
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000725 // FIXME: Refactor with EmitExprAsInit.
Eli Friedmand7722d92011-12-03 02:13:40 +0000726 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall9d232c82013-03-07 21:37:08 +0000727 switch (CGF.getEvaluationKind(AllocType)) {
728 case TEK_Scalar:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700729 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
730 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000731 false);
John McCall9d232c82013-03-07 21:37:08 +0000732 return;
733 case TEK_Complex:
734 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
735 Alignment),
736 /*isInit*/ true);
737 return;
738 case TEK_Aggregate: {
John McCall558d2ab2010-09-15 10:14:12 +0000739 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000740 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000741 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000742 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000743 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000744 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000745 return;
John McCall558d2ab2010-09-15 10:14:12 +0000746 }
John McCall9d232c82013-03-07 21:37:08 +0000747 }
748 llvm_unreachable("bad evaluation kind");
Fariborz Jahanianef668722010-06-25 18:26:07 +0000749}
750
751void
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700752CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
753 QualType ElementType,
754 llvm::Value *BeginPtr,
755 llvm::Value *NumElements,
756 llvm::Value *AllocSizeWithoutCookie) {
757 // If we have a type with trivial initialization and no initializer,
758 // there's nothing to do.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000759 if (!E->hasInitializer())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700760 return;
John McCall19705672011-09-15 06:49:18 +0000761
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700762 llvm::Value *CurPtr = BeginPtr;
John McCall19705672011-09-15 06:49:18 +0000763
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700764 unsigned InitListElements = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000765
766 const Expr *Init = E->getInitializer();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700767 llvm::AllocaInst *EndOfInit = nullptr;
768 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
769 EHScopeStack::stable_iterator Cleanup;
770 llvm::Instruction *CleanupDominator = nullptr;
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000771
Sebastian Redl92036472012-02-22 17:37:52 +0000772 // If the initializer is an initializer list, first do the explicit elements.
773 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700774 InitListElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000775
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000776 // If this is a multi-dimensional array new, we will initialize multiple
777 // elements with each init list element.
778 QualType AllocType = E->getAllocatedType();
779 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
780 AllocType->getAsArrayTypeUnsafe())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700781 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000782 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700783 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
784 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000785 }
786
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700787 // Enter a partial-destruction Cleanup if necessary.
788 if (needsEHCleanup(DtorKind)) {
789 // In principle we could tell the Cleanup where we are more
Chad Rosier577fb5b2012-02-24 00:13:55 +0000790 // directly, but the control flow can get so varied here that it
791 // would actually be quite complex. Therefore we go through an
792 // alloca.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700793 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
794 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
795 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
796 getDestroyer(DtorKind));
797 Cleanup = EHStack.stable_begin();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000798 }
799
Sebastian Redl92036472012-02-22 17:37:52 +0000800 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000801 // Tell the cleanup that it needs to destroy up to this
802 // element. TODO: some of these stores can be trivially
803 // observed to be unnecessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700804 if (EndOfInit)
805 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
806 EndOfInit);
807 // FIXME: If the last initializer is an incomplete initializer list for
808 // an array, and we have an array filler, we can fold together the two
809 // initialization loops.
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000810 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700811 ILE->getInit(i)->getType(), CurPtr);
812 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redl92036472012-02-22 17:37:52 +0000813 }
814
815 // The remaining elements are filled with the array filler expression.
816 Init = ILE->getArrayFiller();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000817
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700818 // Extract the initializer for the individual array elements by pulling
819 // out the array filler from all the nested initializer lists. This avoids
820 // generating a nested loop for the initialization.
821 while (Init && Init->getType()->isConstantArrayType()) {
822 auto *SubILE = dyn_cast<InitListExpr>(Init);
823 if (!SubILE)
824 break;
825 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
826 Init = SubILE->getArrayFiller();
827 }
828
829 // Switch back to initializing one base element at a time.
830 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redl92036472012-02-22 17:37:52 +0000831 }
832
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700833 // Attempt to perform zero-initialization using memset.
834 auto TryMemsetInitialization = [&]() -> bool {
835 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
836 // we can initialize with a memset to -1.
837 if (!CGM.getTypes().isZeroInitializable(ElementType))
838 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700839
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700840 // Optimization: since zero initialization will just set the memory
841 // to all zeroes, generate a single memset to do it in one shot.
842
843 // Subtract out the size of any elements we've already initialized.
844 auto *RemainingSize = AllocSizeWithoutCookie;
845 if (InitListElements) {
846 // We know this can't overflow; we check this when doing the allocation.
847 auto *InitializedSize = llvm::ConstantInt::get(
848 RemainingSize->getType(),
849 getContext().getTypeSizeInChars(ElementType).getQuantity() *
850 InitListElements);
851 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
852 }
853
854 // Create the memset.
855 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
856 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
857 Alignment.getQuantity(), false);
858 return true;
859 };
860
861 // If all elements have already been initialized, skip any further
862 // initialization.
863 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
864 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
865 // If there was a Cleanup, deactivate it.
866 if (CleanupDominator)
867 DeactivateCleanupBlock(Cleanup, CleanupDominator);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700868 return;
869 }
870
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700871 assert(Init && "have trailing elements to initialize but no initializer");
872
873 // If this is a constructor call, try to optimize it out, and failing that
874 // emit a single loop to initialize all remaining elements.
875 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
876 CXXConstructorDecl *Ctor = CCE->getConstructor();
877 if (Ctor->isTrivial()) {
878 // If new expression did not specify value-initialization, then there
879 // is no initialization.
880 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
881 return;
882
883 if (TryMemsetInitialization())
884 return;
885 }
886
887 // Store the new Cleanup position for irregular Cleanups.
888 //
889 // FIXME: Share this cleanup with the constructor call emission rather than
890 // having it create a cleanup of its own.
891 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
892
893 // Emit a constructor call loop to initialize the remaining elements.
894 if (InitListElements)
895 NumElements = Builder.CreateSub(
896 NumElements,
897 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
898 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr,
899 CCE->arg_begin(), CCE->arg_end(),
900 CCE->requiresZeroInitialization());
901 return;
902 }
903
904 // If this is value-initialization, we can usually use memset.
905 ImplicitValueInitExpr IVIE(ElementType);
906 if (isa<ImplicitValueInitExpr>(Init)) {
907 if (TryMemsetInitialization())
908 return;
909
910 // Switch to an ImplicitValueInitExpr for the element type. This handles
911 // only one case: multidimensional array new of pointers to members. In
912 // all other cases, we already have an initializer for the array element.
913 Init = &IVIE;
914 }
915
916 // At this point we should have found an initializer for the individual
917 // elements of the array.
918 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
919 "got wrong type of element to initialize");
920
921 // If we have an empty initializer list, we can usually use memset.
922 if (auto *ILE = dyn_cast<InitListExpr>(Init))
923 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
924 return;
925
926 // Create the loop blocks.
927 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
928 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
929 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
930
931 // Find the end of the array, hoisted out of the loop.
932 llvm::Value *EndPtr =
933 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall19705672011-09-15 06:49:18 +0000934
Sebastian Redl92036472012-02-22 17:37:52 +0000935 // If the number of elements isn't constant, we have to now check if there is
936 // anything left to initialize.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700937 if (!ConstNum) {
938 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall19705672011-09-15 06:49:18 +0000939 "array.isempty");
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700940 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall19705672011-09-15 06:49:18 +0000941 }
942
943 // Enter the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700944 EmitBlock(LoopBB);
John McCall19705672011-09-15 06:49:18 +0000945
946 // Set up the current-element phi.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700947 llvm::PHINode *CurPtrPhi =
948 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
949 CurPtrPhi->addIncoming(CurPtr, EntryBB);
950 CurPtr = CurPtrPhi;
John McCall19705672011-09-15 06:49:18 +0000951
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700952 // Store the new Cleanup position for irregular Cleanups.
953 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosier577fb5b2012-02-24 00:13:55 +0000954
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700955 // Enter a partial-destruction Cleanup if necessary.
956 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
957 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
958 getDestroyer(DtorKind));
959 Cleanup = EHStack.stable_begin();
960 CleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000961 }
962
963 // Emit the initializer into this element.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700964 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall19705672011-09-15 06:49:18 +0000965
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700966 // Leave the Cleanup if we entered one.
967 if (CleanupDominator) {
968 DeactivateCleanupBlock(Cleanup, CleanupDominator);
969 CleanupDominator->eraseFromParent();
John McCall6f103ba2011-11-10 10:43:54 +0000970 }
John McCall19705672011-09-15 06:49:18 +0000971
Stephen Hines651f13c2014-04-23 16:59:28 -0700972 // Advance to the next element by adjusting the pointer type as necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700973 llvm::Value *NextPtr =
974 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
975
John McCall19705672011-09-15 06:49:18 +0000976 // Check whether we've gotten to the end of the array and, if so,
977 // exit the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700978 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
979 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
980 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall19705672011-09-15 06:49:18 +0000981
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700982 EmitBlock(ContBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000983}
984
Anders Carlssona4d4c012009-09-23 16:07:23 +0000985static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000986 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000987 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000988 llvm::Value *NumElements,
989 llvm::Value *AllocSizeWithoutCookie) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700990 if (E->isArray())
991 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
992 AllocSizeWithoutCookie);
993 else if (const Expr *Init = E->getInitializer())
994 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000995}
996
Richard Smithddcff1b2013-07-21 23:12:18 +0000997/// Emit a call to an operator new or operator delete function, as implicitly
998/// created by new-expressions and delete-expressions.
999static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1000 const FunctionDecl *Callee,
1001 const FunctionProtoType *CalleeType,
1002 const CallArgList &Args) {
1003 llvm::Instruction *CallOrInvoke;
Richard Smith060cb4a2013-07-29 20:14:16 +00001004 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smithddcff1b2013-07-21 23:12:18 +00001005 RValue RV =
1006 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith060cb4a2013-07-29 20:14:16 +00001007 CalleeAddr, ReturnValueSlot(), Args,
Richard Smithddcff1b2013-07-21 23:12:18 +00001008 Callee, &CallOrInvoke);
1009
1010 /// C++1y [expr.new]p10:
1011 /// [In a new-expression,] an implementation is allowed to omit a call
1012 /// to a replaceable global allocation function.
1013 ///
1014 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola87017a72013-10-22 14:23:09 +00001015 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith060cb4a2013-07-29 20:14:16 +00001016 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola87017a72013-10-22 14:23:09 +00001017 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smithddcff1b2013-07-21 23:12:18 +00001018 // FIXME: Add addAttribute to CallSite.
1019 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1020 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1021 llvm::Attribute::Builtin);
1022 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1023 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1024 llvm::Attribute::Builtin);
1025 else
1026 llvm_unreachable("unexpected kind of call instruction");
1027 }
1028
1029 return RV;
1030}
1031
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001032RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1033 const Expr *Arg,
1034 bool IsDelete) {
1035 CallArgList Args;
1036 const Stmt *ArgS = Arg;
1037 EmitCallArgs(Args, *Type->param_type_begin(),
1038 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1039 // Find the allocation or deallocation function that we're calling.
1040 ASTContext &Ctx = getContext();
1041 DeclarationName Name = Ctx.DeclarationNames
1042 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1043 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1044 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1045 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1046 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1047 llvm_unreachable("predeclared global operator new/delete is missing");
1048}
1049
John McCall7d8647f2010-09-14 07:57:04 +00001050namespace {
1051 /// A cleanup to call the given 'operator delete' function upon
1052 /// abnormal exit from a new expression.
1053 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1054 size_t NumPlacementArgs;
1055 const FunctionDecl *OperatorDelete;
1056 llvm::Value *Ptr;
1057 llvm::Value *AllocSize;
1058
1059 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1060
1061 public:
1062 static size_t getExtraSize(size_t NumPlacementArgs) {
1063 return NumPlacementArgs * sizeof(RValue);
1064 }
1065
1066 CallDeleteDuringNew(size_t NumPlacementArgs,
1067 const FunctionDecl *OperatorDelete,
1068 llvm::Value *Ptr,
1069 llvm::Value *AllocSize)
1070 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1071 Ptr(Ptr), AllocSize(AllocSize) {}
1072
1073 void setPlacementArg(unsigned I, RValue Arg) {
1074 assert(I < NumPlacementArgs && "index out of range");
1075 getPlacementArgs()[I] = Arg;
1076 }
1077
Stephen Hines651f13c2014-04-23 16:59:28 -07001078 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7d8647f2010-09-14 07:57:04 +00001079 const FunctionProtoType *FPT
1080 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001081 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1082 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001083
1084 CallArgList DeleteArgs;
1085
1086 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001087 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001088 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001089
1090 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001091 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001092 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001093
1094 // Pass the rest of the arguments, which must match exactly.
1095 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001096 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001097
1098 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001099 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7d8647f2010-09-14 07:57:04 +00001100 }
1101 };
John McCall3019c442010-09-17 00:50:28 +00001102
1103 /// A cleanup to call the given 'operator delete' function upon
1104 /// abnormal exit from a new expression when the new expression is
1105 /// conditional.
1106 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1107 size_t NumPlacementArgs;
1108 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001109 DominatingValue<RValue>::saved_type Ptr;
1110 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001111
John McCall804b8072011-01-28 10:53:53 +00001112 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1113 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001114 }
1115
1116 public:
1117 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001118 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001119 }
1120
1121 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1122 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001123 DominatingValue<RValue>::saved_type Ptr,
1124 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001125 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1126 Ptr(Ptr), AllocSize(AllocSize) {}
1127
John McCall804b8072011-01-28 10:53:53 +00001128 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001129 assert(I < NumPlacementArgs && "index out of range");
1130 getPlacementArgs()[I] = Arg;
1131 }
1132
Stephen Hines651f13c2014-04-23 16:59:28 -07001133 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall3019c442010-09-17 00:50:28 +00001134 const FunctionProtoType *FPT
1135 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001136 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1137 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall3019c442010-09-17 00:50:28 +00001138
1139 CallArgList DeleteArgs;
1140
1141 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001142 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001143 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001144
1145 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001146 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001147 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001148 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001149 }
1150
1151 // Pass the rest of the arguments, which must match exactly.
1152 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001153 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001154 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001155 }
1156
1157 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001158 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall3019c442010-09-17 00:50:28 +00001159 }
1160 };
1161}
1162
1163/// Enter a cleanup to call 'operator delete' if the initializer in a
1164/// new-expression throws.
1165static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1166 const CXXNewExpr *E,
1167 llvm::Value *NewPtr,
1168 llvm::Value *AllocSize,
1169 const CallArgList &NewArgs) {
1170 // If we're not inside a conditional branch, then the cleanup will
1171 // dominate and we can do the easier (and more efficient) thing.
1172 if (!CGF.isInConditionalBranch()) {
1173 CallDeleteDuringNew *Cleanup = CGF.EHStack
1174 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1175 E->getNumPlacementArgs(),
1176 E->getOperatorDelete(),
1177 NewPtr, AllocSize);
1178 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001179 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001180
1181 return;
1182 }
1183
1184 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001185 DominatingValue<RValue>::saved_type SavedNewPtr =
1186 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1187 DominatingValue<RValue>::saved_type SavedAllocSize =
1188 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001189
1190 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001191 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001192 E->getNumPlacementArgs(),
1193 E->getOperatorDelete(),
1194 SavedNewPtr,
1195 SavedAllocSize);
1196 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001197 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001198 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001199
John McCall6f103ba2011-11-10 10:43:54 +00001200 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001201}
1202
Anders Carlsson16d81b82009-09-22 22:53:17 +00001203llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001204 // The element type being allocated.
1205 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001206
John McCallc2f3e7f2011-03-07 03:12:35 +00001207 // 1. Build a call to the allocation function.
1208 FunctionDecl *allocator = E->getOperatorNew();
1209 const FunctionProtoType *allocatorType =
1210 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001211
John McCallc2f3e7f2011-03-07 03:12:35 +00001212 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001213
1214 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001215 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001216
Sebastian Redl92036472012-02-22 17:37:52 +00001217 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1218 unsigned minElements = 0;
1219 if (E->isArray() && E->hasInitializer()) {
1220 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1221 minElements = ILE->getNumInits();
1222 }
1223
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001224 llvm::Value *numElements = nullptr;
1225 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCallc2f3e7f2011-03-07 03:12:35 +00001226 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001227 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1228 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001229
Eli Friedman04c9a492011-05-02 17:57:46 +00001230 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001231
Anders Carlsson16d81b82009-09-22 22:53:17 +00001232 // We start at 1 here because the first argument (the allocation size)
1233 // has already been emitted.
Stephen Hines651f13c2014-04-23 16:59:28 -07001234 EmitCallArgs(allocatorArgs, allocatorType->isVariadic(),
1235 allocatorType->param_type_begin() + 1,
1236 allocatorType->param_type_end(), E->placement_arg_begin(),
1237 E->placement_arg_end());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001238
John McCallb1c98a32011-05-16 01:05:12 +00001239 // Emit the allocation call. If the allocator is a global placement
1240 // operator, just "inline" it directly.
1241 RValue RV;
1242 if (allocator->isReservedGlobalPlacementOperator()) {
1243 assert(allocatorArgs.size() == 2);
1244 RV = allocatorArgs[1].RV;
1245 // TODO: kill any unnecessary computations done for the size
1246 // argument.
1247 } else {
Richard Smithddcff1b2013-07-21 23:12:18 +00001248 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCallb1c98a32011-05-16 01:05:12 +00001249 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001250
John McCallc2f3e7f2011-03-07 03:12:35 +00001251 // Emit a null check on the allocation result if the allocation
1252 // function is allowed to return null (because it has a non-throwing
1253 // exception spec; for this part, we inline
1254 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1255 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001256 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001257 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001258
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001259 llvm::BasicBlock *nullCheckBB = nullptr;
1260 llvm::BasicBlock *contBB = nullptr;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001261
John McCallc2f3e7f2011-03-07 03:12:35 +00001262 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001263 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001264
John McCalla7f633f2011-03-07 01:52:56 +00001265 // The null-check means that the initializer is conditionally
1266 // evaluated.
1267 ConditionalEvaluation conditional(*this);
1268
John McCallc2f3e7f2011-03-07 03:12:35 +00001269 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001270 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001271
1272 nullCheckBB = Builder.GetInsertBlock();
1273 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1274 contBB = createBasicBlock("new.cont");
1275
1276 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1277 Builder.CreateCondBr(isNull, contBB, notNullBB);
1278 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001279 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001280
John McCall7d8647f2010-09-14 07:57:04 +00001281 // If there's an operator delete, enter a cleanup to call it if an
1282 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001283 EHScopeStack::stable_iterator operatorDeleteCleanup;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001284 llvm::Instruction *cleanupDominator = nullptr;
John McCallb1c98a32011-05-16 01:05:12 +00001285 if (E->getOperatorDelete() &&
1286 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001287 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1288 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001289 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001290 }
1291
Eli Friedman576cf172011-09-06 18:53:03 +00001292 assert((allocSize == allocSizeWithoutCookie) ==
1293 CalculateCookiePadding(*this, E).isZero());
1294 if (allocSize != allocSizeWithoutCookie) {
1295 assert(E->isArray());
1296 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1297 numElements,
1298 E, allocType);
1299 }
1300
Chris Lattner2acc6e32011-07-18 04:24:23 +00001301 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001302 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1303 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001304
John McCall19705672011-09-15 06:49:18 +00001305 EmitNewInitializer(*this, E, allocType, result, numElements,
1306 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001307 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001308 // NewPtr is a pointer to the base element type. If we're
1309 // allocating an array of arrays, we'll need to cast back to the
1310 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001311 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001312 if (result->getType() != resultType)
1313 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001314 }
John McCall7d8647f2010-09-14 07:57:04 +00001315
1316 // Deactivate the 'operator delete' cleanup if we finished
1317 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001318 if (operatorDeleteCleanup.isValid()) {
1319 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1320 cleanupDominator->eraseFromParent();
1321 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001322
John McCallc2f3e7f2011-03-07 03:12:35 +00001323 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001324 conditional.end(*this);
1325
John McCallc2f3e7f2011-03-07 03:12:35 +00001326 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1327 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001328
Jay Foadbbf3bac2011-03-30 11:28:58 +00001329 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001330 PHI->addIncoming(result, notNullBB);
1331 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1332 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001333
John McCallc2f3e7f2011-03-07 03:12:35 +00001334 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001335 }
John McCall1e7fe752010-09-02 09:58:18 +00001336
John McCallc2f3e7f2011-03-07 03:12:35 +00001337 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001338}
1339
Eli Friedman5fe05982009-11-18 00:50:08 +00001340void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1341 llvm::Value *Ptr,
1342 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001343 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1344
Eli Friedman5fe05982009-11-18 00:50:08 +00001345 const FunctionProtoType *DeleteFTy =
1346 DeleteFD->getType()->getAs<FunctionProtoType>();
1347
1348 CallArgList DeleteArgs;
1349
Anders Carlsson871d0782009-12-13 20:04:38 +00001350 // Check if we need to pass the size to the delete operator.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001351 llvm::Value *Size = nullptr;
Anders Carlsson871d0782009-12-13 20:04:38 +00001352 QualType SizeTy;
Stephen Hines651f13c2014-04-23 16:59:28 -07001353 if (DeleteFTy->getNumParams() == 2) {
1354 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001355 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1356 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1357 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001358 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001359
1360 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedman5fe05982009-11-18 00:50:08 +00001361 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001362 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001363
Anders Carlsson871d0782009-12-13 20:04:38 +00001364 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001365 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001366
1367 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001368 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedman5fe05982009-11-18 00:50:08 +00001369}
1370
John McCall1e7fe752010-09-02 09:58:18 +00001371namespace {
1372 /// Calls the given 'operator delete' on a single object.
1373 struct CallObjectDelete : EHScopeStack::Cleanup {
1374 llvm::Value *Ptr;
1375 const FunctionDecl *OperatorDelete;
1376 QualType ElementType;
1377
1378 CallObjectDelete(llvm::Value *Ptr,
1379 const FunctionDecl *OperatorDelete,
1380 QualType ElementType)
1381 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1382
Stephen Hines651f13c2014-04-23 16:59:28 -07001383 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001384 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1385 }
1386 };
1387}
1388
1389/// Emit the code for deleting a single object.
1390static void EmitObjectDelete(CodeGenFunction &CGF,
1391 const FunctionDecl *OperatorDelete,
1392 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001393 QualType ElementType,
1394 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001395 // Find the destructor for the type, if applicable. If the
1396 // destructor is virtual, we'll just emit the vcall and return.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001397 const CXXDestructorDecl *Dtor = nullptr;
John McCall1e7fe752010-09-02 09:58:18 +00001398 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1399 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001400 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001401 Dtor = RD->getDestructor();
1402
1403 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001404 if (UseGlobalDelete) {
1405 // If we're supposed to call the global delete, make sure we do so
1406 // even if the destructor throws.
John McCallecd03b42012-09-25 10:10:39 +00001407
1408 // Derive the complete-object pointer, which is what we need
1409 // to pass to the deallocation function.
1410 llvm::Value *completePtr =
1411 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1412
Douglas Gregora8b20f72011-07-13 00:54:47 +00001413 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCallecd03b42012-09-25 10:10:39 +00001414 completePtr, OperatorDelete,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001415 ElementType);
1416 }
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001417
Richard Smith4def70d2012-10-09 19:52:38 +00001418 // FIXME: Provide a source location here.
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +00001419 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1420 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType,
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001421 SourceLocation(), Ptr);
John McCall1e7fe752010-09-02 09:58:18 +00001422
Douglas Gregora8b20f72011-07-13 00:54:47 +00001423 if (UseGlobalDelete) {
1424 CGF.PopCleanupBlock();
1425 }
1426
John McCall1e7fe752010-09-02 09:58:18 +00001427 return;
1428 }
1429 }
1430 }
1431
1432 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001433 // This doesn't have to a conditional cleanup because we're going
1434 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001435 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1436 Ptr, OperatorDelete, ElementType);
1437
1438 if (Dtor)
1439 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001440 /*ForVirtualBase=*/false,
1441 /*Delegating=*/false,
1442 Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001443 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001444 ElementType->isObjCLifetimeType()) {
1445 switch (ElementType.getObjCLifetime()) {
1446 case Qualifiers::OCL_None:
1447 case Qualifiers::OCL_ExplicitNone:
1448 case Qualifiers::OCL_Autoreleasing:
1449 break;
John McCall1e7fe752010-09-02 09:58:18 +00001450
John McCallf85e1932011-06-15 23:02:42 +00001451 case Qualifiers::OCL_Strong: {
1452 // Load the pointer value.
1453 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1454 ElementType.isVolatileQualified());
1455
John McCall5b07e802013-03-13 03:10:54 +00001456 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001457 break;
1458 }
1459
1460 case Qualifiers::OCL_Weak:
1461 CGF.EmitARCDestroyWeak(Ptr);
1462 break;
1463 }
1464 }
1465
John McCall1e7fe752010-09-02 09:58:18 +00001466 CGF.PopCleanupBlock();
1467}
1468
1469namespace {
1470 /// Calls the given 'operator delete' on an array of objects.
1471 struct CallArrayDelete : EHScopeStack::Cleanup {
1472 llvm::Value *Ptr;
1473 const FunctionDecl *OperatorDelete;
1474 llvm::Value *NumElements;
1475 QualType ElementType;
1476 CharUnits CookieSize;
1477
1478 CallArrayDelete(llvm::Value *Ptr,
1479 const FunctionDecl *OperatorDelete,
1480 llvm::Value *NumElements,
1481 QualType ElementType,
1482 CharUnits CookieSize)
1483 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1484 ElementType(ElementType), CookieSize(CookieSize) {}
1485
Stephen Hines651f13c2014-04-23 16:59:28 -07001486 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001487 const FunctionProtoType *DeleteFTy =
1488 OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001489 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall1e7fe752010-09-02 09:58:18 +00001490
1491 CallArgList Args;
1492
1493 // Pass the pointer as the first argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001494 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall1e7fe752010-09-02 09:58:18 +00001495 llvm::Value *DeletePtr
1496 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001497 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001498
1499 // Pass the original requested size as the second argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001500 if (DeleteFTy->getNumParams() == 2) {
1501 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001502 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001503 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1504
1505 CharUnits ElementTypeSize =
1506 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1507
1508 // The size of an element, multiplied by the number of elements.
1509 llvm::Value *Size
1510 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1511 Size = CGF.Builder.CreateMul(Size, NumElements);
1512
1513 // Plus the size of the cookie if applicable.
1514 if (!CookieSize.isZero()) {
1515 llvm::Value *CookieSizeV
1516 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1517 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1518 }
1519
Eli Friedman04c9a492011-05-02 17:57:46 +00001520 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001521 }
1522
1523 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001524 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall1e7fe752010-09-02 09:58:18 +00001525 }
1526 };
1527}
1528
1529/// Emit the code for deleting an array of objects.
1530static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001531 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001532 llvm::Value *deletedPtr,
1533 QualType elementType) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001534 llvm::Value *numElements = nullptr;
1535 llvm::Value *allocatedPtr = nullptr;
John McCall7cfd76c2011-07-13 01:41:37 +00001536 CharUnits cookieSize;
1537 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1538 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001539
John McCall7cfd76c2011-07-13 01:41:37 +00001540 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001541
1542 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001543 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001544 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001545 allocatedPtr, operatorDelete,
1546 numElements, elementType,
1547 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001548
John McCall7cfd76c2011-07-13 01:41:37 +00001549 // Destroy the elements.
1550 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1551 assert(numElements && "no element count for a type with a destructor!");
1552
John McCall7cfd76c2011-07-13 01:41:37 +00001553 llvm::Value *arrayEnd =
1554 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001555
1556 // Note that it is legal to allocate a zero-length array, and we
1557 // can never fold the check away because the length should always
1558 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001559 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1560 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001561 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001562 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001563 }
1564
John McCall7cfd76c2011-07-13 01:41:37 +00001565 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001566 CGF.PopCleanupBlock();
1567}
1568
Anders Carlsson16d81b82009-09-22 22:53:17 +00001569void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001570 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001571 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001572
1573 // Null check the pointer.
1574 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1575 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1576
Anders Carlssonb9241242011-04-11 00:30:07 +00001577 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001578
1579 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1580 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001581
John McCall1e7fe752010-09-02 09:58:18 +00001582 // We might be deleting a pointer to array. If so, GEP down to the
1583 // first non-array element.
1584 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1585 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1586 if (DeleteTy->isConstantArrayType()) {
1587 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001588 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001589
1590 GEP.push_back(Zero); // point at the outermost array
1591
1592 // For each layer of array type we're pointing at:
1593 while (const ConstantArrayType *Arr
1594 = getContext().getAsConstantArrayType(DeleteTy)) {
1595 // 1. Unpeel the array type.
1596 DeleteTy = Arr->getElementType();
1597
1598 // 2. GEP to the first element of the array.
1599 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001600 }
John McCall1e7fe752010-09-02 09:58:18 +00001601
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001602 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001603 }
1604
Douglas Gregoreede61a2010-09-02 17:38:50 +00001605 assert(ConvertTypeForMem(DeleteTy) ==
1606 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001607
1608 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001609 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001610 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001611 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1612 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001613 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001614
Anders Carlsson16d81b82009-09-22 22:53:17 +00001615 EmitBlock(DeleteEnd);
1616}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001617
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001618static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001619 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001620 // Get the vtable pointer.
1621 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1622
1623 // C++ [expr.typeid]p2:
1624 // If the glvalue expression is obtained by applying the unary * operator to
1625 // a pointer and the pointer is a null pointer value, the typeid expression
1626 // throws the std::bad_typeid exception.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001627 bool IsDeref = false;
1628 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens()))
1629 if (UO->getOpcode() == UO_Deref)
1630 IsDeref = true;
1631
1632 QualType SrcRecordTy = E->getType();
1633 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(IsDeref, SrcRecordTy)) {
1634 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001635 CGF.createBasicBlock("typeid.bad_typeid");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001636 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001637
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001638 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1639 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001640
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001641 CGF.EmitBlock(BadTypeidBlock);
1642 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1643 CGF.EmitBlock(EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001644 }
1645
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001646 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1647 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001648}
1649
John McCall3ad32c82011-01-28 08:37:24 +00001650llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001651 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001652 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001653
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001654 if (E->isTypeOperand()) {
David Majnemerfe16aa32013-09-27 07:04:31 +00001655 llvm::Constant *TypeInfo =
1656 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001657 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001658 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001659
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001660 // C++ [expr.typeid]p2:
1661 // When typeid is applied to a glvalue expression whose type is a
1662 // polymorphic class type, the result refers to a std::type_info object
1663 // representing the type of the most derived object (that is, the dynamic
1664 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001665 if (E->isPotentiallyEvaluated())
1666 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1667 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001668
1669 QualType OperandTy = E->getExprOperand()->getType();
1670 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1671 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001672}
Mike Stumpc849c052009-11-16 06:50:58 +00001673
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001674static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1675 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001676 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001677 if (DestTy->isPointerType())
1678 return llvm::Constant::getNullValue(DestLTy);
1679
1680 /// C++ [expr.dynamic.cast]p9:
1681 /// A failed cast to reference type throws std::bad_cast
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001682 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1683 return nullptr;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001684
1685 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1686 return llvm::UndefValue::get(DestLTy);
1687}
1688
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001689llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001690 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001691 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001692
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001693 if (DCE->isAlwaysNull())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001694 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1695 return T;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001696
1697 QualType SrcTy = DCE->getSubExpr()->getType();
1698
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001699 // C++ [expr.dynamic.cast]p7:
1700 // If T is "pointer to cv void," then the result is a pointer to the most
1701 // derived object pointed to by v.
1702 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1703
1704 bool isDynamicCastToVoid;
1705 QualType SrcRecordTy;
1706 QualType DestRecordTy;
1707 if (DestPTy) {
1708 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1709 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1710 DestRecordTy = DestPTy->getPointeeType();
1711 } else {
1712 isDynamicCastToVoid = false;
1713 SrcRecordTy = SrcTy;
1714 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1715 }
1716
1717 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1718
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001719 // C++ [expr.dynamic.cast]p4:
1720 // If the value of v is a null pointer value in the pointer case, the result
1721 // is the null pointer value of type T.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001722 bool ShouldNullCheckSrcValue =
1723 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1724 SrcRecordTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001725
1726 llvm::BasicBlock *CastNull = nullptr;
1727 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001728 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001729
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001730 if (ShouldNullCheckSrcValue) {
1731 CastNull = createBasicBlock("dynamic_cast.null");
1732 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1733
1734 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1735 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1736 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001737 }
1738
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001739 if (isDynamicCastToVoid) {
1740 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1741 DestTy);
1742 } else {
1743 assert(DestRecordTy->isRecordType() &&
1744 "destination type must be a record type!");
1745 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1746 DestTy, DestRecordTy, CastEnd);
1747 }
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001748
1749 if (ShouldNullCheckSrcValue) {
1750 EmitBranch(CastEnd);
1751
1752 EmitBlock(CastNull);
1753 EmitBranch(CastEnd);
1754 }
1755
1756 EmitBlock(CastEnd);
1757
1758 if (ShouldNullCheckSrcValue) {
1759 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1760 PHI->addIncoming(Value, CastNotNull);
1761 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1762
1763 Value = PHI;
1764 }
1765
1766 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001767}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001768
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001769void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001770 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001771 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1772 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001773
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001774 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1775 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1776 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001777 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001778 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001779
David Blaikie581deb32012-06-06 20:45:41 +00001780 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001781 ArrayRef<VarDecl *> ArrayIndexes;
1782 if (CurField->getType()->isArrayType())
1783 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001784 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001785 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001786}