blob: 03b90e2587a9eceb81730a938a64e7ac6bc65cc4 [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
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson27da15b2010-01-01 20:29:01 +000023RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24 llvm::Value *Callee,
25 ReturnValueSlot ReturnValue,
26 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000027 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000028 CallExpr::const_arg_iterator ArgBeg,
29 CallExpr::const_arg_iterator ArgEnd) {
30 assert(MD->isInstance() &&
31 "Trying to emit a member call expr on a static method!");
32
33 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
34
35 CallArgList Args;
36
37 // Push the this ptr.
38 Args.push_back(std::make_pair(RValue::get(This),
39 MD->getThisType(getContext())));
40
Anders Carlssone36a6b32010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
44 Args.push_back(std::make_pair(RValue::get(VTT), T));
45 }
46
Anders Carlsson27da15b2010-01-01 20:29:01 +000047 // And the rest of the call args
48 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49
John McCallab26cfa2010-02-05 21:31:56 +000050 QualType ResultType = FPT->getResultType();
51 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +000052 FPT->getExtInfo()),
53 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000054}
55
56/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
57/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000058static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
59 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +000060 const CXXMethodDecl *MD) {
61
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000062 // Cannot divirtualize in kext mode.
63 if (Context.getLangOptions().AppleKext)
64 return false;
65
Anders Carlsson19588aa2011-01-23 21:07:30 +000066 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +000067 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +000068 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +000069 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +000070
Anders Carlsson19588aa2011-01-23 21:07:30 +000071 // Similarly, if the class itself is marked 'final' it can't be overridden
72 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +000073 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +000074 return true;
75
Anders Carlsson27da15b2010-01-01 20:29:01 +000076 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
77 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
78 // This is a record decl. We know the type and can devirtualize it.
79 return VD->getType()->isRecordType();
80 }
81
82 return false;
83 }
84
85 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +000086 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +000087 return true;
88
89 // And calls on bound temporaries.
90 if (isa<CXXBindTemporaryExpr>(Base))
91 return true;
92
93 // Check if this is a call expr that returns a record type.
94 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
95 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +000096
Anders Carlsson27da15b2010-01-01 20:29:01 +000097 // We can't devirtualize the call.
98 return false;
99}
100
Francois Pichet64225792011-01-18 05:04:39 +0000101// Note: This function also emit constructor calls to support a MSVC
102// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000103RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
104 ReturnValueSlot ReturnValue) {
105 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
106 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
107
108 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
109 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
110
Devang Patel91bbb552010-09-30 19:05:55 +0000111 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000112 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
113 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000114 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
115 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
116 DI->getOrCreateRecordType(PTy->getPointeeType(),
117 MD->getParent()->getLocation());
118 }
119 }
120
Anders Carlsson27da15b2010-01-01 20:29:01 +0000121 if (MD->isStatic()) {
122 // The method is static, emit it as we would a regular call.
123 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
124 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
125 ReturnValue, CE->arg_begin(), CE->arg_end());
126 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000127
John McCall0d635f52010-09-03 01:26:39 +0000128 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000129 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000130 if (ME->isArrow())
131 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000132 else
133 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000134
John McCall0d635f52010-09-03 01:26:39 +0000135 if (MD->isTrivial()) {
136 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000137 if (isa<CXXConstructorDecl>(MD) &&
138 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
139 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000140
Francois Pichet64225792011-01-18 05:04:39 +0000141 if (MD->isCopyAssignmentOperator()) {
142 // We don't like to generate the trivial copy assignment operator when
143 // it isn't necessary; just produce the proper effect here.
144 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
145 EmitAggregateCopy(This, RHS, CE->getType());
146 return RValue::get(This);
147 }
148
149 if (isa<CXXConstructorDecl>(MD) &&
150 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
151 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.
Francois Pichet64225792011-01-18 05:04:39 +0000160 const CGFunctionInfo *FInfo = 0;
161 if (isa<CXXDestructorDecl>(MD))
162 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
163 Dtor_Complete);
164 else if (isa<CXXConstructorDecl>(MD))
165 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
166 Ctor_Complete);
167 else
168 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCall0d635f52010-09-03 01:26:39 +0000169
170 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
171 const llvm::Type *Ty
Francois Pichet64225792011-01-18 05:04:39 +0000172 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCall0d635f52010-09-03 01:26:39 +0000173
Anders Carlsson27da15b2010-01-01 20:29:01 +0000174 // C++ [class.virtual]p12:
175 // Explicit qualification with the scope operator (5.1) suppresses the
176 // virtual call mechanism.
177 //
178 // We also don't emit a virtual call if the base expression has a record type
179 // because then we know what the type is.
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000180 bool UseVirtualCall;
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000181 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
182 && !canDevirtualizeMemberFunctionCalls(getContext(),
183 ME->getBase(), MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000184 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000185 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
186 if (UseVirtualCall) {
187 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000188 } else {
John McCall0d635f52010-09-03 01:26:39 +0000189 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000190 }
Francois Pichet64225792011-01-18 05:04:39 +0000191 } else if (const CXXConstructorDecl *Ctor =
192 dyn_cast<CXXConstructorDecl>(MD)) {
193 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000194 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000195 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000196 } else {
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000197 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000198 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000199 ME->hasQualifier())
200 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), This, Ty);
201 else
202 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000203 }
204
Anders Carlssone36a6b32010-01-02 01:01:18 +0000205 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000206 CE->arg_begin(), CE->arg_end());
207}
208
209RValue
210CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
211 ReturnValueSlot ReturnValue) {
212 const BinaryOperator *BO =
213 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
214 const Expr *BaseExpr = BO->getLHS();
215 const Expr *MemFnExpr = BO->getRHS();
216
217 const MemberPointerType *MPT =
218 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000219
Anders Carlsson27da15b2010-01-01 20:29:01 +0000220 const FunctionProtoType *FPT =
221 MPT->getPointeeType()->getAs<FunctionProtoType>();
222 const CXXRecordDecl *RD =
223 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
224
Anders Carlsson27da15b2010-01-01 20:29:01 +0000225 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000226 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000227
228 // Emit the 'this' pointer.
229 llvm::Value *This;
230
John McCalle3027922010-08-25 11:45:40 +0000231 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000232 This = EmitScalarExpr(BaseExpr);
233 else
234 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000235
John McCall475999d2010-08-22 00:05:51 +0000236 // Ask the ABI to load the callee. Note that This is modified.
237 llvm::Value *Callee =
238 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239
Anders Carlsson27da15b2010-01-01 20:29:01 +0000240 CallArgList Args;
241
242 QualType ThisType =
243 getContext().getPointerType(getContext().getTagDeclType(RD));
244
245 // Push the this ptr.
246 Args.push_back(std::make_pair(RValue::get(This), ThisType));
247
248 // And the rest of the call args
249 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallab26cfa2010-02-05 21:31:56 +0000250 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
251 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 ReturnValue, Args);
253}
254
255RValue
256CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
257 const CXXMethodDecl *MD,
258 ReturnValueSlot ReturnValue) {
259 assert(MD->isInstance() &&
260 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000261 LValue LV = EmitLValue(E->getArg(0));
262 llvm::Value *This = LV.getAddress();
263
Douglas Gregorec3bec02010-09-27 22:37:28 +0000264 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000265 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
266 if (ClassDecl->hasTrivialCopyAssignment()) {
267 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
268 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000269 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
270 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000271 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000272 return RValue::get(This);
273 }
274 }
275
276 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
277 const llvm::Type *Ty =
278 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
279 FPT->isVariadic());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000280 llvm::Value *Callee;
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000281 if (MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000282 !canDevirtualizeMemberFunctionCalls(getContext(),
283 E->getArg(0), MD))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000284 Callee = BuildVirtualCall(MD, This, Ty);
285 else
286 Callee = CGM.GetAddrOfFunction(MD, Ty);
287
Anders Carlssone36a6b32010-01-02 01:01:18 +0000288 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000289 E->arg_begin() + 1, E->arg_end());
290}
291
292void
John McCall7a626f62010-09-15 10:14:12 +0000293CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
294 AggValueSlot Dest) {
295 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000297
298 // If we require zero initialization before (or instead of) calling the
299 // constructor, as can be the case with a non-user-provided default
300 // constructor, emit the zero initialization now.
301 if (E->requiresZeroInitialization())
John McCall7a626f62010-09-15 10:14:12 +0000302 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000303
304 // If this is a call to a trivial default constructor, do nothing.
305 if (CD->isTrivial() && CD->isDefaultConstructor())
306 return;
307
John McCall8ea46b62010-09-18 00:58:34 +0000308 // Elide the constructor if we're constructing from a temporary.
309 // The temporary check is required because Sema sets this on NRVO
310 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000311 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000312 assert(getContext().hasSameUnqualifiedType(E->getType(),
313 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000314 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
315 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000316 return;
317 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000318 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000319
320 const ConstantArrayType *Array
321 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000322 if (Array) {
323 QualType BaseElementTy = getContext().getBaseElementType(Array);
324 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
325 BasePtr = llvm::PointerType::getUnqual(BasePtr);
326 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000327 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000328
329 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
330 E->arg_begin(), E->arg_end());
331 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000332 else {
333 CXXCtorType Type =
334 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
335 ? Ctor_Complete : Ctor_Base;
336 bool ForVirtualBase =
337 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
338
Anders Carlsson27da15b2010-01-01 20:29:01 +0000339 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000340 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000341 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000342 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000343}
344
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000345void
346CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
347 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000348 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000349 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000350 Exp = E->getSubExpr();
351 assert(isa<CXXConstructExpr>(Exp) &&
352 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
353 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
354 const CXXConstructorDecl *CD = E->getConstructor();
355 RunCleanupsScope Scope(*this);
356
357 // If we require zero initialization before (or instead of) calling the
358 // constructor, as can be the case with a non-user-provided default
359 // constructor, emit the zero initialization now.
360 // FIXME. Do I still need this for a copy ctor synthesis?
361 if (E->requiresZeroInitialization())
362 EmitNullInitialization(Dest, E->getType());
363
Chandler Carruth99da11c2010-11-15 13:54:43 +0000364 assert(!getContext().getAsConstantArrayType(E->getType())
365 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000366 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
367 E->arg_begin(), E->arg_end());
368}
369
John McCallaa4149a2010-08-23 01:17:59 +0000370/// Check whether the given operator new[] is the global placement
371/// operator new[].
372static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
373 const FunctionDecl *Fn) {
374 // Must be in global scope. Note that allocation functions can't be
375 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000376 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000377 return false;
378
379 // Signature must be void *operator new[](size_t, void*).
380 // The size_t is common to all operator new[]s.
381 if (Fn->getNumParams() != 2)
382 return false;
383
384 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
385 return (ParamType == Ctx.VoidPtrTy);
386}
387
John McCall8ed55a52010-09-02 09:58:18 +0000388static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
389 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000390 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000391 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000392
Anders Carlsson399f4992009-12-13 20:34:34 +0000393 // No cookie is required if the new operator being used is
394 // ::operator new[](size_t, void*).
395 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000396 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000397 return CharUnits::Zero();
398
John McCall284c48f2011-01-27 09:37:56 +0000399 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000400}
401
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000402static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000403 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000404 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000405 llvm::Value *&NumElements,
406 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000407 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000408
409 const llvm::IntegerType *SizeTy =
410 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000411
John McCall8ed55a52010-09-02 09:58:18 +0000412 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
413
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000414 if (!E->isArray()) {
415 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
416 return SizeWithoutCookie;
417 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000418
John McCall8ed55a52010-09-02 09:58:18 +0000419 // Figure out the cookie size.
420 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
421
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000422 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000423 // We multiply the size of all dimensions for NumElements.
424 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000425 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000426 assert(NumElements->getType() == SizeTy && "element count not a size_t");
427
428 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000429 while (const ConstantArrayType *CAT
430 = CGF.getContext().getAsConstantArrayType(ElemType)) {
431 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000432 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000433 }
434
John McCall8ed55a52010-09-02 09:58:18 +0000435 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000436
Chris Lattner32ac5832010-07-20 21:55:52 +0000437 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
438 // Don't bloat the -O0 code.
439 if (llvm::ConstantInt *NumElementsC =
440 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000441 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000442 unsigned SizeWidth = NEC.getBitWidth();
443
444 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000445 NEC = NEC.zext(SizeWidth*2);
John McCall8ed55a52010-09-02 09:58:18 +0000446 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000447 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000448
449 if (!CookieSize.isZero()) {
450 // Save the current size without a cookie. We don't care if an
451 // overflow's already happened because SizeWithoutCookie isn't
452 // used if the allocator returns null or throws, as it should
453 // always do on an overflow.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000454 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000455 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
456
457 // Add the cookie size.
458 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000459 }
460
John McCall8ed55a52010-09-02 09:58:18 +0000461 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000462 SC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000463 Size = llvm::ConstantInt::get(SizeTy, SC);
464 } else {
465 // On overflow, produce a -1 so operator new throws.
466 Size = llvm::Constant::getAllOnesValue(SizeTy);
467 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000468
John McCall8ed55a52010-09-02 09:58:18 +0000469 // Scale NumElements while we're at it.
470 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
471 NumElements = llvm::ConstantInt::get(SizeTy, N);
472
473 // Otherwise, we don't need to do an overflow-checked multiplication if
474 // we're multiplying by one.
475 } else if (TypeSize.isOne()) {
476 assert(ArraySizeMultiplier == 1);
477
478 Size = NumElements;
479
480 // If we need a cookie, add its size in with an overflow check.
481 // This is maybe a little paranoid.
482 if (!CookieSize.isZero()) {
483 SizeWithoutCookie = Size;
484
485 llvm::Value *CookieSizeV
486 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
487
488 const llvm::Type *Types[] = { SizeTy };
489 llvm::Value *UAddF
490 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
491 llvm::Value *AddRes
492 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
493
494 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
495 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
496 Size = CGF.Builder.CreateSelect(DidOverflow,
497 llvm::ConstantInt::get(SizeTy, -1),
498 Size);
499 }
500
501 // Otherwise use the int.umul.with.overflow intrinsic.
502 } else {
503 llvm::Value *OutermostElementSize
504 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
505
506 llvm::Value *NumOutermostElements = NumElements;
507
508 // Scale NumElements by the array size multiplier. This might
509 // overflow, but only if the multiplication below also overflows,
510 // in which case this multiplication isn't used.
511 if (ArraySizeMultiplier != 1)
512 NumElements = CGF.Builder.CreateMul(NumElements,
513 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
514
515 // The requested size of the outermost array is non-constant.
516 // Multiply that by the static size of the elements of that array;
517 // on unsigned overflow, set the size to -1 to trigger an
518 // exception from the allocation routine. This is sufficient to
519 // prevent buffer overruns from the allocator returning a
520 // seemingly valid pointer to insufficient space. This idea comes
521 // originally from MSVC, and GCC has an open bug requesting
522 // similar behavior:
523 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
524 //
525 // This will not be sufficient for C++0x, which requires a
526 // specific exception class (std::bad_array_new_length).
527 // That will require ABI support that has not yet been specified.
528 const llvm::Type *Types[] = { SizeTy };
529 llvm::Value *UMulF
530 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
531 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
532 OutermostElementSize);
533
534 // The overflow bit.
535 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
536
537 // The result of the multiplication.
538 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
539
540 // If we have a cookie, we need to add that size in, too.
541 if (!CookieSize.isZero()) {
542 SizeWithoutCookie = Size;
543
544 llvm::Value *CookieSizeV
545 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
546 llvm::Value *UAddF
547 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
548 llvm::Value *AddRes
549 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
550
551 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
552
553 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
554 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
555 }
556
557 Size = CGF.Builder.CreateSelect(DidOverflow,
558 llvm::ConstantInt::get(SizeTy, -1),
559 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000560 }
John McCall8ed55a52010-09-02 09:58:18 +0000561
562 if (CookieSize.isZero())
563 SizeWithoutCookie = Size;
564 else
565 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
566
Chris Lattner32ac5832010-07-20 21:55:52 +0000567 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000568}
569
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000570static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
571 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000572
573 assert(E->getNumConstructorArgs() == 1 &&
574 "Can only have one argument to initializer of POD type.");
575
576 const Expr *Init = E->getConstructorArg(0);
577 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000578
579 unsigned Alignment =
580 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000581 if (!CGF.hasAggregateLLVMType(AllocType))
582 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000583 AllocType.isVolatileQualified(), Alignment,
584 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000585 else if (AllocType->isAnyComplexType())
586 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
587 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000588 else {
589 AggValueSlot Slot
590 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
591 CGF.EmitAggExpr(Init, Slot);
592 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000593}
594
595void
596CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
597 llvm::Value *NewPtr,
598 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000599 // We have a POD type.
600 if (E->getNumConstructorArgs() == 0)
601 return;
602
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000603 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
604
605 // Create a temporary for the loop index and initialize it with 0.
606 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
607 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
608 Builder.CreateStore(Zero, IndexPtr);
609
610 // Start the loop with a block that tests the condition.
611 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
612 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
613
614 EmitBlock(CondBlock);
615
616 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
617
618 // Generate: if (loop-index < number-of-elements fall to the loop body,
619 // otherwise, go to the block after the for-loop.
620 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
621 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
622 // If the condition is true, execute the body.
623 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
624
625 EmitBlock(ForBody);
626
627 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
628 // Inside the loop body, emit the constructor call on the array element.
629 Counter = Builder.CreateLoad(IndexPtr);
630 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
631 "arrayidx");
632 StoreAnyExprIntoOneUnit(*this, E, Address);
633
634 EmitBlock(ContinueBlock);
635
636 // Emit the increment of the loop counter.
637 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
638 Counter = Builder.CreateLoad(IndexPtr);
639 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
640 Builder.CreateStore(NextVal, IndexPtr);
641
642 // Finally, branch back up to the condition for the next iteration.
643 EmitBranch(CondBlock);
644
645 // Emit the fall-through block.
646 EmitBlock(AfterFor, true);
647}
648
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000649static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
650 llvm::Value *NewPtr, llvm::Value *Size) {
651 llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
652 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
653 if (NewPtr->getType() != BP)
654 NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000655
Ken Dyck705ba072011-01-19 01:58:38 +0000656 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000657 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000658 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000659}
660
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000661static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
662 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000663 llvm::Value *NumElements,
664 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000665 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000666 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000667 bool RequiresZeroInitialization = false;
668 if (Ctor->getParent()->hasTrivialConstructor()) {
669 // If new expression did not specify value-initialization, then there
670 // is no initialization.
671 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
672 return;
673
John McCall614dbdc2010-08-22 21:01:12 +0000674 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000675 // Optimization: since zero initialization will just set the memory
676 // to all zeroes, generate a single memset to do it in one shot.
677 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
678 AllocSizeWithoutCookie);
679 return;
680 }
681
682 RequiresZeroInitialization = true;
683 }
684
685 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
686 E->constructor_arg_begin(),
687 E->constructor_arg_end(),
688 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000689 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000690 } else if (E->getNumConstructorArgs() == 1 &&
691 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
692 // Optimization: since zero initialization will just set the memory
693 // to all zeroes, generate a single memset to do it in one shot.
694 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
695 AllocSizeWithoutCookie);
696 return;
697 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000698 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
699 return;
700 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000701 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000702
703 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000704 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
705 // direct initialization. C++ [dcl.init]p5 requires that we
706 // zero-initialize storage if there are no user-declared constructors.
707 if (E->hasInitializer() &&
708 !Ctor->getParent()->hasUserDeclaredConstructor() &&
709 !Ctor->getParent()->isEmpty())
710 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
711
Douglas Gregore1823702010-07-07 23:37:33 +0000712 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
713 NewPtr, E->constructor_arg_begin(),
714 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000715
716 return;
717 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000718 // We have a POD type.
719 if (E->getNumConstructorArgs() == 0)
720 return;
721
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000722 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000723}
724
John McCall824c2f52010-09-14 07:57:04 +0000725namespace {
726 /// A cleanup to call the given 'operator delete' function upon
727 /// abnormal exit from a new expression.
728 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
729 size_t NumPlacementArgs;
730 const FunctionDecl *OperatorDelete;
731 llvm::Value *Ptr;
732 llvm::Value *AllocSize;
733
734 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
735
736 public:
737 static size_t getExtraSize(size_t NumPlacementArgs) {
738 return NumPlacementArgs * sizeof(RValue);
739 }
740
741 CallDeleteDuringNew(size_t NumPlacementArgs,
742 const FunctionDecl *OperatorDelete,
743 llvm::Value *Ptr,
744 llvm::Value *AllocSize)
745 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
746 Ptr(Ptr), AllocSize(AllocSize) {}
747
748 void setPlacementArg(unsigned I, RValue Arg) {
749 assert(I < NumPlacementArgs && "index out of range");
750 getPlacementArgs()[I] = Arg;
751 }
752
753 void Emit(CodeGenFunction &CGF, bool IsForEH) {
754 const FunctionProtoType *FPT
755 = OperatorDelete->getType()->getAs<FunctionProtoType>();
756 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000757 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000758
759 CallArgList DeleteArgs;
760
761 // The first argument is always a void*.
762 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
763 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
764
765 // A member 'operator delete' can take an extra 'size_t' argument.
766 if (FPT->getNumArgs() == NumPlacementArgs + 2)
767 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
768
769 // Pass the rest of the arguments, which must match exactly.
770 for (unsigned I = 0; I != NumPlacementArgs; ++I)
771 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
772
773 // Call 'operator delete'.
774 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
775 CGF.CGM.GetAddrOfFunction(OperatorDelete),
776 ReturnValueSlot(), DeleteArgs, OperatorDelete);
777 }
778 };
John McCall7f9c92a2010-09-17 00:50:28 +0000779
780 /// A cleanup to call the given 'operator delete' function upon
781 /// abnormal exit from a new expression when the new expression is
782 /// conditional.
783 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
784 size_t NumPlacementArgs;
785 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +0000786 DominatingValue<RValue>::saved_type Ptr;
787 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +0000788
John McCallcb5f77f2011-01-28 10:53:53 +0000789 DominatingValue<RValue>::saved_type *getPlacementArgs() {
790 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +0000791 }
792
793 public:
794 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +0000795 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +0000796 }
797
798 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
799 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +0000800 DominatingValue<RValue>::saved_type Ptr,
801 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +0000802 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
803 Ptr(Ptr), AllocSize(AllocSize) {}
804
John McCallcb5f77f2011-01-28 10:53:53 +0000805 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +0000806 assert(I < NumPlacementArgs && "index out of range");
807 getPlacementArgs()[I] = Arg;
808 }
809
810 void Emit(CodeGenFunction &CGF, bool IsForEH) {
811 const FunctionProtoType *FPT
812 = OperatorDelete->getType()->getAs<FunctionProtoType>();
813 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
814 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
815
816 CallArgList DeleteArgs;
817
818 // The first argument is always a void*.
819 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCallcb5f77f2011-01-28 10:53:53 +0000820 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall7f9c92a2010-09-17 00:50:28 +0000821
822 // A member 'operator delete' can take an extra 'size_t' argument.
823 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +0000824 RValue RV = AllocSize.restore(CGF);
John McCall7f9c92a2010-09-17 00:50:28 +0000825 DeleteArgs.push_back(std::make_pair(RV, *AI++));
826 }
827
828 // Pass the rest of the arguments, which must match exactly.
829 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +0000830 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall7f9c92a2010-09-17 00:50:28 +0000831 DeleteArgs.push_back(std::make_pair(RV, *AI++));
832 }
833
834 // Call 'operator delete'.
835 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
836 CGF.CGM.GetAddrOfFunction(OperatorDelete),
837 ReturnValueSlot(), DeleteArgs, OperatorDelete);
838 }
839 };
840}
841
842/// Enter a cleanup to call 'operator delete' if the initializer in a
843/// new-expression throws.
844static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
845 const CXXNewExpr *E,
846 llvm::Value *NewPtr,
847 llvm::Value *AllocSize,
848 const CallArgList &NewArgs) {
849 // If we're not inside a conditional branch, then the cleanup will
850 // dominate and we can do the easier (and more efficient) thing.
851 if (!CGF.isInConditionalBranch()) {
852 CallDeleteDuringNew *Cleanup = CGF.EHStack
853 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
854 E->getNumPlacementArgs(),
855 E->getOperatorDelete(),
856 NewPtr, AllocSize);
857 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
858 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
859
860 return;
861 }
862
863 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +0000864 DominatingValue<RValue>::saved_type SavedNewPtr =
865 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
866 DominatingValue<RValue>::saved_type SavedAllocSize =
867 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +0000868
869 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
870 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
871 E->getNumPlacementArgs(),
872 E->getOperatorDelete(),
873 SavedNewPtr,
874 SavedAllocSize);
875 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +0000876 Cleanup->setPlacementArg(I,
877 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall7f9c92a2010-09-17 00:50:28 +0000878
879 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000880}
881
Anders Carlssoncc52f652009-09-22 22:53:17 +0000882llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoncc52f652009-09-22 22:53:17 +0000883 QualType AllocType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000884 if (AllocType->isArrayType())
885 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
886 AllocType = AType->getElementType();
887
Anders Carlssoncc52f652009-09-22 22:53:17 +0000888 FunctionDecl *NewFD = E->getOperatorNew();
889 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
890
891 CallArgList NewArgs;
892
893 // The allocation size is the first argument.
894 QualType SizeTy = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000895
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000896 llvm::Value *NumElements = 0;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000897 llvm::Value *AllocSizeWithoutCookie = 0;
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000898 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000899 *this, E, NumElements,
900 AllocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000901
Anders Carlssoncc52f652009-09-22 22:53:17 +0000902 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
903
904 // Emit the rest of the arguments.
905 // FIXME: Ideally, this should just use EmitCallArgs.
906 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
907
908 // First, use the types from the function type.
909 // We start at 1 here because the first argument (the allocation size)
910 // has already been emitted.
911 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
912 QualType ArgType = NewFTy->getArgType(i);
913
914 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
915 getTypePtr() ==
916 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
917 "type mismatch in call argument!");
918
919 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
920 ArgType));
921
922 }
923
924 // Either we've emitted all the call args, or we have a call to a
925 // variadic function.
926 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
927 "Extra arguments in non-variadic function!");
928
929 // If we still have any arguments, emit them using the type of the argument.
930 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
931 NewArg != NewArgEnd; ++NewArg) {
932 QualType ArgType = NewArg->getType();
933 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
934 ArgType));
935 }
936
937 // Emit the call to new.
938 RValue RV =
John McCallab26cfa2010-02-05 21:31:56 +0000939 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +0000940 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000941
942 // If an allocation function is declared with an empty exception specification
943 // it returns null to indicate failure to allocate storage. [expr.new]p13.
944 // (We don't need to check for null when there's no new initializer and
945 // we're allocating a POD type).
946 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
947 !(AllocType->isPODType() && !E->hasInitializer());
948
John McCall8ed55a52010-09-02 09:58:18 +0000949 llvm::BasicBlock *NullCheckSource = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +0000950 llvm::BasicBlock *NewNotNull = 0;
951 llvm::BasicBlock *NewEnd = 0;
952
953 llvm::Value *NewPtr = RV.getScalarVal();
John McCall8ed55a52010-09-02 09:58:18 +0000954 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000955
956 if (NullCheckResult) {
John McCall8ed55a52010-09-02 09:58:18 +0000957 NullCheckSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000958 NewNotNull = createBasicBlock("new.notnull");
959 NewEnd = createBasicBlock("new.end");
960
John McCall8ed55a52010-09-02 09:58:18 +0000961 llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
962 Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000963 EmitBlock(NewNotNull);
964 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000965
John McCall8ed55a52010-09-02 09:58:18 +0000966 assert((AllocSize == AllocSizeWithoutCookie) ==
967 CalculateCookiePadding(*this, E).isZero());
968 if (AllocSize != AllocSizeWithoutCookie) {
969 assert(E->isArray());
970 NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
John McCall284c48f2011-01-27 09:37:56 +0000971 E, AllocType);
John McCall8ed55a52010-09-02 09:58:18 +0000972 }
Anders Carlssonf7716812009-09-23 18:59:48 +0000973
John McCall824c2f52010-09-14 07:57:04 +0000974 // If there's an operator delete, enter a cleanup to call it if an
975 // exception is thrown.
976 EHScopeStack::stable_iterator CallOperatorDelete;
977 if (E->getOperatorDelete()) {
John McCall7f9c92a2010-09-17 00:50:28 +0000978 EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
John McCall824c2f52010-09-14 07:57:04 +0000979 CallOperatorDelete = EHStack.stable_begin();
980 }
981
Douglas Gregor040ad502010-09-02 23:24:14 +0000982 const llvm::Type *ElementPtrTy
983 = ConvertTypeForMem(AllocType)->getPointerTo(AS);
John McCall8ed55a52010-09-02 09:58:18 +0000984 NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +0000985
John McCall8ed55a52010-09-02 09:58:18 +0000986 if (E->isArray()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000987 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +0000988
989 // NewPtr is a pointer to the base element type. If we're
990 // allocating an array of arrays, we'll need to cast back to the
991 // array pointer type.
Douglas Gregor040ad502010-09-02 23:24:14 +0000992 const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
John McCall8ed55a52010-09-02 09:58:18 +0000993 if (NewPtr->getType() != ResultTy)
994 NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
995 } else {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000996 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000997 }
John McCall824c2f52010-09-14 07:57:04 +0000998
999 // Deactivate the 'operator delete' cleanup if we finished
1000 // initialization.
1001 if (CallOperatorDelete.isValid())
1002 DeactivateCleanupBlock(CallOperatorDelete);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001003
Anders Carlssoncc52f652009-09-22 22:53:17 +00001004 if (NullCheckResult) {
1005 Builder.CreateBr(NewEnd);
John McCall8ed55a52010-09-02 09:58:18 +00001006 llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001007 EmitBlock(NewEnd);
1008
1009 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1010 PHI->reserveOperandSpace(2);
John McCall8ed55a52010-09-02 09:58:18 +00001011 PHI->addIncoming(NewPtr, NotNullSource);
1012 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1013 NullCheckSource);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001014
1015 NewPtr = PHI;
1016 }
John McCall8ed55a52010-09-02 09:58:18 +00001017
Anders Carlssoncc52f652009-09-22 22:53:17 +00001018 return NewPtr;
1019}
1020
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001021void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1022 llvm::Value *Ptr,
1023 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001024 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1025
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001026 const FunctionProtoType *DeleteFTy =
1027 DeleteFD->getType()->getAs<FunctionProtoType>();
1028
1029 CallArgList DeleteArgs;
1030
Anders Carlsson21122cf2009-12-13 20:04:38 +00001031 // Check if we need to pass the size to the delete operator.
1032 llvm::Value *Size = 0;
1033 QualType SizeTy;
1034 if (DeleteFTy->getNumArgs() == 2) {
1035 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001036 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1037 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1038 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001039 }
1040
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001041 QualType ArgTy = DeleteFTy->getArgType(0);
1042 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1043 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1044
Anders Carlsson21122cf2009-12-13 20:04:38 +00001045 if (Size)
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001046 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001047
1048 // Emit the call to delete.
John McCallab26cfa2010-02-05 21:31:56 +00001049 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001050 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001051 DeleteArgs, DeleteFD);
1052}
1053
John McCall8ed55a52010-09-02 09:58:18 +00001054namespace {
1055 /// Calls the given 'operator delete' on a single object.
1056 struct CallObjectDelete : EHScopeStack::Cleanup {
1057 llvm::Value *Ptr;
1058 const FunctionDecl *OperatorDelete;
1059 QualType ElementType;
1060
1061 CallObjectDelete(llvm::Value *Ptr,
1062 const FunctionDecl *OperatorDelete,
1063 QualType ElementType)
1064 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1065
1066 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1067 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1068 }
1069 };
1070}
1071
1072/// Emit the code for deleting a single object.
1073static void EmitObjectDelete(CodeGenFunction &CGF,
1074 const FunctionDecl *OperatorDelete,
1075 llvm::Value *Ptr,
1076 QualType ElementType) {
1077 // Find the destructor for the type, if applicable. If the
1078 // destructor is virtual, we'll just emit the vcall and return.
1079 const CXXDestructorDecl *Dtor = 0;
1080 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1081 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1082 if (!RD->hasTrivialDestructor()) {
1083 Dtor = RD->getDestructor();
1084
1085 if (Dtor->isVirtual()) {
1086 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001087 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1088 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001089 /*isVariadic=*/false);
1090
1091 llvm::Value *Callee
1092 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1093 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1094 0, 0);
1095
1096 // The dtor took care of deleting the object.
1097 return;
1098 }
1099 }
1100 }
1101
1102 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001103 // This doesn't have to a conditional cleanup because we're going
1104 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001105 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1106 Ptr, OperatorDelete, ElementType);
1107
1108 if (Dtor)
1109 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1110 /*ForVirtualBase=*/false, Ptr);
1111
1112 CGF.PopCleanupBlock();
1113}
1114
1115namespace {
1116 /// Calls the given 'operator delete' on an array of objects.
1117 struct CallArrayDelete : EHScopeStack::Cleanup {
1118 llvm::Value *Ptr;
1119 const FunctionDecl *OperatorDelete;
1120 llvm::Value *NumElements;
1121 QualType ElementType;
1122 CharUnits CookieSize;
1123
1124 CallArrayDelete(llvm::Value *Ptr,
1125 const FunctionDecl *OperatorDelete,
1126 llvm::Value *NumElements,
1127 QualType ElementType,
1128 CharUnits CookieSize)
1129 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1130 ElementType(ElementType), CookieSize(CookieSize) {}
1131
1132 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1133 const FunctionProtoType *DeleteFTy =
1134 OperatorDelete->getType()->getAs<FunctionProtoType>();
1135 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1136
1137 CallArgList Args;
1138
1139 // Pass the pointer as the first argument.
1140 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1141 llvm::Value *DeletePtr
1142 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1143 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1144
1145 // Pass the original requested size as the second argument.
1146 if (DeleteFTy->getNumArgs() == 2) {
1147 QualType size_t = DeleteFTy->getArgType(1);
1148 const llvm::IntegerType *SizeTy
1149 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1150
1151 CharUnits ElementTypeSize =
1152 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1153
1154 // The size of an element, multiplied by the number of elements.
1155 llvm::Value *Size
1156 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1157 Size = CGF.Builder.CreateMul(Size, NumElements);
1158
1159 // Plus the size of the cookie if applicable.
1160 if (!CookieSize.isZero()) {
1161 llvm::Value *CookieSizeV
1162 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1163 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1164 }
1165
1166 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1167 }
1168
1169 // Emit the call to delete.
1170 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1171 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1172 ReturnValueSlot(), Args, OperatorDelete);
1173 }
1174 };
1175}
1176
1177/// Emit the code for deleting an array of objects.
1178static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001179 const CXXDeleteExpr *E,
John McCall8ed55a52010-09-02 09:58:18 +00001180 llvm::Value *Ptr,
1181 QualType ElementType) {
1182 llvm::Value *NumElements = 0;
1183 llvm::Value *AllocatedPtr = 0;
1184 CharUnits CookieSize;
John McCall284c48f2011-01-27 09:37:56 +00001185 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall8ed55a52010-09-02 09:58:18 +00001186 NumElements, AllocatedPtr, CookieSize);
1187
1188 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1189
1190 // Make sure that we call delete even if one of the dtors throws.
John McCall284c48f2011-01-27 09:37:56 +00001191 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001192 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1193 AllocatedPtr, OperatorDelete,
1194 NumElements, ElementType,
1195 CookieSize);
1196
1197 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1198 if (!RD->hasTrivialDestructor()) {
1199 assert(NumElements && "ReadArrayCookie didn't find element count"
1200 " for a class with destructor");
1201 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1202 }
1203 }
1204
1205 CGF.PopCleanupBlock();
1206}
1207
Anders Carlssoncc52f652009-09-22 22:53:17 +00001208void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001209
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001210 // Get at the argument before we performed the implicit conversion
1211 // to void*.
1212 const Expr *Arg = E->getArgument();
1213 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001214 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001215 ICE->getType()->isVoidPointerType())
1216 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001217 else
1218 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001219 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001220
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001221 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001222
1223 // Null check the pointer.
1224 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1225 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1226
1227 llvm::Value *IsNull =
1228 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1229 "isnull");
1230
1231 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1232 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001233
John McCall8ed55a52010-09-02 09:58:18 +00001234 // We might be deleting a pointer to array. If so, GEP down to the
1235 // first non-array element.
1236 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1237 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1238 if (DeleteTy->isConstantArrayType()) {
1239 llvm::Value *Zero = Builder.getInt32(0);
1240 llvm::SmallVector<llvm::Value*,8> GEP;
1241
1242 GEP.push_back(Zero); // point at the outermost array
1243
1244 // For each layer of array type we're pointing at:
1245 while (const ConstantArrayType *Arr
1246 = getContext().getAsConstantArrayType(DeleteTy)) {
1247 // 1. Unpeel the array type.
1248 DeleteTy = Arr->getElementType();
1249
1250 // 2. GEP to the first element of the array.
1251 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001252 }
John McCall8ed55a52010-09-02 09:58:18 +00001253
1254 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001255 }
1256
Douglas Gregor04f36212010-09-02 17:38:50 +00001257 assert(ConvertTypeForMem(DeleteTy) ==
1258 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001259
1260 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001261 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001262 } else {
1263 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1264 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001265
Anders Carlssoncc52f652009-09-22 22:53:17 +00001266 EmitBlock(DeleteEnd);
1267}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001268
John McCalle4df6c82011-01-28 08:37:24 +00001269llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Mike Stumpc9b231c2009-11-15 08:09:41 +00001270 QualType Ty = E->getType();
1271 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001272
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001273 if (E->isTypeOperand()) {
1274 llvm::Constant *TypeInfo =
1275 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1276 return Builder.CreateBitCast(TypeInfo, LTy);
1277 }
1278
Mike Stumpc9b231c2009-11-15 08:09:41 +00001279 Expr *subE = E->getExprOperand();
Mike Stump6fdfea62009-11-17 22:33:00 +00001280 Ty = subE->getType();
1281 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1282 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc9b231c2009-11-15 08:09:41 +00001283 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1284 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1285 if (RD->isPolymorphic()) {
1286 // FIXME: if subE is an lvalue do
1287 LValue Obj = EmitLValue(subE);
1288 llvm::Value *This = Obj.getAddress();
Mike Stump1bf924b2009-11-15 16:52:53 +00001289 // We need to do a zero check for *p, unless it has NonNullAttr.
1290 // FIXME: PointerType->hasAttr<NonNullAttr>()
1291 bool CanBeZero = false;
Mike Stumpc2c03342009-11-17 00:45:21 +00001292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001293 if (UO->getOpcode() == UO_Deref)
Mike Stump1bf924b2009-11-15 16:52:53 +00001294 CanBeZero = true;
1295 if (CanBeZero) {
1296 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1297 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1298
Dan Gohman8fc50c22010-10-26 18:44:08 +00001299 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1300 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stump1bf924b2009-11-15 16:52:53 +00001301 NonZeroBlock, ZeroBlock);
1302 EmitBlock(ZeroBlock);
1303 /// Call __cxa_bad_typeid
1304 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1305 const llvm::FunctionType *FTy;
1306 FTy = llvm::FunctionType::get(ResultType, false);
1307 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stump65511702009-11-16 06:50:58 +00001308 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stump1bf924b2009-11-15 16:52:53 +00001309 Builder.CreateUnreachable();
1310 EmitBlock(NonZeroBlock);
1311 }
Dan Gohman8fc50c22010-10-26 18:44:08 +00001312 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc9b231c2009-11-15 08:09:41 +00001313 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1314 V = Builder.CreateLoad(V);
1315 return V;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001316 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001317 }
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001318 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001319}
Mike Stump65511702009-11-16 06:50:58 +00001320
1321llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1322 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001323 QualType SrcTy = DCE->getSubExpr()->getType();
1324 QualType DestTy = DCE->getTypeAsWritten();
1325 QualType InnerType = DestTy->getPointeeType();
1326
Mike Stump65511702009-11-16 06:50:58 +00001327 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001328
Mike Stump65511702009-11-16 06:50:58 +00001329 bool CanBeZero = false;
Mike Stump65511702009-11-16 06:50:58 +00001330 bool ToVoid = false;
Mike Stump6ca0e212009-11-16 22:52:20 +00001331 bool ThrowOnBad = false;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001332 if (DestTy->isPointerType()) {
Mike Stump65511702009-11-16 06:50:58 +00001333 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1334 CanBeZero = true;
1335 if (InnerType->isVoidType())
1336 ToVoid = true;
1337 } else {
1338 LTy = LTy->getPointerTo();
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001339
1340 // FIXME: What if exceptions are disabled?
Mike Stump65511702009-11-16 06:50:58 +00001341 ThrowOnBad = true;
1342 }
1343
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001344 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1345 SrcTy = SrcTy->getPointeeType();
1346 SrcTy = SrcTy.getUnqualifiedType();
1347
Anders Carlsson0087bc82009-12-18 14:55:04 +00001348 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001349 DestTy = DestTy->getPointeeType();
1350 DestTy = DestTy.getUnqualifiedType();
Mike Stump65511702009-11-16 06:50:58 +00001351
Mike Stump65511702009-11-16 06:50:58 +00001352 llvm::BasicBlock *ContBlock = createBasicBlock();
1353 llvm::BasicBlock *NullBlock = 0;
1354 llvm::BasicBlock *NonZeroBlock = 0;
1355 if (CanBeZero) {
1356 NonZeroBlock = createBasicBlock();
1357 NullBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001358 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001359 EmitBlock(NonZeroBlock);
1360 }
1361
Mike Stump65511702009-11-16 06:50:58 +00001362 llvm::BasicBlock *BadCastBlock = 0;
Mike Stump65511702009-11-16 06:50:58 +00001363
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001364 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001365
1366 // See if this is a dynamic_cast(void*)
1367 if (ToVoid) {
1368 llvm::Value *This = V;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001369 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump6ca0e212009-11-16 22:52:20 +00001370 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1371 V = Builder.CreateLoad(V, "offset to top");
1372 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1373 V = Builder.CreateInBoundsGEP(This, V);
1374 V = Builder.CreateBitCast(V, LTy);
1375 } else {
1376 /// Call __dynamic_cast
1377 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1378 const llvm::FunctionType *FTy;
1379 std::vector<const llvm::Type*> ArgTys;
1380 const llvm::Type *PtrToInt8Ty
1381 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1382 ArgTys.push_back(PtrToInt8Ty);
1383 ArgTys.push_back(PtrToInt8Ty);
1384 ArgTys.push_back(PtrToInt8Ty);
1385 ArgTys.push_back(PtrDiffTy);
1386 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001387
1388 // FIXME: Calculate better hint.
1389 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001390
1391 assert(SrcTy->isRecordType() && "Src type must be record type!");
1392 assert(DestTy->isRecordType() && "Dest type must be record type!");
1393
Douglas Gregor247894b2009-12-23 22:04:40 +00001394 llvm::Value *SrcArg
1395 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1396 llvm::Value *DestArg
1397 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001398
Mike Stump6ca0e212009-11-16 22:52:20 +00001399 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1400 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001401 V, SrcArg, DestArg, hint);
Mike Stump6ca0e212009-11-16 22:52:20 +00001402 V = Builder.CreateBitCast(V, LTy);
1403
1404 if (ThrowOnBad) {
1405 BadCastBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001406 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump6ca0e212009-11-16 22:52:20 +00001407 EmitBlock(BadCastBlock);
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001408 /// Invoke __cxa_bad_cast
Mike Stump6ca0e212009-11-16 22:52:20 +00001409 ResultType = llvm::Type::getVoidTy(VMContext);
1410 const llvm::FunctionType *FBadTy;
Mike Stump3afea1d2009-11-17 03:01:03 +00001411 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001412 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001413 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1414 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1415 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1416 EmitBlock(Cont);
1417 } else {
1418 // FIXME: Does this ever make sense?
1419 Builder.CreateCall(F)->setDoesNotReturn();
1420 }
Mike Stumpe8cdcc92009-11-17 00:08:50 +00001421 Builder.CreateUnreachable();
Mike Stump6ca0e212009-11-16 22:52:20 +00001422 }
Mike Stump65511702009-11-16 06:50:58 +00001423 }
1424
1425 if (CanBeZero) {
1426 Builder.CreateBr(ContBlock);
1427 EmitBlock(NullBlock);
1428 Builder.CreateBr(ContBlock);
1429 }
1430 EmitBlock(ContBlock);
1431 if (CanBeZero) {
1432 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump4d0e9092009-11-17 00:10:05 +00001433 PHI->reserveOperandSpace(2);
Mike Stump65511702009-11-16 06:50:58 +00001434 PHI->addIncoming(V, NonZeroBlock);
1435 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001436 V = PHI;
1437 }
1438
1439 return V;
1440}