blob: e3b5f71b271f1f2c1b813af01a5aeefb5d6ff9cf [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.
Anders Carlssona7911fa2010-10-27 13:28:46 +000058static bool canDevirtualizeMemberFunctionCalls(const Expr *Base,
59 const CXXMethodDecl *MD) {
60
61 // If the member function has the "final" attribute, we know that it can't be
62 // overridden and can therefor devirtualize it.
63 if (MD->hasAttr<FinalAttr>())
64 return true;
65
Anders Carlsson27da15b2010-01-01 20:29:01 +000066 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
67 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
68 // This is a record decl. We know the type and can devirtualize it.
69 return VD->getType()->isRecordType();
70 }
71
72 return false;
73 }
74
75 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +000076 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +000077 return true;
78
79 // And calls on bound temporaries.
80 if (isa<CXXBindTemporaryExpr>(Base))
81 return true;
82
83 // Check if this is a call expr that returns a record type.
84 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
85 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +000086
Anders Carlsson27da15b2010-01-01 20:29:01 +000087 // We can't devirtualize the call.
88 return false;
89}
90
91RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
92 ReturnValueSlot ReturnValue) {
93 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
94 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
95
96 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
97 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
98
Devang Patel91bbb552010-09-30 19:05:55 +000099 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000100 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
101 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000102 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
103 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
104 DI->getOrCreateRecordType(PTy->getPointeeType(),
105 MD->getParent()->getLocation());
106 }
107 }
108
Anders Carlsson27da15b2010-01-01 20:29:01 +0000109 if (MD->isStatic()) {
110 // The method is static, emit it as we would a regular call.
111 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
112 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
113 ReturnValue, CE->arg_begin(), CE->arg_end());
114 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000115
John McCall0d635f52010-09-03 01:26:39 +0000116 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000117 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000118 if (ME->isArrow())
119 This = EmitScalarExpr(ME->getBase());
120 else {
121 LValue BaseLV = EmitLValue(ME->getBase());
Fariborz Jahanianf93ac892010-09-10 18:56:35 +0000122 if (BaseLV.isPropertyRef() || BaseLV.isKVCRef()) {
123 QualType QT = ME->getBase()->getType();
124 RValue RV =
125 BaseLV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(BaseLV, QT)
126 : EmitLoadOfKVCRefLValue(BaseLV, QT);
127 This = RV.isScalar() ? RV.getScalarVal() : RV.getAggregateAddr();
128 }
129 else
130 This = BaseLV.getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000131 }
132
John McCall0d635f52010-09-03 01:26:39 +0000133 if (MD->isTrivial()) {
134 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
135
Douglas Gregorec3bec02010-09-27 22:37:28 +0000136 assert(MD->isCopyAssignmentOperator() && "unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000137 // We don't like to generate the trivial copy assignment operator when
138 // it isn't necessary; just produce the proper effect here.
139 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
140 EmitAggregateCopy(This, RHS, CE->getType());
141 return RValue::get(This);
142 }
143
John McCall0d635f52010-09-03 01:26:39 +0000144 // Compute the function type we're calling.
145 const CGFunctionInfo &FInfo =
146 (isa<CXXDestructorDecl>(MD)
147 ? CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
148 Dtor_Complete)
149 : CGM.getTypes().getFunctionInfo(MD));
150
151 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
152 const llvm::Type *Ty
153 = CGM.getTypes().GetFunctionType(FInfo, FPT->isVariadic());
154
Anders Carlsson27da15b2010-01-01 20:29:01 +0000155 // C++ [class.virtual]p12:
156 // Explicit qualification with the scope operator (5.1) suppresses the
157 // virtual call mechanism.
158 //
159 // We also don't emit a virtual call if the base expression has a record type
160 // because then we know what the type is.
John McCall0d635f52010-09-03 01:26:39 +0000161 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
Anders Carlssona7911fa2010-10-27 13:28:46 +0000162 && !canDevirtualizeMemberFunctionCalls(ME->getBase(), MD);
John McCall0d635f52010-09-03 01:26:39 +0000163
Anders Carlsson27da15b2010-01-01 20:29:01 +0000164 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000165 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
166 if (UseVirtualCall) {
167 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000168 } else {
John McCall0d635f52010-09-03 01:26:39 +0000169 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000170 }
John McCall0d635f52010-09-03 01:26:39 +0000171 } else if (UseVirtualCall) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000172 Callee = BuildVirtualCall(MD, This, Ty);
173 } else {
174 Callee = CGM.GetAddrOfFunction(MD, Ty);
175 }
176
Anders Carlssone36a6b32010-01-02 01:01:18 +0000177 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000178 CE->arg_begin(), CE->arg_end());
179}
180
181RValue
182CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
183 ReturnValueSlot ReturnValue) {
184 const BinaryOperator *BO =
185 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
186 const Expr *BaseExpr = BO->getLHS();
187 const Expr *MemFnExpr = BO->getRHS();
188
189 const MemberPointerType *MPT =
190 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000191
Anders Carlsson27da15b2010-01-01 20:29:01 +0000192 const FunctionProtoType *FPT =
193 MPT->getPointeeType()->getAs<FunctionProtoType>();
194 const CXXRecordDecl *RD =
195 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
196
Anders Carlsson27da15b2010-01-01 20:29:01 +0000197 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000198 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000199
200 // Emit the 'this' pointer.
201 llvm::Value *This;
202
John McCalle3027922010-08-25 11:45:40 +0000203 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000204 This = EmitScalarExpr(BaseExpr);
205 else
206 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000207
John McCall475999d2010-08-22 00:05:51 +0000208 // Ask the ABI to load the callee. Note that This is modified.
209 llvm::Value *Callee =
210 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000211
Anders Carlsson27da15b2010-01-01 20:29:01 +0000212 CallArgList Args;
213
214 QualType ThisType =
215 getContext().getPointerType(getContext().getTagDeclType(RD));
216
217 // Push the this ptr.
218 Args.push_back(std::make_pair(RValue::get(This), ThisType));
219
220 // And the rest of the call args
221 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallab26cfa2010-02-05 21:31:56 +0000222 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
223 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000224 ReturnValue, Args);
225}
226
227RValue
228CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
229 const CXXMethodDecl *MD,
230 ReturnValueSlot ReturnValue) {
231 assert(MD->isInstance() &&
232 "Trying to emit a member call expr on a static method!");
Douglas Gregorec3bec02010-09-27 22:37:28 +0000233 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000234 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
235 if (ClassDecl->hasTrivialCopyAssignment()) {
236 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
237 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Fariborz Jahanian43a40f92010-05-10 22:57:35 +0000238 LValue LV = EmitLValue(E->getArg(0));
239 llvm::Value *This;
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000240 if (LV.isPropertyRef() || LV.isKVCRef()) {
John McCall7a626f62010-09-15 10:14:12 +0000241 AggValueSlot Slot = CreateAggTemp(E->getArg(1)->getType());
242 EmitAggExpr(E->getArg(1), Slot);
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000243 if (LV.isPropertyRef())
John McCall7a626f62010-09-15 10:14:12 +0000244 EmitObjCPropertySet(LV.getPropertyRefExpr(), Slot.asRValue());
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000245 else
John McCall7a626f62010-09-15 10:14:12 +0000246 EmitObjCPropertySet(LV.getKVCRefExpr(), Slot.asRValue());
Fariborz Jahaniane1b45a52010-05-15 23:05:52 +0000247 return RValue::getAggregate(0, false);
Fariborz Jahanian43a40f92010-05-10 22:57:35 +0000248 }
249 else
250 This = LV.getAddress();
251
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
253 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000254 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000255 return RValue::get(This);
256 }
257 }
258
259 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
260 const llvm::Type *Ty =
261 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
262 FPT->isVariadic());
Fariborz Jahanianfdf474b2010-05-07 18:56:13 +0000263 LValue LV = EmitLValue(E->getArg(0));
264 llvm::Value *This;
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000265 if (LV.isPropertyRef() || LV.isKVCRef()) {
266 QualType QT = E->getArg(0)->getType();
267 RValue RV =
268 LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT)
269 : EmitLoadOfKVCRefLValue(LV, QT);
Fariborz Jahanian6855ba22010-05-20 16:46:55 +0000270 assert (!RV.isScalar() && "EmitCXXOperatorMemberCallExpr");
271 This = RV.getAggregateAddr();
Fariborz Jahanianfdf474b2010-05-07 18:56:13 +0000272 }
273 else
274 This = LV.getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000275
276 llvm::Value *Callee;
Anders Carlssona7911fa2010-10-27 13:28:46 +0000277 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0), MD))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000278 Callee = BuildVirtualCall(MD, This, Ty);
279 else
280 Callee = CGM.GetAddrOfFunction(MD, Ty);
281
Anders Carlssone36a6b32010-01-02 01:01:18 +0000282 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000283 E->arg_begin() + 1, E->arg_end());
284}
285
286void
John McCall7a626f62010-09-15 10:14:12 +0000287CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
288 AggValueSlot Dest) {
289 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000290 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000291
292 // If we require zero initialization before (or instead of) calling the
293 // constructor, as can be the case with a non-user-provided default
294 // constructor, emit the zero initialization now.
295 if (E->requiresZeroInitialization())
John McCall7a626f62010-09-15 10:14:12 +0000296 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000297
298 // If this is a call to a trivial default constructor, do nothing.
299 if (CD->isTrivial() && CD->isDefaultConstructor())
300 return;
301
John McCall8ea46b62010-09-18 00:58:34 +0000302 // Elide the constructor if we're constructing from a temporary.
303 // The temporary check is required because Sema sets this on NRVO
304 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000306 assert(getContext().hasSameUnqualifiedType(E->getType(),
307 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000308 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
309 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000310 return;
311 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000313
314 const ConstantArrayType *Array
315 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000316 if (Array) {
317 QualType BaseElementTy = getContext().getBaseElementType(Array);
318 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
319 BasePtr = llvm::PointerType::getUnqual(BasePtr);
320 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000321 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000322
323 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
324 E->arg_begin(), E->arg_end());
325 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000326 else {
327 CXXCtorType Type =
328 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
329 ? Ctor_Complete : Ctor_Base;
330 bool ForVirtualBase =
331 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
332
Anders Carlsson27da15b2010-01-01 20:29:01 +0000333 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000334 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000335 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000336 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000337}
338
John McCallaa4149a2010-08-23 01:17:59 +0000339/// Check whether the given operator new[] is the global placement
340/// operator new[].
341static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
342 const FunctionDecl *Fn) {
343 // Must be in global scope. Note that allocation functions can't be
344 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000345 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000346 return false;
347
348 // Signature must be void *operator new[](size_t, void*).
349 // The size_t is common to all operator new[]s.
350 if (Fn->getNumParams() != 2)
351 return false;
352
353 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
354 return (ParamType == Ctx.VoidPtrTy);
355}
356
John McCall8ed55a52010-09-02 09:58:18 +0000357static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
358 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000359 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000360 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000361
Anders Carlsson399f4992009-12-13 20:34:34 +0000362 // No cookie is required if the new operator being used is
363 // ::operator new[](size_t, void*).
364 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000365 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000366 return CharUnits::Zero();
367
John McCall8ed55a52010-09-02 09:58:18 +0000368 return CGF.CGM.getCXXABI().GetArrayCookieSize(E->getAllocatedType());
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000369}
370
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000371static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000372 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000373 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000374 llvm::Value *&NumElements,
375 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000376 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000377
378 const llvm::IntegerType *SizeTy =
379 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000380
John McCall8ed55a52010-09-02 09:58:18 +0000381 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
382
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000383 if (!E->isArray()) {
384 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
385 return SizeWithoutCookie;
386 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000387
John McCall8ed55a52010-09-02 09:58:18 +0000388 // Figure out the cookie size.
389 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
390
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000391 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000392 // We multiply the size of all dimensions for NumElements.
393 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000394 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000395 assert(NumElements->getType() == SizeTy && "element count not a size_t");
396
397 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000398 while (const ConstantArrayType *CAT
399 = CGF.getContext().getAsConstantArrayType(ElemType)) {
400 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000401 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000402 }
403
John McCall8ed55a52010-09-02 09:58:18 +0000404 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000405
Chris Lattner32ac5832010-07-20 21:55:52 +0000406 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
407 // Don't bloat the -O0 code.
408 if (llvm::ConstantInt *NumElementsC =
409 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000410 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000411 unsigned SizeWidth = NEC.getBitWidth();
412
413 // Determine if there is an overflow here by doing an extended multiply.
414 NEC.zext(SizeWidth*2);
415 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000416 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000417
418 if (!CookieSize.isZero()) {
419 // Save the current size without a cookie. We don't care if an
420 // overflow's already happened because SizeWithoutCookie isn't
421 // used if the allocator returns null or throws, as it should
422 // always do on an overflow.
423 llvm::APInt SWC = SC;
424 SWC.trunc(SizeWidth);
425 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
426
427 // Add the cookie size.
428 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000429 }
430
John McCall8ed55a52010-09-02 09:58:18 +0000431 if (SC.countLeadingZeros() >= SizeWidth) {
432 SC.trunc(SizeWidth);
433 Size = llvm::ConstantInt::get(SizeTy, SC);
434 } else {
435 // On overflow, produce a -1 so operator new throws.
436 Size = llvm::Constant::getAllOnesValue(SizeTy);
437 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000438
John McCall8ed55a52010-09-02 09:58:18 +0000439 // Scale NumElements while we're at it.
440 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
441 NumElements = llvm::ConstantInt::get(SizeTy, N);
442
443 // Otherwise, we don't need to do an overflow-checked multiplication if
444 // we're multiplying by one.
445 } else if (TypeSize.isOne()) {
446 assert(ArraySizeMultiplier == 1);
447
448 Size = NumElements;
449
450 // If we need a cookie, add its size in with an overflow check.
451 // This is maybe a little paranoid.
452 if (!CookieSize.isZero()) {
453 SizeWithoutCookie = Size;
454
455 llvm::Value *CookieSizeV
456 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
457
458 const llvm::Type *Types[] = { SizeTy };
459 llvm::Value *UAddF
460 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
461 llvm::Value *AddRes
462 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
463
464 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
465 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
466 Size = CGF.Builder.CreateSelect(DidOverflow,
467 llvm::ConstantInt::get(SizeTy, -1),
468 Size);
469 }
470
471 // Otherwise use the int.umul.with.overflow intrinsic.
472 } else {
473 llvm::Value *OutermostElementSize
474 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
475
476 llvm::Value *NumOutermostElements = NumElements;
477
478 // Scale NumElements by the array size multiplier. This might
479 // overflow, but only if the multiplication below also overflows,
480 // in which case this multiplication isn't used.
481 if (ArraySizeMultiplier != 1)
482 NumElements = CGF.Builder.CreateMul(NumElements,
483 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
484
485 // The requested size of the outermost array is non-constant.
486 // Multiply that by the static size of the elements of that array;
487 // on unsigned overflow, set the size to -1 to trigger an
488 // exception from the allocation routine. This is sufficient to
489 // prevent buffer overruns from the allocator returning a
490 // seemingly valid pointer to insufficient space. This idea comes
491 // originally from MSVC, and GCC has an open bug requesting
492 // similar behavior:
493 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
494 //
495 // This will not be sufficient for C++0x, which requires a
496 // specific exception class (std::bad_array_new_length).
497 // That will require ABI support that has not yet been specified.
498 const llvm::Type *Types[] = { SizeTy };
499 llvm::Value *UMulF
500 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
501 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
502 OutermostElementSize);
503
504 // The overflow bit.
505 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
506
507 // The result of the multiplication.
508 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
509
510 // If we have a cookie, we need to add that size in, too.
511 if (!CookieSize.isZero()) {
512 SizeWithoutCookie = Size;
513
514 llvm::Value *CookieSizeV
515 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
516 llvm::Value *UAddF
517 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
518 llvm::Value *AddRes
519 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
520
521 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
522
523 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
524 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
525 }
526
527 Size = CGF.Builder.CreateSelect(DidOverflow,
528 llvm::ConstantInt::get(SizeTy, -1),
529 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000530 }
John McCall8ed55a52010-09-02 09:58:18 +0000531
532 if (CookieSize.isZero())
533 SizeWithoutCookie = Size;
534 else
535 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
536
Chris Lattner32ac5832010-07-20 21:55:52 +0000537 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000538}
539
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000540static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
541 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000542
543 assert(E->getNumConstructorArgs() == 1 &&
544 "Can only have one argument to initializer of POD type.");
545
546 const Expr *Init = E->getConstructorArg(0);
547 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000548
549 unsigned Alignment =
550 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000551 if (!CGF.hasAggregateLLVMType(AllocType))
552 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000553 AllocType.isVolatileQualified(), Alignment,
554 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000555 else if (AllocType->isAnyComplexType())
556 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
557 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000558 else {
559 AggValueSlot Slot
560 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
561 CGF.EmitAggExpr(Init, Slot);
562 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000563}
564
565void
566CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
567 llvm::Value *NewPtr,
568 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000569 // We have a POD type.
570 if (E->getNumConstructorArgs() == 0)
571 return;
572
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000573 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
574
575 // Create a temporary for the loop index and initialize it with 0.
576 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
577 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
578 Builder.CreateStore(Zero, IndexPtr);
579
580 // Start the loop with a block that tests the condition.
581 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
582 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
583
584 EmitBlock(CondBlock);
585
586 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
587
588 // Generate: if (loop-index < number-of-elements fall to the loop body,
589 // otherwise, go to the block after the for-loop.
590 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
591 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
592 // If the condition is true, execute the body.
593 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
594
595 EmitBlock(ForBody);
596
597 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
598 // Inside the loop body, emit the constructor call on the array element.
599 Counter = Builder.CreateLoad(IndexPtr);
600 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
601 "arrayidx");
602 StoreAnyExprIntoOneUnit(*this, E, Address);
603
604 EmitBlock(ContinueBlock);
605
606 // Emit the increment of the loop counter.
607 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
608 Counter = Builder.CreateLoad(IndexPtr);
609 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
610 Builder.CreateStore(NextVal, IndexPtr);
611
612 // Finally, branch back up to the condition for the next iteration.
613 EmitBranch(CondBlock);
614
615 // Emit the fall-through block.
616 EmitBlock(AfterFor, true);
617}
618
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000619static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
620 llvm::Value *NewPtr, llvm::Value *Size) {
621 llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
622 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
623 if (NewPtr->getType() != BP)
624 NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
625
626 CGF.Builder.CreateCall5(CGF.CGM.getMemSetFn(BP, CGF.IntPtrTy), NewPtr,
627 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
628 Size,
629 llvm::ConstantInt::get(CGF.Int32Ty,
630 CGF.getContext().getTypeAlign(T)/8),
631 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
632 0));
633}
634
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000635static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
636 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000637 llvm::Value *NumElements,
638 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000639 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000640 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000641 bool RequiresZeroInitialization = false;
642 if (Ctor->getParent()->hasTrivialConstructor()) {
643 // If new expression did not specify value-initialization, then there
644 // is no initialization.
645 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
646 return;
647
John McCall614dbdc2010-08-22 21:01:12 +0000648 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000649 // Optimization: since zero initialization will just set the memory
650 // to all zeroes, generate a single memset to do it in one shot.
651 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
652 AllocSizeWithoutCookie);
653 return;
654 }
655
656 RequiresZeroInitialization = true;
657 }
658
659 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
660 E->constructor_arg_begin(),
661 E->constructor_arg_end(),
662 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000663 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000664 } else if (E->getNumConstructorArgs() == 1 &&
665 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
666 // Optimization: since zero initialization will just set the memory
667 // to all zeroes, generate a single memset to do it in one shot.
668 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
669 AllocSizeWithoutCookie);
670 return;
671 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000672 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
673 return;
674 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000675 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000676
677 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000678 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
679 // direct initialization. C++ [dcl.init]p5 requires that we
680 // zero-initialize storage if there are no user-declared constructors.
681 if (E->hasInitializer() &&
682 !Ctor->getParent()->hasUserDeclaredConstructor() &&
683 !Ctor->getParent()->isEmpty())
684 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
685
Douglas Gregore1823702010-07-07 23:37:33 +0000686 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
687 NewPtr, E->constructor_arg_begin(),
688 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000689
690 return;
691 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000692 // We have a POD type.
693 if (E->getNumConstructorArgs() == 0)
694 return;
695
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000696 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000697}
698
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000699namespace {
John McCall7f9c92a2010-09-17 00:50:28 +0000700/// A utility class for saving an rvalue.
701class SavedRValue {
702public:
703 enum Kind { ScalarLiteral, ScalarAddress,
704 AggregateLiteral, AggregateAddress,
705 Complex };
706
707private:
708 llvm::Value *Value;
709 Kind K;
710
711 SavedRValue(llvm::Value *V, Kind K) : Value(V), K(K) {}
712
713public:
714 SavedRValue() {}
715
716 static SavedRValue forScalarLiteral(llvm::Value *V) {
717 return SavedRValue(V, ScalarLiteral);
718 }
719
720 static SavedRValue forScalarAddress(llvm::Value *Addr) {
721 return SavedRValue(Addr, ScalarAddress);
722 }
723
724 static SavedRValue forAggregateLiteral(llvm::Value *V) {
725 return SavedRValue(V, AggregateLiteral);
726 }
727
728 static SavedRValue forAggregateAddress(llvm::Value *Addr) {
729 return SavedRValue(Addr, AggregateAddress);
730 }
731
732 static SavedRValue forComplexAddress(llvm::Value *Addr) {
733 return SavedRValue(Addr, Complex);
734 }
735
736 Kind getKind() const { return K; }
737 llvm::Value *getValue() const { return Value; }
738};
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000739} // end anonymous namespace
John McCall7f9c92a2010-09-17 00:50:28 +0000740
741/// Given an r-value, perform the code necessary to make sure that a
742/// future RestoreRValue will be able to load the value without
743/// domination concerns.
744static SavedRValue SaveRValue(CodeGenFunction &CGF, RValue RV) {
745 if (RV.isScalar()) {
746 llvm::Value *V = RV.getScalarVal();
747
748 // These automatically dominate and don't need to be saved.
749 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
750 return SavedRValue::forScalarLiteral(V);
751
752 // Everything else needs an alloca.
753 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
754 CGF.Builder.CreateStore(V, Addr);
755 return SavedRValue::forScalarAddress(Addr);
756 }
757
758 if (RV.isComplex()) {
759 CodeGenFunction::ComplexPairTy V = RV.getComplexVal();
760 const llvm::Type *ComplexTy =
761 llvm::StructType::get(CGF.getLLVMContext(),
762 V.first->getType(), V.second->getType(),
763 (void*) 0);
764 llvm::Value *Addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
765 CGF.StoreComplexToAddr(V, Addr, /*volatile*/ false);
766 return SavedRValue::forComplexAddress(Addr);
767 }
768
769 assert(RV.isAggregate());
770 llvm::Value *V = RV.getAggregateAddr(); // TODO: volatile?
771 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
772 return SavedRValue::forAggregateLiteral(V);
773
774 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
775 CGF.Builder.CreateStore(V, Addr);
776 return SavedRValue::forAggregateAddress(Addr);
777}
778
779/// Given a saved r-value produced by SaveRValue, perform the code
780/// necessary to restore it to usability at the current insertion
781/// point.
782static RValue RestoreRValue(CodeGenFunction &CGF, SavedRValue RV) {
783 switch (RV.getKind()) {
784 case SavedRValue::ScalarLiteral:
785 return RValue::get(RV.getValue());
786 case SavedRValue::ScalarAddress:
787 return RValue::get(CGF.Builder.CreateLoad(RV.getValue()));
788 case SavedRValue::AggregateLiteral:
789 return RValue::getAggregate(RV.getValue());
790 case SavedRValue::AggregateAddress:
791 return RValue::getAggregate(CGF.Builder.CreateLoad(RV.getValue()));
792 case SavedRValue::Complex:
793 return RValue::getComplex(CGF.LoadComplexFromAddr(RV.getValue(), false));
794 }
795
796 llvm_unreachable("bad saved r-value kind");
797 return RValue();
798}
799
John McCall824c2f52010-09-14 07:57:04 +0000800namespace {
801 /// A cleanup to call the given 'operator delete' function upon
802 /// abnormal exit from a new expression.
803 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
804 size_t NumPlacementArgs;
805 const FunctionDecl *OperatorDelete;
806 llvm::Value *Ptr;
807 llvm::Value *AllocSize;
808
809 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
810
811 public:
812 static size_t getExtraSize(size_t NumPlacementArgs) {
813 return NumPlacementArgs * sizeof(RValue);
814 }
815
816 CallDeleteDuringNew(size_t NumPlacementArgs,
817 const FunctionDecl *OperatorDelete,
818 llvm::Value *Ptr,
819 llvm::Value *AllocSize)
820 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
821 Ptr(Ptr), AllocSize(AllocSize) {}
822
823 void setPlacementArg(unsigned I, RValue Arg) {
824 assert(I < NumPlacementArgs && "index out of range");
825 getPlacementArgs()[I] = Arg;
826 }
827
828 void Emit(CodeGenFunction &CGF, bool IsForEH) {
829 const FunctionProtoType *FPT
830 = OperatorDelete->getType()->getAs<FunctionProtoType>();
831 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000832 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000833
834 CallArgList DeleteArgs;
835
836 // The first argument is always a void*.
837 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
838 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
839
840 // A member 'operator delete' can take an extra 'size_t' argument.
841 if (FPT->getNumArgs() == NumPlacementArgs + 2)
842 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
843
844 // Pass the rest of the arguments, which must match exactly.
845 for (unsigned I = 0; I != NumPlacementArgs; ++I)
846 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
847
848 // Call 'operator delete'.
849 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
850 CGF.CGM.GetAddrOfFunction(OperatorDelete),
851 ReturnValueSlot(), DeleteArgs, OperatorDelete);
852 }
853 };
John McCall7f9c92a2010-09-17 00:50:28 +0000854
855 /// A cleanup to call the given 'operator delete' function upon
856 /// abnormal exit from a new expression when the new expression is
857 /// conditional.
858 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
859 size_t NumPlacementArgs;
860 const FunctionDecl *OperatorDelete;
861 SavedRValue Ptr;
862 SavedRValue AllocSize;
863
864 SavedRValue *getPlacementArgs() {
865 return reinterpret_cast<SavedRValue*>(this+1);
866 }
867
868 public:
869 static size_t getExtraSize(size_t NumPlacementArgs) {
870 return NumPlacementArgs * sizeof(SavedRValue);
871 }
872
873 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
874 const FunctionDecl *OperatorDelete,
875 SavedRValue Ptr,
876 SavedRValue AllocSize)
877 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
878 Ptr(Ptr), AllocSize(AllocSize) {}
879
880 void setPlacementArg(unsigned I, SavedRValue Arg) {
881 assert(I < NumPlacementArgs && "index out of range");
882 getPlacementArgs()[I] = Arg;
883 }
884
885 void Emit(CodeGenFunction &CGF, bool IsForEH) {
886 const FunctionProtoType *FPT
887 = OperatorDelete->getType()->getAs<FunctionProtoType>();
888 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
889 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
890
891 CallArgList DeleteArgs;
892
893 // The first argument is always a void*.
894 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
895 DeleteArgs.push_back(std::make_pair(RestoreRValue(CGF, Ptr), *AI++));
896
897 // A member 'operator delete' can take an extra 'size_t' argument.
898 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
899 RValue RV = RestoreRValue(CGF, AllocSize);
900 DeleteArgs.push_back(std::make_pair(RV, *AI++));
901 }
902
903 // Pass the rest of the arguments, which must match exactly.
904 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
905 RValue RV = RestoreRValue(CGF, getPlacementArgs()[I]);
906 DeleteArgs.push_back(std::make_pair(RV, *AI++));
907 }
908
909 // Call 'operator delete'.
910 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
911 CGF.CGM.GetAddrOfFunction(OperatorDelete),
912 ReturnValueSlot(), DeleteArgs, OperatorDelete);
913 }
914 };
915}
916
917/// Enter a cleanup to call 'operator delete' if the initializer in a
918/// new-expression throws.
919static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
920 const CXXNewExpr *E,
921 llvm::Value *NewPtr,
922 llvm::Value *AllocSize,
923 const CallArgList &NewArgs) {
924 // If we're not inside a conditional branch, then the cleanup will
925 // dominate and we can do the easier (and more efficient) thing.
926 if (!CGF.isInConditionalBranch()) {
927 CallDeleteDuringNew *Cleanup = CGF.EHStack
928 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
929 E->getNumPlacementArgs(),
930 E->getOperatorDelete(),
931 NewPtr, AllocSize);
932 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
933 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
934
935 return;
936 }
937
938 // Otherwise, we need to save all this stuff.
939 SavedRValue SavedNewPtr = SaveRValue(CGF, RValue::get(NewPtr));
940 SavedRValue SavedAllocSize = SaveRValue(CGF, RValue::get(AllocSize));
941
942 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
943 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
944 E->getNumPlacementArgs(),
945 E->getOperatorDelete(),
946 SavedNewPtr,
947 SavedAllocSize);
948 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
949 Cleanup->setPlacementArg(I, SaveRValue(CGF, NewArgs[I+1].first));
950
951 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000952}
953
Anders Carlssoncc52f652009-09-22 22:53:17 +0000954llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoncc52f652009-09-22 22:53:17 +0000955 QualType AllocType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000956 if (AllocType->isArrayType())
957 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
958 AllocType = AType->getElementType();
959
Anders Carlssoncc52f652009-09-22 22:53:17 +0000960 FunctionDecl *NewFD = E->getOperatorNew();
961 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
962
963 CallArgList NewArgs;
964
965 // The allocation size is the first argument.
966 QualType SizeTy = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000967
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000968 llvm::Value *NumElements = 0;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000969 llvm::Value *AllocSizeWithoutCookie = 0;
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000970 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000971 *this, E, NumElements,
972 AllocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000973
Anders Carlssoncc52f652009-09-22 22:53:17 +0000974 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
975
976 // Emit the rest of the arguments.
977 // FIXME: Ideally, this should just use EmitCallArgs.
978 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
979
980 // First, use the types from the function type.
981 // We start at 1 here because the first argument (the allocation size)
982 // has already been emitted.
983 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
984 QualType ArgType = NewFTy->getArgType(i);
985
986 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
987 getTypePtr() ==
988 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
989 "type mismatch in call argument!");
990
991 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
992 ArgType));
993
994 }
995
996 // Either we've emitted all the call args, or we have a call to a
997 // variadic function.
998 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
999 "Extra arguments in non-variadic function!");
1000
1001 // If we still have any arguments, emit them using the type of the argument.
1002 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
1003 NewArg != NewArgEnd; ++NewArg) {
1004 QualType ArgType = NewArg->getType();
1005 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
1006 ArgType));
1007 }
1008
1009 // Emit the call to new.
1010 RValue RV =
John McCallab26cfa2010-02-05 21:31:56 +00001011 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001012 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001013
1014 // If an allocation function is declared with an empty exception specification
1015 // it returns null to indicate failure to allocate storage. [expr.new]p13.
1016 // (We don't need to check for null when there's no new initializer and
1017 // we're allocating a POD type).
1018 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
1019 !(AllocType->isPODType() && !E->hasInitializer());
1020
John McCall8ed55a52010-09-02 09:58:18 +00001021 llvm::BasicBlock *NullCheckSource = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001022 llvm::BasicBlock *NewNotNull = 0;
1023 llvm::BasicBlock *NewEnd = 0;
1024
1025 llvm::Value *NewPtr = RV.getScalarVal();
John McCall8ed55a52010-09-02 09:58:18 +00001026 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001027
1028 if (NullCheckResult) {
John McCall8ed55a52010-09-02 09:58:18 +00001029 NullCheckSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001030 NewNotNull = createBasicBlock("new.notnull");
1031 NewEnd = createBasicBlock("new.end");
1032
John McCall8ed55a52010-09-02 09:58:18 +00001033 llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
1034 Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001035 EmitBlock(NewNotNull);
1036 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001037
John McCall8ed55a52010-09-02 09:58:18 +00001038 assert((AllocSize == AllocSizeWithoutCookie) ==
1039 CalculateCookiePadding(*this, E).isZero());
1040 if (AllocSize != AllocSizeWithoutCookie) {
1041 assert(E->isArray());
1042 NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
1043 AllocType);
1044 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001045
John McCall824c2f52010-09-14 07:57:04 +00001046 // If there's an operator delete, enter a cleanup to call it if an
1047 // exception is thrown.
1048 EHScopeStack::stable_iterator CallOperatorDelete;
1049 if (E->getOperatorDelete()) {
John McCall7f9c92a2010-09-17 00:50:28 +00001050 EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
John McCall824c2f52010-09-14 07:57:04 +00001051 CallOperatorDelete = EHStack.stable_begin();
1052 }
1053
Douglas Gregor040ad502010-09-02 23:24:14 +00001054 const llvm::Type *ElementPtrTy
1055 = ConvertTypeForMem(AllocType)->getPointerTo(AS);
John McCall8ed55a52010-09-02 09:58:18 +00001056 NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001057
John McCall8ed55a52010-09-02 09:58:18 +00001058 if (E->isArray()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001059 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001060
1061 // NewPtr is a pointer to the base element type. If we're
1062 // allocating an array of arrays, we'll need to cast back to the
1063 // array pointer type.
Douglas Gregor040ad502010-09-02 23:24:14 +00001064 const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
John McCall8ed55a52010-09-02 09:58:18 +00001065 if (NewPtr->getType() != ResultTy)
1066 NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
1067 } else {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001068 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001069 }
John McCall824c2f52010-09-14 07:57:04 +00001070
1071 // Deactivate the 'operator delete' cleanup if we finished
1072 // initialization.
1073 if (CallOperatorDelete.isValid())
1074 DeactivateCleanupBlock(CallOperatorDelete);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001075
Anders Carlssoncc52f652009-09-22 22:53:17 +00001076 if (NullCheckResult) {
1077 Builder.CreateBr(NewEnd);
John McCall8ed55a52010-09-02 09:58:18 +00001078 llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001079 EmitBlock(NewEnd);
1080
1081 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1082 PHI->reserveOperandSpace(2);
John McCall8ed55a52010-09-02 09:58:18 +00001083 PHI->addIncoming(NewPtr, NotNullSource);
1084 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1085 NullCheckSource);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001086
1087 NewPtr = PHI;
1088 }
John McCall8ed55a52010-09-02 09:58:18 +00001089
Anders Carlssoncc52f652009-09-22 22:53:17 +00001090 return NewPtr;
1091}
1092
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001093void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1094 llvm::Value *Ptr,
1095 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001096 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1097
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001098 const FunctionProtoType *DeleteFTy =
1099 DeleteFD->getType()->getAs<FunctionProtoType>();
1100
1101 CallArgList DeleteArgs;
1102
Anders Carlsson21122cf2009-12-13 20:04:38 +00001103 // Check if we need to pass the size to the delete operator.
1104 llvm::Value *Size = 0;
1105 QualType SizeTy;
1106 if (DeleteFTy->getNumArgs() == 2) {
1107 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001108 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1109 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1110 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001111 }
1112
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001113 QualType ArgTy = DeleteFTy->getArgType(0);
1114 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1115 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1116
Anders Carlsson21122cf2009-12-13 20:04:38 +00001117 if (Size)
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001118 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001119
1120 // Emit the call to delete.
John McCallab26cfa2010-02-05 21:31:56 +00001121 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001122 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001123 DeleteArgs, DeleteFD);
1124}
1125
John McCall8ed55a52010-09-02 09:58:18 +00001126namespace {
1127 /// Calls the given 'operator delete' on a single object.
1128 struct CallObjectDelete : EHScopeStack::Cleanup {
1129 llvm::Value *Ptr;
1130 const FunctionDecl *OperatorDelete;
1131 QualType ElementType;
1132
1133 CallObjectDelete(llvm::Value *Ptr,
1134 const FunctionDecl *OperatorDelete,
1135 QualType ElementType)
1136 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1137
1138 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1139 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1140 }
1141 };
1142}
1143
1144/// Emit the code for deleting a single object.
1145static void EmitObjectDelete(CodeGenFunction &CGF,
1146 const FunctionDecl *OperatorDelete,
1147 llvm::Value *Ptr,
1148 QualType ElementType) {
1149 // Find the destructor for the type, if applicable. If the
1150 // destructor is virtual, we'll just emit the vcall and return.
1151 const CXXDestructorDecl *Dtor = 0;
1152 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1153 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1154 if (!RD->hasTrivialDestructor()) {
1155 Dtor = RD->getDestructor();
1156
1157 if (Dtor->isVirtual()) {
1158 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001159 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1160 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001161 /*isVariadic=*/false);
1162
1163 llvm::Value *Callee
1164 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1165 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1166 0, 0);
1167
1168 // The dtor took care of deleting the object.
1169 return;
1170 }
1171 }
1172 }
1173
1174 // Make sure that we call delete even if the dtor throws.
1175 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1176 Ptr, OperatorDelete, ElementType);
1177
1178 if (Dtor)
1179 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1180 /*ForVirtualBase=*/false, Ptr);
1181
1182 CGF.PopCleanupBlock();
1183}
1184
1185namespace {
1186 /// Calls the given 'operator delete' on an array of objects.
1187 struct CallArrayDelete : EHScopeStack::Cleanup {
1188 llvm::Value *Ptr;
1189 const FunctionDecl *OperatorDelete;
1190 llvm::Value *NumElements;
1191 QualType ElementType;
1192 CharUnits CookieSize;
1193
1194 CallArrayDelete(llvm::Value *Ptr,
1195 const FunctionDecl *OperatorDelete,
1196 llvm::Value *NumElements,
1197 QualType ElementType,
1198 CharUnits CookieSize)
1199 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1200 ElementType(ElementType), CookieSize(CookieSize) {}
1201
1202 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1203 const FunctionProtoType *DeleteFTy =
1204 OperatorDelete->getType()->getAs<FunctionProtoType>();
1205 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1206
1207 CallArgList Args;
1208
1209 // Pass the pointer as the first argument.
1210 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1211 llvm::Value *DeletePtr
1212 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1213 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1214
1215 // Pass the original requested size as the second argument.
1216 if (DeleteFTy->getNumArgs() == 2) {
1217 QualType size_t = DeleteFTy->getArgType(1);
1218 const llvm::IntegerType *SizeTy
1219 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1220
1221 CharUnits ElementTypeSize =
1222 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1223
1224 // The size of an element, multiplied by the number of elements.
1225 llvm::Value *Size
1226 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1227 Size = CGF.Builder.CreateMul(Size, NumElements);
1228
1229 // Plus the size of the cookie if applicable.
1230 if (!CookieSize.isZero()) {
1231 llvm::Value *CookieSizeV
1232 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1233 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1234 }
1235
1236 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1237 }
1238
1239 // Emit the call to delete.
1240 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1241 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1242 ReturnValueSlot(), Args, OperatorDelete);
1243 }
1244 };
1245}
1246
1247/// Emit the code for deleting an array of objects.
1248static void EmitArrayDelete(CodeGenFunction &CGF,
1249 const FunctionDecl *OperatorDelete,
1250 llvm::Value *Ptr,
1251 QualType ElementType) {
1252 llvm::Value *NumElements = 0;
1253 llvm::Value *AllocatedPtr = 0;
1254 CharUnits CookieSize;
1255 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, ElementType,
1256 NumElements, AllocatedPtr, CookieSize);
1257
1258 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1259
1260 // Make sure that we call delete even if one of the dtors throws.
1261 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1262 AllocatedPtr, OperatorDelete,
1263 NumElements, ElementType,
1264 CookieSize);
1265
1266 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1267 if (!RD->hasTrivialDestructor()) {
1268 assert(NumElements && "ReadArrayCookie didn't find element count"
1269 " for a class with destructor");
1270 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1271 }
1272 }
1273
1274 CGF.PopCleanupBlock();
1275}
1276
Anders Carlssoncc52f652009-09-22 22:53:17 +00001277void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001278
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001279 // Get at the argument before we performed the implicit conversion
1280 // to void*.
1281 const Expr *Arg = E->getArgument();
1282 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001283 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001284 ICE->getType()->isVoidPointerType())
1285 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001286 else
1287 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001288 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001289
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001290 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001291
1292 // Null check the pointer.
1293 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1294 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1295
1296 llvm::Value *IsNull =
1297 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1298 "isnull");
1299
1300 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1301 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001302
John McCall8ed55a52010-09-02 09:58:18 +00001303 // We might be deleting a pointer to array. If so, GEP down to the
1304 // first non-array element.
1305 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1306 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1307 if (DeleteTy->isConstantArrayType()) {
1308 llvm::Value *Zero = Builder.getInt32(0);
1309 llvm::SmallVector<llvm::Value*,8> GEP;
1310
1311 GEP.push_back(Zero); // point at the outermost array
1312
1313 // For each layer of array type we're pointing at:
1314 while (const ConstantArrayType *Arr
1315 = getContext().getAsConstantArrayType(DeleteTy)) {
1316 // 1. Unpeel the array type.
1317 DeleteTy = Arr->getElementType();
1318
1319 // 2. GEP to the first element of the array.
1320 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001321 }
John McCall8ed55a52010-09-02 09:58:18 +00001322
1323 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001324 }
1325
Douglas Gregor04f36212010-09-02 17:38:50 +00001326 assert(ConvertTypeForMem(DeleteTy) ==
1327 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001328
1329 if (E->isArrayForm()) {
1330 EmitArrayDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1331 } else {
1332 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1333 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001334
Anders Carlssoncc52f652009-09-22 22:53:17 +00001335 EmitBlock(DeleteEnd);
1336}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001337
1338llvm::Value * CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1339 QualType Ty = E->getType();
1340 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001341
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001342 if (E->isTypeOperand()) {
1343 llvm::Constant *TypeInfo =
1344 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1345 return Builder.CreateBitCast(TypeInfo, LTy);
1346 }
1347
Mike Stumpc9b231c2009-11-15 08:09:41 +00001348 Expr *subE = E->getExprOperand();
Mike Stump6fdfea62009-11-17 22:33:00 +00001349 Ty = subE->getType();
1350 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1351 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc9b231c2009-11-15 08:09:41 +00001352 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1353 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1354 if (RD->isPolymorphic()) {
1355 // FIXME: if subE is an lvalue do
1356 LValue Obj = EmitLValue(subE);
1357 llvm::Value *This = Obj.getAddress();
Mike Stump1bf924b2009-11-15 16:52:53 +00001358 // We need to do a zero check for *p, unless it has NonNullAttr.
1359 // FIXME: PointerType->hasAttr<NonNullAttr>()
1360 bool CanBeZero = false;
Mike Stumpc2c03342009-11-17 00:45:21 +00001361 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001362 if (UO->getOpcode() == UO_Deref)
Mike Stump1bf924b2009-11-15 16:52:53 +00001363 CanBeZero = true;
1364 if (CanBeZero) {
1365 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1366 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1367
Dan Gohman8fc50c22010-10-26 18:44:08 +00001368 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1369 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stump1bf924b2009-11-15 16:52:53 +00001370 NonZeroBlock, ZeroBlock);
1371 EmitBlock(ZeroBlock);
1372 /// Call __cxa_bad_typeid
1373 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1374 const llvm::FunctionType *FTy;
1375 FTy = llvm::FunctionType::get(ResultType, false);
1376 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stump65511702009-11-16 06:50:58 +00001377 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stump1bf924b2009-11-15 16:52:53 +00001378 Builder.CreateUnreachable();
1379 EmitBlock(NonZeroBlock);
1380 }
Dan Gohman8fc50c22010-10-26 18:44:08 +00001381 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc9b231c2009-11-15 08:09:41 +00001382 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1383 V = Builder.CreateLoad(V);
1384 return V;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001385 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001386 }
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001387 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001388}
Mike Stump65511702009-11-16 06:50:58 +00001389
1390llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1391 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001392 QualType SrcTy = DCE->getSubExpr()->getType();
1393 QualType DestTy = DCE->getTypeAsWritten();
1394 QualType InnerType = DestTy->getPointeeType();
1395
Mike Stump65511702009-11-16 06:50:58 +00001396 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001397
Mike Stump65511702009-11-16 06:50:58 +00001398 bool CanBeZero = false;
Mike Stump65511702009-11-16 06:50:58 +00001399 bool ToVoid = false;
Mike Stump6ca0e212009-11-16 22:52:20 +00001400 bool ThrowOnBad = false;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001401 if (DestTy->isPointerType()) {
Mike Stump65511702009-11-16 06:50:58 +00001402 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1403 CanBeZero = true;
1404 if (InnerType->isVoidType())
1405 ToVoid = true;
1406 } else {
1407 LTy = LTy->getPointerTo();
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001408
1409 // FIXME: What if exceptions are disabled?
Mike Stump65511702009-11-16 06:50:58 +00001410 ThrowOnBad = true;
1411 }
1412
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001413 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1414 SrcTy = SrcTy->getPointeeType();
1415 SrcTy = SrcTy.getUnqualifiedType();
1416
Anders Carlsson0087bc82009-12-18 14:55:04 +00001417 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001418 DestTy = DestTy->getPointeeType();
1419 DestTy = DestTy.getUnqualifiedType();
Mike Stump65511702009-11-16 06:50:58 +00001420
Mike Stump65511702009-11-16 06:50:58 +00001421 llvm::BasicBlock *ContBlock = createBasicBlock();
1422 llvm::BasicBlock *NullBlock = 0;
1423 llvm::BasicBlock *NonZeroBlock = 0;
1424 if (CanBeZero) {
1425 NonZeroBlock = createBasicBlock();
1426 NullBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001427 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001428 EmitBlock(NonZeroBlock);
1429 }
1430
Mike Stump65511702009-11-16 06:50:58 +00001431 llvm::BasicBlock *BadCastBlock = 0;
Mike Stump65511702009-11-16 06:50:58 +00001432
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001433 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001434
1435 // See if this is a dynamic_cast(void*)
1436 if (ToVoid) {
1437 llvm::Value *This = V;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001438 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump6ca0e212009-11-16 22:52:20 +00001439 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1440 V = Builder.CreateLoad(V, "offset to top");
1441 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1442 V = Builder.CreateInBoundsGEP(This, V);
1443 V = Builder.CreateBitCast(V, LTy);
1444 } else {
1445 /// Call __dynamic_cast
1446 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1447 const llvm::FunctionType *FTy;
1448 std::vector<const llvm::Type*> ArgTys;
1449 const llvm::Type *PtrToInt8Ty
1450 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1451 ArgTys.push_back(PtrToInt8Ty);
1452 ArgTys.push_back(PtrToInt8Ty);
1453 ArgTys.push_back(PtrToInt8Ty);
1454 ArgTys.push_back(PtrDiffTy);
1455 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001456
1457 // FIXME: Calculate better hint.
1458 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001459
1460 assert(SrcTy->isRecordType() && "Src type must be record type!");
1461 assert(DestTy->isRecordType() && "Dest type must be record type!");
1462
Douglas Gregor247894b2009-12-23 22:04:40 +00001463 llvm::Value *SrcArg
1464 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1465 llvm::Value *DestArg
1466 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001467
Mike Stump6ca0e212009-11-16 22:52:20 +00001468 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1469 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001470 V, SrcArg, DestArg, hint);
Mike Stump6ca0e212009-11-16 22:52:20 +00001471 V = Builder.CreateBitCast(V, LTy);
1472
1473 if (ThrowOnBad) {
1474 BadCastBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001475 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump6ca0e212009-11-16 22:52:20 +00001476 EmitBlock(BadCastBlock);
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001477 /// Invoke __cxa_bad_cast
Mike Stump6ca0e212009-11-16 22:52:20 +00001478 ResultType = llvm::Type::getVoidTy(VMContext);
1479 const llvm::FunctionType *FBadTy;
Mike Stump3afea1d2009-11-17 03:01:03 +00001480 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001481 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001482 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1483 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1484 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1485 EmitBlock(Cont);
1486 } else {
1487 // FIXME: Does this ever make sense?
1488 Builder.CreateCall(F)->setDoesNotReturn();
1489 }
Mike Stumpe8cdcc92009-11-17 00:08:50 +00001490 Builder.CreateUnreachable();
Mike Stump6ca0e212009-11-16 22:52:20 +00001491 }
Mike Stump65511702009-11-16 06:50:58 +00001492 }
1493
1494 if (CanBeZero) {
1495 Builder.CreateBr(ContBlock);
1496 EmitBlock(NullBlock);
1497 Builder.CreateBr(ContBlock);
1498 }
1499 EmitBlock(ContBlock);
1500 if (CanBeZero) {
1501 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump4d0e9092009-11-17 00:10:05 +00001502 PHI->reserveOperandSpace(2);
Mike Stump65511702009-11-16 06:50:58 +00001503 PHI->addIncoming(V, NonZeroBlock);
1504 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001505 V = PHI;
1506 }
1507
1508 return V;
1509}