blob: 12b953b333439105268425201cb7342ca617b31a [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000021#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000022#include "llvm/Support/CallSite.h"
23
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Anders Carlsson27da15b2010-01-01 20:29:01 +000027RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
Richard Smithe30752c2012-10-09 19:52:38 +000028 SourceLocation CallLoc,
Anders Carlsson27da15b2010-01-01 20:29:01 +000029 llvm::Value *Callee,
30 ReturnValueSlot ReturnValue,
31 llvm::Value *This,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000032 llvm::Value *ImplicitParam,
33 QualType ImplicitParamTy,
Anders Carlsson27da15b2010-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 Smith69d0d262012-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 Smith4d3110a2012-10-25 02:14:12 +000042 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
43 : TCK_MemberCall,
44 CallLoc, This, getContext().getRecordType(MD->getParent()));
Richard Smith69d0d262012-08-24 00:54:33 +000045
Anders Carlsson27da15b2010-01-01 20:29:01 +000046 CallArgList Args;
47
48 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000049 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000050
Timur Iskhodzhanovee6bc532013-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 Carlssone36a6b32010-01-02 01:01:18 +000054 }
John McCalla729c622012-02-17 03:33:10 +000055
56 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssone36a6b32010-01-02 01:01:18 +000058
John McCalla729c622012-02-17 03:33:10 +000059 // And the rest of the call args.
Anders Carlsson27da15b2010-01-01 20:29:01 +000060 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
61
John McCall8dda7b22012-07-07 06:41:13 +000062 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000063 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000064}
65
Rafael Espindola3b33c4e2012-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 Pichet64225792011-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 Carlsson27da15b2010-01-01 20:29:01 +000076RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
77 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +000078 const Expr *callee = CE->getCallee()->IgnoreParens();
79
80 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +000081 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +000082
83 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-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 Collingbourneb453cd62013-10-20 21:29:19 +000090 CE->getLocStart(), ReturnValue, CE->arg_begin(),
91 CE->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +000092 }
Anders Carlsson27da15b2010-01-01 20:29:01 +000093
John McCall0d635f52010-09-03 01:26:39 +000094 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000095 const Expr *Base = ME->getBase();
96 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000097
Rafael Espindola3b33c4e2012-06-28 14:28:57 +000098 const CXXMethodDecl *DevirtualizedMethod = NULL;
Benjamin Kramer7463ed72013-08-25 22:46:27 +000099 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-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.
114 DevirtualizedMethod = NULL;
115 }
Rafael Espindolab27564a2012-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 &&
122 DevirtualizedMethod->getResultType().getCanonicalType() !=
123 MD->getResultType().getCanonicalType())
Rafael Espindoladebc71c2012-06-28 15:11:39 +0000124 DevirtualizedMethod = NULL;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000125 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000126
Anders Carlsson27da15b2010-01-01 20:29:01 +0000127 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000128 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000129 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000130 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000131 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000132
Anders Carlsson27da15b2010-01-01 20:29:01 +0000133
John McCall0d635f52010-09-03 01:26:39 +0000134 if (MD->isTrivial()) {
135 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000136 if (isa<CXXConstructorDecl>(MD) &&
137 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
138 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000139
Sebastian Redl22653ba2011-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 Pichet64225792011-01-18 05:04:39 +0000143 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000144 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000145 return RValue::get(This);
146 }
147
148 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000149 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
150 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-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 Carlsson27da15b2010-01-01 20:29:01 +0000157 }
158
John McCall0d635f52010-09-03 01:26:39 +0000159 // Compute the function type we're calling.
Eli Friedmanade60972012-10-25 00:12:49 +0000160 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Francois Pichet64225792011-01-18 05:04:39 +0000161 const CGFunctionInfo *FInfo = 0;
Eli Friedmanade60972012-10-25 00:12:49 +0000162 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
163 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCalla729c622012-02-17 03:33:10 +0000164 Dtor_Complete);
Eli Friedmanade60972012-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 Pichet64225792011-01-18 05:04:39 +0000168 else
Eli Friedmanade60972012-10-25 00:12:49 +0000169 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000170
Reid Klecknere7de47e2013-07-22 13:51:44 +0000171 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000172
Anders Carlsson27da15b2010-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 Espindola3b33c4e2012-06-28 14:28:57 +0000179 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000180 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000181
John McCall0d635f52010-09-03 01:26:39 +0000182 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-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 McCall0d635f52010-09-03 01:26:39 +0000186 if (UseVirtualCall) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000187 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
188 CE->getExprLoc(), This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000189 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000190 if (getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000191 MD->isVirtual() &&
192 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000193 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000194 else if (!DevirtualizedMethod)
Reid Klecknere7de47e2013-07-22 13:51:44 +0000195 Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000196 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000197 const CXXDestructorDecl *DDtor =
198 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000199 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
200 }
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000201 EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
202 /*ImplicitParam=*/0, QualType(), 0, 0);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000203 }
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000204 return RValue::get(0);
205 }
206
207 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000208 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000209 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000210 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000211 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000212 if (getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000213 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000214 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000215 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000216 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000217 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000218 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000219 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000220 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 }
222
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000223 if (MD->isVirtual())
224 This = CGM.getCXXABI().adjustThisArgumentForVirtualCall(*this, MD, This);
225
Richard Smithe30752c2012-10-09 19:52:38 +0000226 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000227 /*ImplicitParam=*/0, QualType(),
228 CE->arg_begin(), CE->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000229}
230
231RValue
232CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
233 ReturnValueSlot ReturnValue) {
234 const BinaryOperator *BO =
235 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
236 const Expr *BaseExpr = BO->getLHS();
237 const Expr *MemFnExpr = BO->getRHS();
238
239 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000240 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000241
Anders Carlsson27da15b2010-01-01 20:29:01 +0000242 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000243 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000244 const CXXRecordDecl *RD =
245 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
246
Anders Carlsson27da15b2010-01-01 20:29:01 +0000247 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000248 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000249
250 // Emit the 'this' pointer.
251 llvm::Value *This;
252
John McCalle3027922010-08-25 11:45:40 +0000253 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000254 This = EmitScalarExpr(BaseExpr);
255 else
256 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000257
Richard Smithe30752c2012-10-09 19:52:38 +0000258 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
259 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000260
John McCall475999d2010-08-22 00:05:51 +0000261 // Ask the ABI to load the callee. Note that This is modified.
262 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000263 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000264
Anders Carlsson27da15b2010-01-01 20:29:01 +0000265 CallArgList Args;
266
267 QualType ThisType =
268 getContext().getPointerType(getContext().getTagDeclType(RD));
269
270 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000271 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000272
273 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000274
275 // And the rest of the call args
276 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000277 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
278 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000279}
280
281RValue
282CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
283 const CXXMethodDecl *MD,
284 ReturnValueSlot ReturnValue) {
285 assert(MD->isInstance() &&
286 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000287 LValue LV = EmitLValue(E->getArg(0));
288 llvm::Value *This = LV.getAddress();
289
Douglas Gregor146b8e92011-09-06 16:26:56 +0000290 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
291 MD->isTrivial()) {
292 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
293 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000294 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000295 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 }
297
Anders Carlssonc36783e2011-05-08 20:32:23 +0000298 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smithe30752c2012-10-09 19:52:38 +0000299 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000300 /*ImplicitParam=*/0, QualType(),
301 E->arg_begin() + 1, E->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000302}
303
Peter Collingbournefe883422011-10-06 18:29:37 +0000304RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
305 ReturnValueSlot ReturnValue) {
306 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
307}
308
Eli Friedmanfde961d2011-10-14 02:27:24 +0000309static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
310 llvm::Value *DestPtr,
311 const CXXRecordDecl *Base) {
312 if (Base->isEmpty())
313 return;
314
315 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
316
317 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
318 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000319 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000320
321 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
322
323 // If the type contains a pointer to data member we can't memset it to zero.
324 // Instead, create a null constant and copy it to the destination.
325 // TODO: there are other patterns besides zero that we can usefully memset,
326 // like -1, which happens to be the pattern used by member-pointers.
327 // TODO: isZeroInitializable can be over-conservative in the case where a
328 // virtual base contains a member pointer.
329 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
330 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
331
332 llvm::GlobalVariable *NullVariable =
333 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
334 /*isConstant=*/true,
335 llvm::GlobalVariable::PrivateLinkage,
336 NullConstant, Twine());
337 NullVariable->setAlignment(Align.getQuantity());
338 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
339
340 // Get and call the appropriate llvm.memcpy overload.
341 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
342 return;
343 }
344
345 // Otherwise, just memset the whole thing to zero. This is legal
346 // because in LLVM, all default initializers (other than the ones we just
347 // handled above) are guaranteed to have a bit pattern of all zeros.
348 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
349 Align.getQuantity());
350}
351
Anders Carlsson27da15b2010-01-01 20:29:01 +0000352void
John McCall7a626f62010-09-15 10:14:12 +0000353CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
354 AggValueSlot Dest) {
355 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000356 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000357
358 // If we require zero initialization before (or instead of) calling the
359 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000360 // constructor, emit the zero initialization now, unless destination is
361 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000362 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
363 switch (E->getConstructionKind()) {
364 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000365 case CXXConstructExpr::CK_Complete:
366 EmitNullInitialization(Dest.getAddr(), E->getType());
367 break;
368 case CXXConstructExpr::CK_VirtualBase:
369 case CXXConstructExpr::CK_NonVirtualBase:
370 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
371 break;
372 }
373 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000374
375 // If this is a call to a trivial default constructor, do nothing.
376 if (CD->isTrivial() && CD->isDefaultConstructor())
377 return;
378
John McCall8ea46b62010-09-18 00:58:34 +0000379 // Elide the constructor if we're constructing from a temporary.
380 // The temporary check is required because Sema sets this on NRVO
381 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000382 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000383 assert(getContext().hasSameUnqualifiedType(E->getType(),
384 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000385 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
386 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000387 return;
388 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000389 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000390
John McCallf677a8e2011-07-13 06:10:41 +0000391 if (const ConstantArrayType *arrayType
392 = getContext().getAsConstantArrayType(E->getType())) {
393 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000394 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000395 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000396 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000397 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000398 bool Delegating = false;
399
Alexis Hunt271c3682011-05-03 20:19:28 +0000400 switch (E->getConstructionKind()) {
401 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000402 // We should be emitting a constructor; GlobalDecl will assert this
403 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000404 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000405 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000406
Alexis Hunt271c3682011-05-03 20:19:28 +0000407 case CXXConstructExpr::CK_Complete:
408 Type = Ctor_Complete;
409 break;
410
411 case CXXConstructExpr::CK_VirtualBase:
412 ForVirtualBase = true;
413 // fall-through
414
415 case CXXConstructExpr::CK_NonVirtualBase:
416 Type = Ctor_Base;
417 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000418
Anders Carlsson27da15b2010-01-01 20:29:01 +0000419 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000420 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000421 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000422 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000423}
424
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000425void
426CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
427 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000428 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000429 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000430 Exp = E->getSubExpr();
431 assert(isa<CXXConstructExpr>(Exp) &&
432 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
433 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
434 const CXXConstructorDecl *CD = E->getConstructor();
435 RunCleanupsScope Scope(*this);
436
437 // If we require zero initialization before (or instead of) calling the
438 // constructor, as can be the case with a non-user-provided default
439 // constructor, emit the zero initialization now.
440 // FIXME. Do I still need this for a copy ctor synthesis?
441 if (E->requiresZeroInitialization())
442 EmitNullInitialization(Dest, E->getType());
443
Chandler Carruth99da11c2010-11-15 13:54:43 +0000444 assert(!getContext().getAsConstantArrayType(E->getType())
445 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000446 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E->arg_begin(), E->arg_end());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000447}
448
John McCall8ed55a52010-09-02 09:58:18 +0000449static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
450 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000451 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000452 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000453
John McCall7ec4b432011-05-16 01:05:12 +0000454 // No cookie is required if the operator new[] being used is the
455 // reserved placement operator new[].
456 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000457 return CharUnits::Zero();
458
John McCall284c48f2011-01-27 09:37:56 +0000459 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000460}
461
John McCall036f2f62011-05-15 07:14:44 +0000462static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
463 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000464 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000465 llvm::Value *&numElements,
466 llvm::Value *&sizeWithoutCookie) {
467 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000468
John McCall036f2f62011-05-15 07:14:44 +0000469 if (!e->isArray()) {
470 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
471 sizeWithoutCookie
472 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
473 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000474 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000475
John McCall036f2f62011-05-15 07:14:44 +0000476 // The width of size_t.
477 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
478
John McCall8ed55a52010-09-02 09:58:18 +0000479 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000480 llvm::APInt cookieSize(sizeWidth,
481 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000482
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000483 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000484 // We multiply the size of all dimensions for NumElements.
485 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000486 numElements = CGF.EmitScalarExpr(e->getArraySize());
487 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000488
John McCall036f2f62011-05-15 07:14:44 +0000489 // The number of elements can be have an arbitrary integer type;
490 // essentially, we need to multiply it by a constant factor, add a
491 // cookie size, and verify that the result is representable as a
492 // size_t. That's just a gloss, though, and it's wrong in one
493 // important way: if the count is negative, it's an error even if
494 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000495 bool isSigned
496 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000497 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000498 = cast<llvm::IntegerType>(numElements->getType());
499 unsigned numElementsWidth = numElementsType->getBitWidth();
500
501 // Compute the constant factor.
502 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000503 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000504 = CGF.getContext().getAsConstantArrayType(type)) {
505 type = CAT->getElementType();
506 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000507 }
508
John McCall036f2f62011-05-15 07:14:44 +0000509 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
510 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
511 typeSizeMultiplier *= arraySizeMultiplier;
512
513 // This will be a size_t.
514 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000515
Chris Lattner32ac5832010-07-20 21:55:52 +0000516 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
517 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000518 if (llvm::ConstantInt *numElementsC =
519 dyn_cast<llvm::ConstantInt>(numElements)) {
520 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000521
John McCall036f2f62011-05-15 07:14:44 +0000522 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000523
John McCall036f2f62011-05-15 07:14:44 +0000524 // If 'count' was a negative number, it's an overflow.
525 if (isSigned && count.isNegative())
526 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000527
John McCall036f2f62011-05-15 07:14:44 +0000528 // We want to do all this arithmetic in size_t. If numElements is
529 // wider than that, check whether it's already too big, and if so,
530 // overflow.
531 else if (numElementsWidth > sizeWidth &&
532 numElementsWidth - sizeWidth > count.countLeadingZeros())
533 hasAnyOverflow = true;
534
535 // Okay, compute a count at the right width.
536 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
537
Sebastian Redlf862eb62012-02-22 17:37:52 +0000538 // If there is a brace-initializer, we cannot allocate fewer elements than
539 // there are initializers. If we do, that's treated like an overflow.
540 if (adjustedCount.ult(minElements))
541 hasAnyOverflow = true;
542
John McCall036f2f62011-05-15 07:14:44 +0000543 // Scale numElements by that. This might overflow, but we don't
544 // care because it only overflows if allocationSize does, too, and
545 // if that overflows then we shouldn't use this.
546 numElements = llvm::ConstantInt::get(CGF.SizeTy,
547 adjustedCount * arraySizeMultiplier);
548
549 // Compute the size before cookie, and track whether it overflowed.
550 bool overflow;
551 llvm::APInt allocationSize
552 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
553 hasAnyOverflow |= overflow;
554
555 // Add in the cookie, and check whether it's overflowed.
556 if (cookieSize != 0) {
557 // Save the current size without a cookie. This shouldn't be
558 // used if there was overflow.
559 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
560
561 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
562 hasAnyOverflow |= overflow;
563 }
564
565 // On overflow, produce a -1 so operator new will fail.
566 if (hasAnyOverflow) {
567 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
568 } else {
569 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
570 }
571
572 // Otherwise, we might need to use the overflow intrinsics.
573 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000574 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000575 // 1) if isSigned, we need to check whether numElements is negative;
576 // 2) if numElementsWidth > sizeWidth, we need to check whether
577 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000578 // 3) if minElements > 0, we need to check whether numElements is smaller
579 // than that.
580 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000581 // sizeWithoutCookie := numElements * typeSizeMultiplier
582 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000583 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000584 // size := sizeWithoutCookie + cookieSize
585 // and check whether it overflows.
586
587 llvm::Value *hasOverflow = 0;
588
589 // If numElementsWidth > sizeWidth, then one way or another, we're
590 // going to have to do a comparison for (2), and this happens to
591 // take care of (1), too.
592 if (numElementsWidth > sizeWidth) {
593 llvm::APInt threshold(numElementsWidth, 1);
594 threshold <<= sizeWidth;
595
596 llvm::Value *thresholdV
597 = llvm::ConstantInt::get(numElementsType, threshold);
598
599 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
600 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
601
602 // Otherwise, if we're signed, we want to sext up to size_t.
603 } else if (isSigned) {
604 if (numElementsWidth < sizeWidth)
605 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
606
607 // If there's a non-1 type size multiplier, then we can do the
608 // signedness check at the same time as we do the multiply
609 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000610 // unsigned overflow. Otherwise, we have to do it here. But at least
611 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000612 if (typeSizeMultiplier == 1)
613 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000614 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000615
616 // Otherwise, zext up to size_t if necessary.
617 } else if (numElementsWidth < sizeWidth) {
618 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
619 }
620
621 assert(numElements->getType() == CGF.SizeTy);
622
Sebastian Redlf862eb62012-02-22 17:37:52 +0000623 if (minElements) {
624 // Don't allow allocation of fewer elements than we have initializers.
625 if (!hasOverflow) {
626 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
627 llvm::ConstantInt::get(CGF.SizeTy, minElements));
628 } else if (numElementsWidth > sizeWidth) {
629 // The other existing overflow subsumes this check.
630 // We do an unsigned comparison, since any signed value < -1 is
631 // taken care of either above or below.
632 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
633 CGF.Builder.CreateICmpULT(numElements,
634 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
635 }
636 }
637
John McCall036f2f62011-05-15 07:14:44 +0000638 size = numElements;
639
640 // Multiply by the type size if necessary. This multiplier
641 // includes all the factors for nested arrays.
642 //
643 // This step also causes numElements to be scaled up by the
644 // nested-array factor if necessary. Overflow on this computation
645 // can be ignored because the result shouldn't be used if
646 // allocation fails.
647 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000648 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000649 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000650
651 llvm::Value *tsmV =
652 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
653 llvm::Value *result =
654 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
655
656 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
657 if (hasOverflow)
658 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
659 else
660 hasOverflow = overflowed;
661
662 size = CGF.Builder.CreateExtractValue(result, 0);
663
664 // Also scale up numElements by the array size multiplier.
665 if (arraySizeMultiplier != 1) {
666 // If the base element type size is 1, then we can re-use the
667 // multiply we just did.
668 if (typeSize.isOne()) {
669 assert(arraySizeMultiplier == typeSizeMultiplier);
670 numElements = size;
671
672 // Otherwise we need a separate multiply.
673 } else {
674 llvm::Value *asmV =
675 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
676 numElements = CGF.Builder.CreateMul(numElements, asmV);
677 }
678 }
679 } else {
680 // numElements doesn't need to be scaled.
681 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000682 }
683
John McCall036f2f62011-05-15 07:14:44 +0000684 // Add in the cookie size if necessary.
685 if (cookieSize != 0) {
686 sizeWithoutCookie = size;
687
John McCall036f2f62011-05-15 07:14:44 +0000688 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000689 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000690
691 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
692 llvm::Value *result =
693 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
694
695 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
696 if (hasOverflow)
697 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
698 else
699 hasOverflow = overflowed;
700
701 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000702 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000703
John McCall036f2f62011-05-15 07:14:44 +0000704 // If we had any possibility of dynamic overflow, make a select to
705 // overwrite 'size' with an all-ones value, which should cause
706 // operator new to throw.
707 if (hasOverflow)
708 size = CGF.Builder.CreateSelect(hasOverflow,
709 llvm::Constant::getAllOnesValue(CGF.SizeTy),
710 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000711 }
John McCall8ed55a52010-09-02 09:58:18 +0000712
John McCall036f2f62011-05-15 07:14:44 +0000713 if (cookieSize == 0)
714 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000715 else
John McCall036f2f62011-05-15 07:14:44 +0000716 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000717
John McCall036f2f62011-05-15 07:14:44 +0000718 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000719}
720
Sebastian Redlf862eb62012-02-22 17:37:52 +0000721static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
722 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000723 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000724 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000725 switch (CGF.getEvaluationKind(AllocType)) {
726 case TEK_Scalar:
Eli Friedman38cd36d2011-12-03 02:13:40 +0000727 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000728 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000729 false);
John McCall47fb9502013-03-07 21:37:08 +0000730 return;
731 case TEK_Complex:
732 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
733 Alignment),
734 /*isInit*/ true);
735 return;
736 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000737 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000738 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000739 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000740 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000741 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000742 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000743 return;
John McCall7a626f62010-09-15 10:14:12 +0000744 }
John McCall47fb9502013-03-07 21:37:08 +0000745 }
746 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000747}
748
749void
750CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000751 QualType elementType,
752 llvm::Value *beginPtr,
753 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000754 if (!E->hasInitializer())
755 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000756
Sebastian Redlf862eb62012-02-22 17:37:52 +0000757 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000758 // Find the end of the array, hoisted out of the loop.
759 llvm::Value *endPtr =
760 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
761
Sebastian Redlf862eb62012-02-22 17:37:52 +0000762 unsigned initializerElements = 0;
763
764 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000765 llvm::AllocaInst *endOfInit = 0;
766 QualType::DestructionKind dtorKind = elementType.isDestructedType();
767 EHScopeStack::stable_iterator cleanup;
768 llvm::Instruction *cleanupDominator = 0;
Richard Smith1c96bc52013-12-11 01:40:16 +0000769
Sebastian Redlf862eb62012-02-22 17:37:52 +0000770 // If the initializer is an initializer list, first do the explicit elements.
771 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
772 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000773
Richard Smith1c96bc52013-12-11 01:40:16 +0000774 // If this is a multi-dimensional array new, we will initialize multiple
775 // elements with each init list element.
776 QualType AllocType = E->getAllocatedType();
777 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
778 AllocType->getAsArrayTypeUnsafe())) {
779 unsigned AS = explicitPtr->getType()->getPointerAddressSpace();
780 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
781 explicitPtr = Builder.CreateBitCast(explicitPtr, AllocPtrTy);
782 initializerElements *= getContext().getConstantArrayElementCount(CAT);
783 }
784
Chad Rosierf62290a2012-02-24 00:13:55 +0000785 // Enter a partial-destruction cleanup if necessary.
786 if (needsEHCleanup(dtorKind)) {
787 // In principle we could tell the cleanup where we are more
788 // directly, but the control flow can get so varied here that it
789 // would actually be quite complex. Therefore we go through an
790 // alloca.
791 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
792 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
793 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
794 getDestroyer(dtorKind));
795 cleanup = EHStack.stable_begin();
796 }
797
Sebastian Redlf862eb62012-02-22 17:37:52 +0000798 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000799 // Tell the cleanup that it needs to destroy up to this
800 // element. TODO: some of these stores can be trivially
801 // observed to be unnecessary.
802 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Richard Smith1c96bc52013-12-11 01:40:16 +0000803 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
804 ILE->getInit(i)->getType(), explicitPtr);
805 explicitPtr = Builder.CreateConstGEP1_32(explicitPtr, 1,
806 "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000807 }
808
809 // The remaining elements are filled with the array filler expression.
810 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000811
812 explicitPtr = Builder.CreateBitCast(explicitPtr, beginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000813 }
814
John McCall99210dc2011-09-15 06:49:18 +0000815 // Create the continuation block.
816 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
817
Sebastian Redlf862eb62012-02-22 17:37:52 +0000818 // If the number of elements isn't constant, we have to now check if there is
819 // anything left to initialize.
820 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
821 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000822 if (constNum->getZExtValue() <= initializerElements) {
823 // If there was a cleanup, deactivate it.
824 if (cleanupDominator)
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +0000825 DeactivateCleanupBlock(cleanup, cleanupDominator);
Chad Rosierf62290a2012-02-24 00:13:55 +0000826 return;
827 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000828 } else {
John McCall99210dc2011-09-15 06:49:18 +0000829 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000830 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000831 "array.isempty");
832 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
833 EmitBlock(nonEmptyBB);
834 }
835
836 // Enter the loop.
837 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
838 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
839
840 EmitBlock(loopBB);
841
842 // Set up the current-element phi.
843 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000844 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
845 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000846
Chad Rosierf62290a2012-02-24 00:13:55 +0000847 // Store the new cleanup position for irregular cleanups.
848 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
849
John McCall99210dc2011-09-15 06:49:18 +0000850 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000851 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000852 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
853 getDestroyer(dtorKind));
854 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000855 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000856 }
857
858 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000859 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000860
861 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000862 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000863 DeactivateCleanupBlock(cleanup, cleanupDominator);
864 cleanupDominator->eraseFromParent();
865 }
John McCall99210dc2011-09-15 06:49:18 +0000866
Faisal Vali57ae0562013-12-14 00:40:05 +0000867 // FIXME: The code below intends to initialize the individual array base
868 // elements, one at a time - but when dealing with multi-dimensional arrays -
869 // the pointer arithmetic can get confused - so the fix below entails casting
870 // to the allocated type to ensure that we get the pointer arithmetic right.
871 // It seems like the right approach here, it to really initialize the
872 // individual array base elements one at a time since it'll generate less
873 // code. I think the problem is that the wrong type is being passed into
874 // StoreAnyExprIntoOneUnit, but directly fixing that doesn't really work,
875 // because the Init expression has the wrong type at this point.
876 // So... this is ok for a quick fix, but we can and should do a lot better
877 // here long-term.
John McCall99210dc2011-09-15 06:49:18 +0000878
Faisal Vali57ae0562013-12-14 00:40:05 +0000879 // Advance to the next element by adjusting the pointer type as necessary.
880 // For new int[10][20][30], alloc type is int[20][30], base type is 'int'.
881 QualType AllocType = E->getAllocatedType();
882 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(
883 curPtr->getType()->getPointerAddressSpace());
884 llvm::Value *curPtrAllocTy = Builder.CreateBitCast(curPtr, AllocPtrTy);
885 llvm::Value *nextPtrAllocTy =
886 Builder.CreateConstGEP1_32(curPtrAllocTy, 1, "array.next");
887 // Cast it back to the base type so that we can compare it to the endPtr.
888 llvm::Value *nextPtr =
889 Builder.CreateBitCast(nextPtrAllocTy, endPtr->getType());
John McCall99210dc2011-09-15 06:49:18 +0000890 // Check whether we've gotten to the end of the array and, if so,
891 // exit the loop.
892 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
893 Builder.CreateCondBr(isEnd, contBB, loopBB);
894 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
895
896 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000897}
898
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000899static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
900 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000901 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000902 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000903 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000904 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000905}
906
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000907static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000908 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000909 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000910 llvm::Value *NumElements,
911 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000912 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000913 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000914 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
915 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregord1531032012-02-23 17:07:43 +0000916 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000917 // If new expression did not specify value-initialization, then there
918 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000919 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000920 return;
921
John McCall99210dc2011-09-15 06:49:18 +0000922 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000923 // Optimization: since zero initialization will just set the memory
924 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000925 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000926 return;
927 }
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000928 }
John McCallf677a8e2011-07-13 06:10:41 +0000929
Sebastian Redl6047f072012-02-16 12:22:20 +0000930 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
931 CCE->arg_begin(), CCE->arg_end(),
Eli Friedman48ddcf22012-08-25 07:11:29 +0000932 CCE->requiresZeroInitialization());
Anders Carlssond040e6b2010-05-03 15:09:17 +0000933 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000934 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000935 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000936 // Optimization: since zero initialization will just set the memory
937 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000938 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
939 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000940 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000941 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
942 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000943 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000944
Sebastian Redl6047f072012-02-16 12:22:20 +0000945 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000946 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000947
Sebastian Redlf862eb62012-02-22 17:37:52 +0000948 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000949}
950
Richard Smith8d0dc312013-07-21 23:12:18 +0000951/// Emit a call to an operator new or operator delete function, as implicitly
952/// created by new-expressions and delete-expressions.
953static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
954 const FunctionDecl *Callee,
955 const FunctionProtoType *CalleeType,
956 const CallArgList &Args) {
957 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +0000958 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +0000959 RValue RV =
960 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +0000961 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +0000962 Callee, &CallOrInvoke);
963
964 /// C++1y [expr.new]p10:
965 /// [In a new-expression,] an implementation is allowed to omit a call
966 /// to a replaceable global allocation function.
967 ///
968 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +0000969 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +0000970 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +0000971 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +0000972 // FIXME: Add addAttribute to CallSite.
973 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
974 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
975 llvm::Attribute::Builtin);
976 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
977 II->addAttribute(llvm::AttributeSet::FunctionIndex,
978 llvm::Attribute::Builtin);
979 else
980 llvm_unreachable("unexpected kind of call instruction");
981 }
982
983 return RV;
984}
985
John McCall824c2f52010-09-14 07:57:04 +0000986namespace {
987 /// A cleanup to call the given 'operator delete' function upon
988 /// abnormal exit from a new expression.
989 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
990 size_t NumPlacementArgs;
991 const FunctionDecl *OperatorDelete;
992 llvm::Value *Ptr;
993 llvm::Value *AllocSize;
994
995 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
996
997 public:
998 static size_t getExtraSize(size_t NumPlacementArgs) {
999 return NumPlacementArgs * sizeof(RValue);
1000 }
1001
1002 CallDeleteDuringNew(size_t NumPlacementArgs,
1003 const FunctionDecl *OperatorDelete,
1004 llvm::Value *Ptr,
1005 llvm::Value *AllocSize)
1006 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1007 Ptr(Ptr), AllocSize(AllocSize) {}
1008
1009 void setPlacementArg(unsigned I, RValue Arg) {
1010 assert(I < NumPlacementArgs && "index out of range");
1011 getPlacementArgs()[I] = Arg;
1012 }
1013
John McCall30317fd2011-07-12 20:27:29 +00001014 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +00001015 const FunctionProtoType *FPT
1016 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001017 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1018 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001019
1020 CallArgList DeleteArgs;
1021
1022 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001023 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001024 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001025
1026 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001027 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001028 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001029
1030 // Pass the rest of the arguments, which must match exactly.
1031 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001032 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001033
1034 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001035 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001036 }
1037 };
John McCall7f9c92a2010-09-17 00:50:28 +00001038
1039 /// A cleanup to call the given 'operator delete' function upon
1040 /// abnormal exit from a new expression when the new expression is
1041 /// conditional.
1042 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1043 size_t NumPlacementArgs;
1044 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001045 DominatingValue<RValue>::saved_type Ptr;
1046 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001047
John McCallcb5f77f2011-01-28 10:53:53 +00001048 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1049 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001050 }
1051
1052 public:
1053 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001054 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001055 }
1056
1057 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1058 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001059 DominatingValue<RValue>::saved_type Ptr,
1060 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001061 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1062 Ptr(Ptr), AllocSize(AllocSize) {}
1063
John McCallcb5f77f2011-01-28 10:53:53 +00001064 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001065 assert(I < NumPlacementArgs && "index out of range");
1066 getPlacementArgs()[I] = Arg;
1067 }
1068
John McCall30317fd2011-07-12 20:27:29 +00001069 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001070 const FunctionProtoType *FPT
1071 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001072 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1073 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001074
1075 CallArgList DeleteArgs;
1076
1077 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001078 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001079 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001080
1081 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001082 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001083 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001084 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001085 }
1086
1087 // Pass the rest of the arguments, which must match exactly.
1088 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001089 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001090 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001091 }
1092
1093 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001094 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001095 }
1096 };
1097}
1098
1099/// Enter a cleanup to call 'operator delete' if the initializer in a
1100/// new-expression throws.
1101static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1102 const CXXNewExpr *E,
1103 llvm::Value *NewPtr,
1104 llvm::Value *AllocSize,
1105 const CallArgList &NewArgs) {
1106 // If we're not inside a conditional branch, then the cleanup will
1107 // dominate and we can do the easier (and more efficient) thing.
1108 if (!CGF.isInConditionalBranch()) {
1109 CallDeleteDuringNew *Cleanup = CGF.EHStack
1110 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1111 E->getNumPlacementArgs(),
1112 E->getOperatorDelete(),
1113 NewPtr, AllocSize);
1114 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001115 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001116
1117 return;
1118 }
1119
1120 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001121 DominatingValue<RValue>::saved_type SavedNewPtr =
1122 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1123 DominatingValue<RValue>::saved_type SavedAllocSize =
1124 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001125
1126 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001127 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001128 E->getNumPlacementArgs(),
1129 E->getOperatorDelete(),
1130 SavedNewPtr,
1131 SavedAllocSize);
1132 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001133 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001134 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001135
John McCallf4beacd2011-11-10 10:43:54 +00001136 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001137}
1138
Anders Carlssoncc52f652009-09-22 22:53:17 +00001139llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001140 // The element type being allocated.
1141 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001142
John McCall75f94982011-03-07 03:12:35 +00001143 // 1. Build a call to the allocation function.
1144 FunctionDecl *allocator = E->getOperatorNew();
1145 const FunctionProtoType *allocatorType =
1146 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001147
John McCall75f94982011-03-07 03:12:35 +00001148 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001149
1150 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001151 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001152
Sebastian Redlf862eb62012-02-22 17:37:52 +00001153 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1154 unsigned minElements = 0;
1155 if (E->isArray() && E->hasInitializer()) {
1156 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1157 minElements = ILE->getNumInits();
1158 }
1159
John McCall75f94982011-03-07 03:12:35 +00001160 llvm::Value *numElements = 0;
1161 llvm::Value *allocSizeWithoutCookie = 0;
1162 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001163 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1164 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001165
Eli Friedman43dca6a2011-05-02 17:57:46 +00001166 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001167
Anders Carlssoncc52f652009-09-22 22:53:17 +00001168 // We start at 1 here because the first argument (the allocation size)
1169 // has already been emitted.
Reid Kleckner739756c2013-12-04 19:23:12 +00001170 EmitCallArgs(allocatorArgs, allocatorType->isVariadic(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001171 allocatorType->param_type_begin() + 1,
1172 allocatorType->param_type_end(), E->placement_arg_begin(),
Reid Kleckner739756c2013-12-04 19:23:12 +00001173 E->placement_arg_end());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001174
John McCall7ec4b432011-05-16 01:05:12 +00001175 // Emit the allocation call. If the allocator is a global placement
1176 // operator, just "inline" it directly.
1177 RValue RV;
1178 if (allocator->isReservedGlobalPlacementOperator()) {
1179 assert(allocatorArgs.size() == 2);
1180 RV = allocatorArgs[1].RV;
1181 // TODO: kill any unnecessary computations done for the size
1182 // argument.
1183 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001184 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001185 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001186
John McCall75f94982011-03-07 03:12:35 +00001187 // Emit a null check on the allocation result if the allocation
1188 // function is allowed to return null (because it has a non-throwing
1189 // exception spec; for this part, we inline
1190 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1191 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001192 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001193 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001194
John McCall75f94982011-03-07 03:12:35 +00001195 llvm::BasicBlock *nullCheckBB = 0;
1196 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001197
John McCall75f94982011-03-07 03:12:35 +00001198 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001199 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001200
John McCallf7dcf322011-03-07 01:52:56 +00001201 // The null-check means that the initializer is conditionally
1202 // evaluated.
1203 ConditionalEvaluation conditional(*this);
1204
John McCall75f94982011-03-07 03:12:35 +00001205 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001206 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001207
1208 nullCheckBB = Builder.GetInsertBlock();
1209 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1210 contBB = createBasicBlock("new.cont");
1211
1212 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1213 Builder.CreateCondBr(isNull, contBB, notNullBB);
1214 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001215 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001216
John McCall824c2f52010-09-14 07:57:04 +00001217 // If there's an operator delete, enter a cleanup to call it if an
1218 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001219 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001220 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001221 if (E->getOperatorDelete() &&
1222 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001223 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1224 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001225 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001226 }
1227
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001228 assert((allocSize == allocSizeWithoutCookie) ==
1229 CalculateCookiePadding(*this, E).isZero());
1230 if (allocSize != allocSizeWithoutCookie) {
1231 assert(E->isArray());
1232 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1233 numElements,
1234 E, allocType);
1235 }
1236
Chris Lattner2192fe52011-07-18 04:24:23 +00001237 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001238 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1239 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001240
John McCall99210dc2011-09-15 06:49:18 +00001241 EmitNewInitializer(*this, E, allocType, result, numElements,
1242 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001243 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001244 // NewPtr is a pointer to the base element type. If we're
1245 // allocating an array of arrays, we'll need to cast back to the
1246 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001247 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001248 if (result->getType() != resultType)
1249 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001250 }
John McCall824c2f52010-09-14 07:57:04 +00001251
1252 // Deactivate the 'operator delete' cleanup if we finished
1253 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001254 if (operatorDeleteCleanup.isValid()) {
1255 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1256 cleanupDominator->eraseFromParent();
1257 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001258
John McCall75f94982011-03-07 03:12:35 +00001259 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001260 conditional.end(*this);
1261
John McCall75f94982011-03-07 03:12:35 +00001262 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1263 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001264
Jay Foad20c0f022011-03-30 11:28:58 +00001265 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001266 PHI->addIncoming(result, notNullBB);
1267 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1268 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001269
John McCall75f94982011-03-07 03:12:35 +00001270 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001271 }
John McCall8ed55a52010-09-02 09:58:18 +00001272
John McCall75f94982011-03-07 03:12:35 +00001273 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001274}
1275
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001276void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1277 llvm::Value *Ptr,
1278 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001279 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1280
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001281 const FunctionProtoType *DeleteFTy =
1282 DeleteFD->getType()->getAs<FunctionProtoType>();
1283
1284 CallArgList DeleteArgs;
1285
Anders Carlsson21122cf2009-12-13 20:04:38 +00001286 // Check if we need to pass the size to the delete operator.
1287 llvm::Value *Size = 0;
1288 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001289 if (DeleteFTy->getNumParams() == 2) {
1290 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001291 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1292 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1293 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001294 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001295
1296 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001297 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001298 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001299
Anders Carlsson21122cf2009-12-13 20:04:38 +00001300 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001301 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001302
1303 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001304 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001305}
1306
John McCall8ed55a52010-09-02 09:58:18 +00001307namespace {
1308 /// Calls the given 'operator delete' on a single object.
1309 struct CallObjectDelete : EHScopeStack::Cleanup {
1310 llvm::Value *Ptr;
1311 const FunctionDecl *OperatorDelete;
1312 QualType ElementType;
1313
1314 CallObjectDelete(llvm::Value *Ptr,
1315 const FunctionDecl *OperatorDelete,
1316 QualType ElementType)
1317 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1318
John McCall30317fd2011-07-12 20:27:29 +00001319 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001320 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1321 }
1322 };
1323}
1324
1325/// Emit the code for deleting a single object.
1326static void EmitObjectDelete(CodeGenFunction &CGF,
1327 const FunctionDecl *OperatorDelete,
1328 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001329 QualType ElementType,
1330 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001331 // Find the destructor for the type, if applicable. If the
1332 // destructor is virtual, we'll just emit the vcall and return.
1333 const CXXDestructorDecl *Dtor = 0;
1334 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1335 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001336 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001337 Dtor = RD->getDestructor();
1338
1339 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001340 if (UseGlobalDelete) {
1341 // If we're supposed to call the global delete, make sure we do so
1342 // even if the destructor throws.
John McCall82fb8922012-09-25 10:10:39 +00001343
1344 // Derive the complete-object pointer, which is what we need
1345 // to pass to the deallocation function.
1346 llvm::Value *completePtr =
1347 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1348
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001349 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall82fb8922012-09-25 10:10:39 +00001350 completePtr, OperatorDelete,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001351 ElementType);
1352 }
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001353
Richard Smithe30752c2012-10-09 19:52:38 +00001354 // FIXME: Provide a source location here.
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001355 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1356 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType,
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001357 SourceLocation(), Ptr);
John McCall8ed55a52010-09-02 09:58:18 +00001358
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001359 if (UseGlobalDelete) {
1360 CGF.PopCleanupBlock();
1361 }
1362
John McCall8ed55a52010-09-02 09:58:18 +00001363 return;
1364 }
1365 }
1366 }
1367
1368 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001369 // This doesn't have to a conditional cleanup because we're going
1370 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001371 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1372 Ptr, OperatorDelete, ElementType);
1373
1374 if (Dtor)
1375 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001376 /*ForVirtualBase=*/false,
1377 /*Delegating=*/false,
1378 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001379 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001380 ElementType->isObjCLifetimeType()) {
1381 switch (ElementType.getObjCLifetime()) {
1382 case Qualifiers::OCL_None:
1383 case Qualifiers::OCL_ExplicitNone:
1384 case Qualifiers::OCL_Autoreleasing:
1385 break;
John McCall8ed55a52010-09-02 09:58:18 +00001386
John McCall31168b02011-06-15 23:02:42 +00001387 case Qualifiers::OCL_Strong: {
1388 // Load the pointer value.
1389 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1390 ElementType.isVolatileQualified());
1391
John McCallcdda29c2013-03-13 03:10:54 +00001392 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001393 break;
1394 }
1395
1396 case Qualifiers::OCL_Weak:
1397 CGF.EmitARCDestroyWeak(Ptr);
1398 break;
1399 }
1400 }
1401
John McCall8ed55a52010-09-02 09:58:18 +00001402 CGF.PopCleanupBlock();
1403}
1404
1405namespace {
1406 /// Calls the given 'operator delete' on an array of objects.
1407 struct CallArrayDelete : EHScopeStack::Cleanup {
1408 llvm::Value *Ptr;
1409 const FunctionDecl *OperatorDelete;
1410 llvm::Value *NumElements;
1411 QualType ElementType;
1412 CharUnits CookieSize;
1413
1414 CallArrayDelete(llvm::Value *Ptr,
1415 const FunctionDecl *OperatorDelete,
1416 llvm::Value *NumElements,
1417 QualType ElementType,
1418 CharUnits CookieSize)
1419 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1420 ElementType(ElementType), CookieSize(CookieSize) {}
1421
John McCall30317fd2011-07-12 20:27:29 +00001422 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001423 const FunctionProtoType *DeleteFTy =
1424 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001425 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001426
1427 CallArgList Args;
1428
1429 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001430 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001431 llvm::Value *DeletePtr
1432 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001433 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001434
1435 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001436 if (DeleteFTy->getNumParams() == 2) {
1437 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001438 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001439 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1440
1441 CharUnits ElementTypeSize =
1442 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1443
1444 // The size of an element, multiplied by the number of elements.
1445 llvm::Value *Size
1446 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1447 Size = CGF.Builder.CreateMul(Size, NumElements);
1448
1449 // Plus the size of the cookie if applicable.
1450 if (!CookieSize.isZero()) {
1451 llvm::Value *CookieSizeV
1452 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1453 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1454 }
1455
Eli Friedman43dca6a2011-05-02 17:57:46 +00001456 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001457 }
1458
1459 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001460 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001461 }
1462 };
1463}
1464
1465/// Emit the code for deleting an array of objects.
1466static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001467 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001468 llvm::Value *deletedPtr,
1469 QualType elementType) {
1470 llvm::Value *numElements = 0;
1471 llvm::Value *allocatedPtr = 0;
1472 CharUnits cookieSize;
1473 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1474 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001475
John McCallca2c56f2011-07-13 01:41:37 +00001476 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001477
1478 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001479 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001480 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001481 allocatedPtr, operatorDelete,
1482 numElements, elementType,
1483 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001484
John McCallca2c56f2011-07-13 01:41:37 +00001485 // Destroy the elements.
1486 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1487 assert(numElements && "no element count for a type with a destructor!");
1488
John McCallca2c56f2011-07-13 01:41:37 +00001489 llvm::Value *arrayEnd =
1490 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001491
1492 // Note that it is legal to allocate a zero-length array, and we
1493 // can never fold the check away because the length should always
1494 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001495 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1496 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001497 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001498 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001499 }
1500
John McCallca2c56f2011-07-13 01:41:37 +00001501 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001502 CGF.PopCleanupBlock();
1503}
1504
Anders Carlssoncc52f652009-09-22 22:53:17 +00001505void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001506 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001507 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001508
1509 // Null check the pointer.
1510 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1511 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1512
Anders Carlsson98981b12011-04-11 00:30:07 +00001513 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001514
1515 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1516 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001517
John McCall8ed55a52010-09-02 09:58:18 +00001518 // We might be deleting a pointer to array. If so, GEP down to the
1519 // first non-array element.
1520 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1521 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1522 if (DeleteTy->isConstantArrayType()) {
1523 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001524 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001525
1526 GEP.push_back(Zero); // point at the outermost array
1527
1528 // For each layer of array type we're pointing at:
1529 while (const ConstantArrayType *Arr
1530 = getContext().getAsConstantArrayType(DeleteTy)) {
1531 // 1. Unpeel the array type.
1532 DeleteTy = Arr->getElementType();
1533
1534 // 2. GEP to the first element of the array.
1535 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001536 }
John McCall8ed55a52010-09-02 09:58:18 +00001537
Jay Foad040dd822011-07-22 08:16:57 +00001538 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001539 }
1540
Douglas Gregor04f36212010-09-02 17:38:50 +00001541 assert(ConvertTypeForMem(DeleteTy) ==
1542 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001543
1544 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001545 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001546 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001547 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1548 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001549 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001550
Anders Carlssoncc52f652009-09-22 22:53:17 +00001551 EmitBlock(DeleteEnd);
1552}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001553
Anders Carlsson0c633502011-04-11 14:13:40 +00001554static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1555 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001556 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001557
1558 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1559}
1560
1561static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001562 llvm::Value *Fn = getBadTypeidFn(CGF);
John McCall882987f2013-02-28 19:01:20 +00001563 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001564 CGF.Builder.CreateUnreachable();
1565}
1566
Anders Carlsson940f02d2011-04-18 00:57:03 +00001567static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1568 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001569 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001570 // Get the vtable pointer.
1571 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1572
1573 // C++ [expr.typeid]p2:
1574 // If the glvalue expression is obtained by applying the unary * operator to
1575 // a pointer and the pointer is a null pointer value, the typeid expression
1576 // throws the std::bad_typeid exception.
1577 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1578 if (UO->getOpcode() == UO_Deref) {
1579 llvm::BasicBlock *BadTypeidBlock =
1580 CGF.createBasicBlock("typeid.bad_typeid");
1581 llvm::BasicBlock *EndBlock =
1582 CGF.createBasicBlock("typeid.end");
1583
1584 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1585 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1586
1587 CGF.EmitBlock(BadTypeidBlock);
1588 EmitBadTypeidCall(CGF);
1589 CGF.EmitBlock(EndBlock);
1590 }
1591 }
1592
1593 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1594 StdTypeInfoPtrTy->getPointerTo());
1595
1596 // Load the type info.
1597 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1598 return CGF.Builder.CreateLoad(Value);
1599}
1600
John McCalle4df6c82011-01-28 08:37:24 +00001601llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001602 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001603 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001604
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001605 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001606 llvm::Constant *TypeInfo =
1607 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001608 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001609 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001610
Anders Carlsson940f02d2011-04-18 00:57:03 +00001611 // C++ [expr.typeid]p2:
1612 // When typeid is applied to a glvalue expression whose type is a
1613 // polymorphic class type, the result refers to a std::type_info object
1614 // representing the type of the most derived object (that is, the dynamic
1615 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001616 if (E->isPotentiallyEvaluated())
1617 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1618 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001619
1620 QualType OperandTy = E->getExprOperand()->getType();
1621 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1622 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001623}
Mike Stump65511702009-11-16 06:50:58 +00001624
Anders Carlsson882d7902011-04-11 00:46:40 +00001625static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1626 // void *__dynamic_cast(const void *sub,
1627 // const abi::__class_type_info *src,
1628 // const abi::__class_type_info *dst,
1629 // std::ptrdiff_t src2dst_offset);
1630
Chris Lattnerece04092012-02-07 00:39:47 +00001631 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001632 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001633 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1634
Chris Lattnera5f58b02011-07-09 17:41:47 +00001635 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Benjamin Kramerb5206332013-02-03 17:44:25 +00001636
1637 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1638
1639 // Mark the function as nounwind readonly.
1640 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1641 llvm::Attribute::ReadOnly };
1642 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1643 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1644
1645 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
Anders Carlsson882d7902011-04-11 00:46:40 +00001646}
1647
1648static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1649 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001650 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001651 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1652}
1653
Anders Carlssonc1c99712011-04-11 01:45:29 +00001654static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001655 llvm::Value *Fn = getBadCastFn(CGF);
John McCall882987f2013-02-28 19:01:20 +00001656 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001657 CGF.Builder.CreateUnreachable();
1658}
1659
Benjamin Kramerd9c84552013-02-03 19:59:25 +00001660/// \brief Compute the src2dst_offset hint as described in the
1661/// Itanium C++ ABI [2.9.7]
1662static CharUnits computeOffsetHint(ASTContext &Context,
1663 const CXXRecordDecl *Src,
1664 const CXXRecordDecl *Dst) {
1665 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1666 /*DetectVirtual=*/false);
1667
1668 // If Dst is not derived from Src we can skip the whole computation below and
1669 // return that Src is not a public base of Dst. Record all inheritance paths.
1670 if (!Dst->isDerivedFrom(Src, Paths))
1671 return CharUnits::fromQuantity(-2ULL);
1672
1673 unsigned NumPublicPaths = 0;
1674 CharUnits Offset;
1675
1676 // Now walk all possible inheritance paths.
1677 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
1678 I != E; ++I) {
1679 if (I->Access != AS_public) // Ignore non-public inheritance.
1680 continue;
1681
1682 ++NumPublicPaths;
1683
1684 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1685 // If the path contains a virtual base class we can't give any hint.
1686 // -1: no hint.
1687 if (J->Base->isVirtual())
1688 return CharUnits::fromQuantity(-1ULL);
1689
1690 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1691 continue;
1692
1693 // Accumulate the base class offsets.
1694 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1695 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1696 }
1697 }
1698
1699 // -2: Src is not a public base of Dst.
1700 if (NumPublicPaths == 0)
1701 return CharUnits::fromQuantity(-2ULL);
1702
1703 // -3: Src is a multiple public base type but never a virtual base type.
1704 if (NumPublicPaths > 1)
1705 return CharUnits::fromQuantity(-3ULL);
1706
1707 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1708 // Return the offset of Src from the origin of Dst.
1709 return Offset;
1710}
1711
Anders Carlsson882d7902011-04-11 00:46:40 +00001712static llvm::Value *
1713EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1714 QualType SrcTy, QualType DestTy,
1715 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001716 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001717 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001718 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001719
1720 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1721 if (PTy->getPointeeType()->isVoidType()) {
1722 // C++ [expr.dynamic.cast]p7:
1723 // If T is "pointer to cv void," then the result is a pointer to the
1724 // most derived object pointed to by v.
1725
1726 // Get the vtable pointer.
1727 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1728
1729 // Get the offset-to-top from the vtable.
1730 llvm::Value *OffsetToTop =
1731 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1732 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1733
1734 // Finally, add the offset to the pointer.
1735 Value = CGF.EmitCastToVoidPtr(Value);
1736 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1737
1738 return CGF.Builder.CreateBitCast(Value, DestLTy);
1739 }
1740 }
1741
1742 QualType SrcRecordTy;
1743 QualType DestRecordTy;
1744
1745 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1746 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1747 DestRecordTy = DestPTy->getPointeeType();
1748 } else {
1749 SrcRecordTy = SrcTy;
1750 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1751 }
1752
1753 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1754 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1755
1756 llvm::Value *SrcRTTI =
1757 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1758 llvm::Value *DestRTTI =
1759 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1760
Benjamin Kramerd9c84552013-02-03 19:59:25 +00001761 // Compute the offset hint.
1762 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1763 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1764 llvm::Value *OffsetHint =
1765 llvm::ConstantInt::get(PtrDiffLTy,
1766 computeOffsetHint(CGF.getContext(), SrcDecl,
1767 DestDecl).getQuantity());
Anders Carlsson882d7902011-04-11 00:46:40 +00001768
1769 // Emit the call to __dynamic_cast.
1770 Value = CGF.EmitCastToVoidPtr(Value);
John McCall882987f2013-02-28 19:01:20 +00001771
1772 llvm::Value *args[] = { Value, SrcRTTI, DestRTTI, OffsetHint };
1773 Value = CGF.EmitNounwindRuntimeCall(getDynamicCastFn(CGF), args);
Anders Carlsson882d7902011-04-11 00:46:40 +00001774 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1775
1776 /// C++ [expr.dynamic.cast]p9:
1777 /// A failed cast to reference type throws std::bad_cast
1778 if (DestTy->isReferenceType()) {
1779 llvm::BasicBlock *BadCastBlock =
1780 CGF.createBasicBlock("dynamic_cast.bad_cast");
1781
1782 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1783 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1784
1785 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001786 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001787 }
1788
1789 return Value;
1790}
1791
Anders Carlssonc1c99712011-04-11 01:45:29 +00001792static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1793 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001794 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001795 if (DestTy->isPointerType())
1796 return llvm::Constant::getNullValue(DestLTy);
1797
1798 /// C++ [expr.dynamic.cast]p9:
1799 /// A failed cast to reference type throws std::bad_cast
1800 EmitBadCastCall(CGF);
1801
1802 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1803 return llvm::UndefValue::get(DestLTy);
1804}
1805
Anders Carlsson882d7902011-04-11 00:46:40 +00001806llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001807 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001808 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001809
Anders Carlssonc1c99712011-04-11 01:45:29 +00001810 if (DCE->isAlwaysNull())
1811 return EmitDynamicCastToNull(*this, DestTy);
1812
1813 QualType SrcTy = DCE->getSubExpr()->getType();
1814
Anders Carlsson882d7902011-04-11 00:46:40 +00001815 // C++ [expr.dynamic.cast]p4:
1816 // If the value of v is a null pointer value in the pointer case, the result
1817 // is the null pointer value of type T.
1818 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001819
Anders Carlsson882d7902011-04-11 00:46:40 +00001820 llvm::BasicBlock *CastNull = 0;
1821 llvm::BasicBlock *CastNotNull = 0;
1822 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001823
Anders Carlsson882d7902011-04-11 00:46:40 +00001824 if (ShouldNullCheckSrcValue) {
1825 CastNull = createBasicBlock("dynamic_cast.null");
1826 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1827
1828 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1829 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1830 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001831 }
1832
Anders Carlsson882d7902011-04-11 00:46:40 +00001833 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1834
1835 if (ShouldNullCheckSrcValue) {
1836 EmitBranch(CastEnd);
1837
1838 EmitBlock(CastNull);
1839 EmitBranch(CastEnd);
1840 }
1841
1842 EmitBlock(CastEnd);
1843
1844 if (ShouldNullCheckSrcValue) {
1845 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1846 PHI->addIncoming(Value, CastNotNull);
1847 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1848
1849 Value = PHI;
1850 }
1851
1852 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001853}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001854
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001855void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001856 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001857 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1858 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001859
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001860 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1861 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1862 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001863 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001864 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001865
David Blaikie40ed2972012-06-06 20:45:41 +00001866 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001867 ArrayRef<VarDecl *> ArrayIndexes;
1868 if (CurField->getType()->isArrayType())
1869 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001870 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001871 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001872}