blob: e66afc6290c2f7d7393df444db624eb1e52a93b0 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelc69e1cf2010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000020#include "llvm/Support/CallSite.h"
21
Anders Carlsson16d81b82009-09-22 22:53:17 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson3b5ad222010-01-01 20:29:01 +000025RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26 llvm::Value *Callee,
27 ReturnValueSlot ReturnValue,
28 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000029 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000030 CallExpr::const_arg_iterator ArgBeg,
31 CallExpr::const_arg_iterator ArgEnd) {
32 assert(MD->isInstance() &&
33 "Trying to emit a member call expr on a static method!");
34
35 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
36
37 CallArgList Args;
38
39 // Push the this ptr.
40 Args.push_back(std::make_pair(RValue::get(This),
41 MD->getThisType(getContext())));
42
Anders Carlssonc997d422010-01-02 01:01:18 +000043 // If there is a VTT parameter, emit it.
44 if (VTT) {
45 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
46 Args.push_back(std::make_pair(RValue::get(VTT), T));
47 }
48
Anders Carlsson3b5ad222010-01-01 20:29:01 +000049 // And the rest of the call args
50 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
51
John McCall04a67a62010-02-05 21:31:56 +000052 QualType ResultType = FPT->getResultType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000053 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
54 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000055 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000056}
57
Anders Carlsson1679f5a2011-01-29 03:52:01 +000058static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000059 const Expr *E = Base;
60
61 while (true) {
62 E = E->IgnoreParens();
63 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
64 if (CE->getCastKind() == CK_DerivedToBase ||
65 CE->getCastKind() == CK_UncheckedDerivedToBase ||
66 CE->getCastKind() == CK_NoOp) {
67 E = CE->getSubExpr();
68 continue;
69 }
70 }
71
72 break;
73 }
74
75 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000076 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
77 DerivedType = PTy->getPointeeType();
78
79 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
80}
81
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000082// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
83// quite what we want.
84static const Expr *skipNoOpCastsAndParens(const Expr *E) {
85 while (true) {
86 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
87 E = PE->getSubExpr();
88 continue;
89 }
90
91 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
92 if (CE->getCastKind() == CK_NoOp) {
93 E = CE->getSubExpr();
94 continue;
95 }
96 }
97 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
98 if (UO->getOpcode() == UO_Extension) {
99 E = UO->getSubExpr();
100 continue;
101 }
102 }
103 return E;
104 }
105}
106
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000107/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
108/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000109static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
110 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000111 const CXXMethodDecl *MD) {
112
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000113 // When building with -fapple-kext, all calls must go through the vtable since
114 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000115 if (Context.getLangOptions().AppleKext)
116 return false;
117
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000118 // If the most derived class is marked final, we know that no subclass can
119 // override this member function and so we can devirtualize it. For example:
120 //
121 // struct A { virtual void f(); }
122 // struct B final : A { };
123 //
124 // void f(B *b) {
125 // b->f();
126 // }
127 //
128 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
129 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
130 return true;
131
Anders Carlssonf89e0422011-01-23 21:07:30 +0000132 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000133 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000134 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000135 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000136
Anders Carlssonf89e0422011-01-23 21:07:30 +0000137 // Similarly, if the class itself is marked 'final' it can't be overridden
138 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000139 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000140 return true;
141
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000142 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000143 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
144 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
145 // This is a record decl. We know the type and can devirtualize it.
146 return VD->getType()->isRecordType();
147 }
148
149 return false;
150 }
151
152 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000153 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000154 return true;
155
156 // And calls on bound temporaries.
157 if (isa<CXXBindTemporaryExpr>(Base))
158 return true;
159
160 // Check if this is a call expr that returns a record type.
161 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
162 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000163
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000164 // We can't devirtualize the call.
165 return false;
166}
167
Francois Pichetdbee3412011-01-18 05:04:39 +0000168// Note: This function also emit constructor calls to support a MSVC
169// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000170RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
171 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000172 const Expr *callee = CE->getCallee()->IgnoreParens();
173
174 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000175 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000176
177 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000178 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
179
Devang Patelc69e1cf2010-09-30 19:05:55 +0000180 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000181 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
182 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000183 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
184 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
185 DI->getOrCreateRecordType(PTy->getPointeeType(),
186 MD->getParent()->getLocation());
187 }
188 }
189
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000190 if (MD->isStatic()) {
191 // The method is static, emit it as we would a regular call.
192 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
193 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
194 ReturnValue, CE->arg_begin(), CE->arg_end());
195 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000196
John McCallfc400282010-09-03 01:26:39 +0000197 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000198 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000199 if (ME->isArrow())
200 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000201 else
202 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000203
John McCallfc400282010-09-03 01:26:39 +0000204 if (MD->isTrivial()) {
205 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000206 if (isa<CXXConstructorDecl>(MD) &&
207 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
208 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000209
Francois Pichetdbee3412011-01-18 05:04:39 +0000210 if (MD->isCopyAssignmentOperator()) {
211 // We don't like to generate the trivial copy assignment operator when
212 // it isn't necessary; just produce the proper effect here.
213 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
214 EmitAggregateCopy(This, RHS, CE->getType());
215 return RValue::get(This);
216 }
217
218 if (isa<CXXConstructorDecl>(MD) &&
219 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
220 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
221 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
222 CE->arg_begin(), CE->arg_end());
223 return RValue::get(This);
224 }
225 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000226 }
227
John McCallfc400282010-09-03 01:26:39 +0000228 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000229 const CGFunctionInfo *FInfo = 0;
230 if (isa<CXXDestructorDecl>(MD))
231 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
232 Dtor_Complete);
233 else if (isa<CXXConstructorDecl>(MD))
234 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
235 Ctor_Complete);
236 else
237 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000238
239 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
240 const llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000241 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000242
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000243 // C++ [class.virtual]p12:
244 // Explicit qualification with the scope operator (5.1) suppresses the
245 // virtual call mechanism.
246 //
247 // We also don't emit a virtual call if the base expression has a record type
248 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000249 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000250 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
251 && !canDevirtualizeMemberFunctionCalls(getContext(),
252 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000253 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000254 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
255 if (UseVirtualCall) {
256 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000257 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000258 if (getContext().getLangOptions().AppleKext &&
259 MD->isVirtual() &&
260 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000261 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000262 else
263 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000265 } else if (const CXXConstructorDecl *Ctor =
266 dyn_cast<CXXConstructorDecl>(MD)) {
267 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000268 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000269 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000270 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000271 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000272 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000273 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000274 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000275 else
276 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000277 }
278
Anders Carlssonc997d422010-01-02 01:01:18 +0000279 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000280 CE->arg_begin(), CE->arg_end());
281}
282
283RValue
284CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
285 ReturnValueSlot ReturnValue) {
286 const BinaryOperator *BO =
287 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
288 const Expr *BaseExpr = BO->getLHS();
289 const Expr *MemFnExpr = BO->getRHS();
290
291 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000292 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000293
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000294 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000295 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
298
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000299 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000301
302 // Emit the 'this' pointer.
303 llvm::Value *This;
304
John McCall2de56d12010-08-25 11:45:40 +0000305 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000306 This = EmitScalarExpr(BaseExpr);
307 else
308 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309
John McCall93d557b2010-08-22 00:05:51 +0000310 // Ask the ABI to load the callee. Note that This is modified.
311 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000312 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000314 CallArgList Args;
315
316 QualType ThisType =
317 getContext().getPointerType(getContext().getTagDeclType(RD));
318
319 // Push the this ptr.
320 Args.push_back(std::make_pair(RValue::get(This), ThisType));
321
322 // And the rest of the call args
323 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall864c0412011-04-26 20:42:42 +0000324 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000325 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326}
327
328RValue
329CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
330 const CXXMethodDecl *MD,
331 ReturnValueSlot ReturnValue) {
332 assert(MD->isInstance() &&
333 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000334 LValue LV = EmitLValue(E->getArg(0));
335 llvm::Value *This = LV.getAddress();
336
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000337 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000338 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
339 if (ClassDecl->hasTrivialCopyAssignment()) {
340 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
341 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000342 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
343 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000344 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000345 return RValue::get(This);
346 }
347 }
348
349 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
350 const llvm::Type *Ty =
351 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
352 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000353 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000354 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000355 !canDevirtualizeMemberFunctionCalls(getContext(),
356 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000357 Callee = BuildVirtualCall(MD, This, Ty);
358 else
359 Callee = CGM.GetAddrOfFunction(MD, Ty);
360
Anders Carlssonc997d422010-01-02 01:01:18 +0000361 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000362 E->arg_begin() + 1, E->arg_end());
363}
364
365void
John McCall558d2ab2010-09-15 10:14:12 +0000366CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
367 AggValueSlot Dest) {
368 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000369 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000370
371 // If we require zero initialization before (or instead of) calling the
372 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000373 // constructor, emit the zero initialization now, unless destination is
374 // already zeroed.
375 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall558d2ab2010-09-15 10:14:12 +0000376 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000377
378 // If this is a call to a trivial default constructor, do nothing.
379 if (CD->isTrivial() && CD->isDefaultConstructor())
380 return;
381
John McCallfc1e6c72010-09-18 00:58:34 +0000382 // Elide the constructor if we're constructing from a temporary.
383 // The temporary check is required because Sema sets this on NRVO
384 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000385 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000386 assert(getContext().hasSameUnqualifiedType(E->getType(),
387 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000388 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
389 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000390 return;
391 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000392 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000393
394 const ConstantArrayType *Array
395 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000396 if (Array) {
397 QualType BaseElementTy = getContext().getBaseElementType(Array);
398 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
399 BasePtr = llvm::PointerType::getUnqual(BasePtr);
400 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000401 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000402
403 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
404 E->arg_begin(), E->arg_end());
405 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000406 else {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000407 CXXCtorType Type;
408 CXXConstructExpr::ConstructionKind K = E->getConstructionKind();
409 if (K == CXXConstructExpr::CK_Delegating) {
410 // We should be emitting a constructor; GlobalDecl will assert this
411 Type = CurGD.getCtorType();
412 } else {
413 Type = (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
414 ? Ctor_Complete : Ctor_Base;
415 }
416
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000417 bool ForVirtualBase =
418 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
419
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000420 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000421 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000422 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000423 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000424}
425
Fariborz Jahanian34999872010-11-13 21:53:34 +0000426void
427CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
428 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000429 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000430 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000431 Exp = E->getSubExpr();
432 assert(isa<CXXConstructExpr>(Exp) &&
433 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
434 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
435 const CXXConstructorDecl *CD = E->getConstructor();
436 RunCleanupsScope Scope(*this);
437
438 // If we require zero initialization before (or instead of) calling the
439 // constructor, as can be the case with a non-user-provided default
440 // constructor, emit the zero initialization now.
441 // FIXME. Do I still need this for a copy ctor synthesis?
442 if (E->requiresZeroInitialization())
443 EmitNullInitialization(Dest, E->getType());
444
Chandler Carruth858a5462010-11-15 13:54:43 +0000445 assert(!getContext().getAsConstantArrayType(E->getType())
446 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000447 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
448 E->arg_begin(), E->arg_end());
449}
450
John McCall5172ed92010-08-23 01:17:59 +0000451/// Check whether the given operator new[] is the global placement
452/// operator new[].
453static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
454 const FunctionDecl *Fn) {
455 // Must be in global scope. Note that allocation functions can't be
456 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000457 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000458 return false;
459
460 // Signature must be void *operator new[](size_t, void*).
461 // The size_t is common to all operator new[]s.
462 if (Fn->getNumParams() != 2)
463 return false;
464
465 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
466 return (ParamType == Ctx.VoidPtrTy);
467}
468
John McCall1e7fe752010-09-02 09:58:18 +0000469static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
470 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000471 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000472 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000473
Anders Carlssondd937552009-12-13 20:34:34 +0000474 // No cookie is required if the new operator being used is
475 // ::operator new[](size_t, void*).
476 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000477 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000478 return CharUnits::Zero();
479
John McCall6ec278d2011-01-27 09:37:56 +0000480 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000481}
482
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000483static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000484 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000485 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000486 llvm::Value *&NumElements,
487 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000488 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000489
490 const llvm::IntegerType *SizeTy =
491 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000492
John McCall1e7fe752010-09-02 09:58:18 +0000493 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
494
Douglas Gregor59174c02010-07-21 01:10:17 +0000495 if (!E->isArray()) {
496 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
497 return SizeWithoutCookie;
498 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000499
John McCall1e7fe752010-09-02 09:58:18 +0000500 // Figure out the cookie size.
501 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
502
Anders Carlssona4d4c012009-09-23 16:07:23 +0000503 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000504 // We multiply the size of all dimensions for NumElements.
505 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000506 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000507 assert(NumElements->getType() == SizeTy && "element count not a size_t");
508
509 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000510 while (const ConstantArrayType *CAT
511 = CGF.getContext().getAsConstantArrayType(ElemType)) {
512 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000513 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000514 }
515
John McCall1e7fe752010-09-02 09:58:18 +0000516 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000517
Chris Lattner806941e2010-07-20 21:55:52 +0000518 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
519 // Don't bloat the -O0 code.
520 if (llvm::ConstantInt *NumElementsC =
521 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000522 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000523 unsigned SizeWidth = NEC.getBitWidth();
524
525 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000526 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000527 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000528 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000529
530 if (!CookieSize.isZero()) {
531 // Save the current size without a cookie. We don't care if an
532 // overflow's already happened because SizeWithoutCookie isn't
533 // used if the allocator returns null or throws, as it should
534 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000535 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000536 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
537
538 // Add the cookie size.
539 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000540 }
541
John McCall1e7fe752010-09-02 09:58:18 +0000542 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000543 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000544 Size = llvm::ConstantInt::get(SizeTy, SC);
545 } else {
546 // On overflow, produce a -1 so operator new throws.
547 Size = llvm::Constant::getAllOnesValue(SizeTy);
548 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000549
John McCall1e7fe752010-09-02 09:58:18 +0000550 // Scale NumElements while we're at it.
551 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
552 NumElements = llvm::ConstantInt::get(SizeTy, N);
553
554 // Otherwise, we don't need to do an overflow-checked multiplication if
555 // we're multiplying by one.
556 } else if (TypeSize.isOne()) {
557 assert(ArraySizeMultiplier == 1);
558
559 Size = NumElements;
560
561 // If we need a cookie, add its size in with an overflow check.
562 // This is maybe a little paranoid.
563 if (!CookieSize.isZero()) {
564 SizeWithoutCookie = Size;
565
566 llvm::Value *CookieSizeV
567 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
568
569 const llvm::Type *Types[] = { SizeTy };
570 llvm::Value *UAddF
571 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
572 llvm::Value *AddRes
573 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
574
575 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
576 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
577 Size = CGF.Builder.CreateSelect(DidOverflow,
578 llvm::ConstantInt::get(SizeTy, -1),
579 Size);
580 }
581
582 // Otherwise use the int.umul.with.overflow intrinsic.
583 } else {
584 llvm::Value *OutermostElementSize
585 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
586
587 llvm::Value *NumOutermostElements = NumElements;
588
589 // Scale NumElements by the array size multiplier. This might
590 // overflow, but only if the multiplication below also overflows,
591 // in which case this multiplication isn't used.
592 if (ArraySizeMultiplier != 1)
593 NumElements = CGF.Builder.CreateMul(NumElements,
594 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
595
596 // The requested size of the outermost array is non-constant.
597 // Multiply that by the static size of the elements of that array;
598 // on unsigned overflow, set the size to -1 to trigger an
599 // exception from the allocation routine. This is sufficient to
600 // prevent buffer overruns from the allocator returning a
601 // seemingly valid pointer to insufficient space. This idea comes
602 // originally from MSVC, and GCC has an open bug requesting
603 // similar behavior:
604 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
605 //
606 // This will not be sufficient for C++0x, which requires a
607 // specific exception class (std::bad_array_new_length).
608 // That will require ABI support that has not yet been specified.
609 const llvm::Type *Types[] = { SizeTy };
610 llvm::Value *UMulF
611 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
612 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
613 OutermostElementSize);
614
615 // The overflow bit.
616 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
617
618 // The result of the multiplication.
619 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
620
621 // If we have a cookie, we need to add that size in, too.
622 if (!CookieSize.isZero()) {
623 SizeWithoutCookie = Size;
624
625 llvm::Value *CookieSizeV
626 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
627 llvm::Value *UAddF
628 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
629 llvm::Value *AddRes
630 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
631
632 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
633
634 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedman5536daa2011-04-09 19:54:33 +0000635 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall1e7fe752010-09-02 09:58:18 +0000636 }
637
638 Size = CGF.Builder.CreateSelect(DidOverflow,
639 llvm::ConstantInt::get(SizeTy, -1),
640 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000641 }
John McCall1e7fe752010-09-02 09:58:18 +0000642
643 if (CookieSize.isZero())
644 SizeWithoutCookie = Size;
645 else
646 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
647
Chris Lattner806941e2010-07-20 21:55:52 +0000648 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000649}
650
Fariborz Jahanianef668722010-06-25 18:26:07 +0000651static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
652 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000653
654 assert(E->getNumConstructorArgs() == 1 &&
655 "Can only have one argument to initializer of POD type.");
656
657 const Expr *Init = E->getConstructorArg(0);
658 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000659
660 unsigned Alignment =
661 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000662 if (!CGF.hasAggregateLLVMType(AllocType))
663 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000664 AllocType.isVolatileQualified(), Alignment,
665 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000666 else if (AllocType->isAnyComplexType())
667 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
668 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000669 else {
670 AggValueSlot Slot
671 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
672 CGF.EmitAggExpr(Init, Slot);
673 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000674}
675
676void
677CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
678 llvm::Value *NewPtr,
679 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000680 // We have a POD type.
681 if (E->getNumConstructorArgs() == 0)
682 return;
683
Fariborz Jahanianef668722010-06-25 18:26:07 +0000684 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
685
686 // Create a temporary for the loop index and initialize it with 0.
687 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
688 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
689 Builder.CreateStore(Zero, IndexPtr);
690
691 // Start the loop with a block that tests the condition.
692 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
693 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
694
695 EmitBlock(CondBlock);
696
697 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
698
699 // Generate: if (loop-index < number-of-elements fall to the loop body,
700 // otherwise, go to the block after the for-loop.
701 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
702 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
703 // If the condition is true, execute the body.
704 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
705
706 EmitBlock(ForBody);
707
708 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
709 // Inside the loop body, emit the constructor call on the array element.
710 Counter = Builder.CreateLoad(IndexPtr);
711 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
712 "arrayidx");
713 StoreAnyExprIntoOneUnit(*this, E, Address);
714
715 EmitBlock(ContinueBlock);
716
717 // Emit the increment of the loop counter.
718 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
719 Counter = Builder.CreateLoad(IndexPtr);
720 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
721 Builder.CreateStore(NextVal, IndexPtr);
722
723 // Finally, branch back up to the condition for the next iteration.
724 EmitBranch(CondBlock);
725
726 // Emit the fall-through block.
727 EmitBlock(AfterFor, true);
728}
729
Douglas Gregor59174c02010-07-21 01:10:17 +0000730static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
731 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000732 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000733 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000734 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000735 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000736}
737
Anders Carlssona4d4c012009-09-23 16:07:23 +0000738static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
739 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000740 llvm::Value *NumElements,
741 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000742 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000743 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000744 bool RequiresZeroInitialization = false;
745 if (Ctor->getParent()->hasTrivialConstructor()) {
746 // If new expression did not specify value-initialization, then there
747 // is no initialization.
748 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
749 return;
750
John McCallf16aa102010-08-22 21:01:12 +0000751 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000752 // Optimization: since zero initialization will just set the memory
753 // to all zeroes, generate a single memset to do it in one shot.
754 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
755 AllocSizeWithoutCookie);
756 return;
757 }
758
759 RequiresZeroInitialization = true;
760 }
761
762 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
763 E->constructor_arg_begin(),
764 E->constructor_arg_end(),
765 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000766 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000767 } else if (E->getNumConstructorArgs() == 1 &&
768 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
769 // Optimization: since zero initialization will just set the memory
770 // to all zeroes, generate a single memset to do it in one shot.
771 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
772 AllocSizeWithoutCookie);
773 return;
774 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000775 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
776 return;
777 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000778 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000779
780 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000781 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
782 // direct initialization. C++ [dcl.init]p5 requires that we
783 // zero-initialize storage if there are no user-declared constructors.
784 if (E->hasInitializer() &&
785 !Ctor->getParent()->hasUserDeclaredConstructor() &&
786 !Ctor->getParent()->isEmpty())
787 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
788
Douglas Gregor84745672010-07-07 23:37:33 +0000789 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
790 NewPtr, E->constructor_arg_begin(),
791 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000792
793 return;
794 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000795 // We have a POD type.
796 if (E->getNumConstructorArgs() == 0)
797 return;
798
Fariborz Jahanianef668722010-06-25 18:26:07 +0000799 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000800}
801
John McCall7d8647f2010-09-14 07:57:04 +0000802namespace {
803 /// A cleanup to call the given 'operator delete' function upon
804 /// abnormal exit from a new expression.
805 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
806 size_t NumPlacementArgs;
807 const FunctionDecl *OperatorDelete;
808 llvm::Value *Ptr;
809 llvm::Value *AllocSize;
810
811 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
812
813 public:
814 static size_t getExtraSize(size_t NumPlacementArgs) {
815 return NumPlacementArgs * sizeof(RValue);
816 }
817
818 CallDeleteDuringNew(size_t NumPlacementArgs,
819 const FunctionDecl *OperatorDelete,
820 llvm::Value *Ptr,
821 llvm::Value *AllocSize)
822 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
823 Ptr(Ptr), AllocSize(AllocSize) {}
824
825 void setPlacementArg(unsigned I, RValue Arg) {
826 assert(I < NumPlacementArgs && "index out of range");
827 getPlacementArgs()[I] = Arg;
828 }
829
830 void Emit(CodeGenFunction &CGF, bool IsForEH) {
831 const FunctionProtoType *FPT
832 = OperatorDelete->getType()->getAs<FunctionProtoType>();
833 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000834 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000835
836 CallArgList DeleteArgs;
837
838 // The first argument is always a void*.
839 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
840 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
841
842 // A member 'operator delete' can take an extra 'size_t' argument.
843 if (FPT->getNumArgs() == NumPlacementArgs + 2)
844 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
845
846 // Pass the rest of the arguments, which must match exactly.
847 for (unsigned I = 0; I != NumPlacementArgs; ++I)
848 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
849
850 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000851 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000852 CGF.CGM.GetAddrOfFunction(OperatorDelete),
853 ReturnValueSlot(), DeleteArgs, OperatorDelete);
854 }
855 };
John McCall3019c442010-09-17 00:50:28 +0000856
857 /// A cleanup to call the given 'operator delete' function upon
858 /// abnormal exit from a new expression when the new expression is
859 /// conditional.
860 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
861 size_t NumPlacementArgs;
862 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000863 DominatingValue<RValue>::saved_type Ptr;
864 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000865
John McCall804b8072011-01-28 10:53:53 +0000866 DominatingValue<RValue>::saved_type *getPlacementArgs() {
867 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000868 }
869
870 public:
871 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000872 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000873 }
874
875 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
876 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000877 DominatingValue<RValue>::saved_type Ptr,
878 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000879 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
880 Ptr(Ptr), AllocSize(AllocSize) {}
881
John McCall804b8072011-01-28 10:53:53 +0000882 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000883 assert(I < NumPlacementArgs && "index out of range");
884 getPlacementArgs()[I] = Arg;
885 }
886
887 void Emit(CodeGenFunction &CGF, bool IsForEH) {
888 const FunctionProtoType *FPT
889 = OperatorDelete->getType()->getAs<FunctionProtoType>();
890 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
891 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
892
893 CallArgList DeleteArgs;
894
895 // The first argument is always a void*.
896 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCall804b8072011-01-28 10:53:53 +0000897 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall3019c442010-09-17 00:50:28 +0000898
899 // A member 'operator delete' can take an extra 'size_t' argument.
900 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000901 RValue RV = AllocSize.restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000902 DeleteArgs.push_back(std::make_pair(RV, *AI++));
903 }
904
905 // Pass the rest of the arguments, which must match exactly.
906 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000907 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000908 DeleteArgs.push_back(std::make_pair(RV, *AI++));
909 }
910
911 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000912 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000913 CGF.CGM.GetAddrOfFunction(OperatorDelete),
914 ReturnValueSlot(), DeleteArgs, OperatorDelete);
915 }
916 };
917}
918
919/// Enter a cleanup to call 'operator delete' if the initializer in a
920/// new-expression throws.
921static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
922 const CXXNewExpr *E,
923 llvm::Value *NewPtr,
924 llvm::Value *AllocSize,
925 const CallArgList &NewArgs) {
926 // If we're not inside a conditional branch, then the cleanup will
927 // dominate and we can do the easier (and more efficient) thing.
928 if (!CGF.isInConditionalBranch()) {
929 CallDeleteDuringNew *Cleanup = CGF.EHStack
930 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
931 E->getNumPlacementArgs(),
932 E->getOperatorDelete(),
933 NewPtr, AllocSize);
934 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
935 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
936
937 return;
938 }
939
940 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000941 DominatingValue<RValue>::saved_type SavedNewPtr =
942 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
943 DominatingValue<RValue>::saved_type SavedAllocSize =
944 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000945
946 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
947 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
948 E->getNumPlacementArgs(),
949 E->getOperatorDelete(),
950 SavedNewPtr,
951 SavedAllocSize);
952 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000953 Cleanup->setPlacementArg(I,
954 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000955
956 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000957}
958
Anders Carlsson16d81b82009-09-22 22:53:17 +0000959llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000960 // The element type being allocated.
961 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +0000962
John McCallc2f3e7f2011-03-07 03:12:35 +0000963 // 1. Build a call to the allocation function.
964 FunctionDecl *allocator = E->getOperatorNew();
965 const FunctionProtoType *allocatorType =
966 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000967
John McCallc2f3e7f2011-03-07 03:12:35 +0000968 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000969
970 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000971 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000972
John McCallc2f3e7f2011-03-07 03:12:35 +0000973 llvm::Value *numElements = 0;
974 llvm::Value *allocSizeWithoutCookie = 0;
975 llvm::Value *allocSize =
976 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
977 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000978
John McCallc2f3e7f2011-03-07 03:12:35 +0000979 allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000980
981 // Emit the rest of the arguments.
982 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +0000983 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000984
985 // First, use the types from the function type.
986 // We start at 1 here because the first argument (the allocation size)
987 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +0000988 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
989 ++i, ++placementArg) {
990 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000991
John McCallc2f3e7f2011-03-07 03:12:35 +0000992 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
993 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +0000994 "type mismatch in call argument!");
995
John McCall413ebdb2011-03-11 20:59:21 +0000996 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000997 }
998
999 // Either we've emitted all the call args, or we have a call to a
1000 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001001 assert((placementArg == E->placement_arg_end() ||
1002 allocatorType->isVariadic()) &&
1003 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001004
1005 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001006 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1007 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001008 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001009 }
1010
John McCallc2f3e7f2011-03-07 03:12:35 +00001011 // Emit the allocation call.
Anders Carlsson16d81b82009-09-22 22:53:17 +00001012 RValue RV =
John McCallc2f3e7f2011-03-07 03:12:35 +00001013 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1014 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1015 allocatorArgs, allocator);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001016
John McCallc2f3e7f2011-03-07 03:12:35 +00001017 // Emit a null check on the allocation result if the allocation
1018 // function is allowed to return null (because it has a non-throwing
1019 // exception spec; for this part, we inline
1020 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1021 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001022 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallc2f3e7f2011-03-07 03:12:35 +00001023 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001024
John McCallc2f3e7f2011-03-07 03:12:35 +00001025 llvm::BasicBlock *nullCheckBB = 0;
1026 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001027
John McCallc2f3e7f2011-03-07 03:12:35 +00001028 llvm::Value *allocation = RV.getScalarVal();
1029 unsigned AS =
1030 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001031
John McCalla7f633f2011-03-07 01:52:56 +00001032 // The null-check means that the initializer is conditionally
1033 // evaluated.
1034 ConditionalEvaluation conditional(*this);
1035
John McCallc2f3e7f2011-03-07 03:12:35 +00001036 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001037 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001038
1039 nullCheckBB = Builder.GetInsertBlock();
1040 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1041 contBB = createBasicBlock("new.cont");
1042
1043 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1044 Builder.CreateCondBr(isNull, contBB, notNullBB);
1045 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001046 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001047
John McCallc2f3e7f2011-03-07 03:12:35 +00001048 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001049 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001050 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001051 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001052 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1053 numElements,
1054 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001055 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001056
John McCall7d8647f2010-09-14 07:57:04 +00001057 // If there's an operator delete, enter a cleanup to call it if an
1058 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001059 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7d8647f2010-09-14 07:57:04 +00001060 if (E->getOperatorDelete()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001061 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1062 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001063 }
1064
John McCallc2f3e7f2011-03-07 03:12:35 +00001065 const llvm::Type *elementPtrTy
1066 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1067 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001068
John McCall1e7fe752010-09-02 09:58:18 +00001069 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001070 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001071
1072 // NewPtr is a pointer to the base element type. If we're
1073 // allocating an array of arrays, we'll need to cast back to the
1074 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001075 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1076 if (result->getType() != resultType)
1077 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001078 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001079 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001080 }
John McCall7d8647f2010-09-14 07:57:04 +00001081
1082 // Deactivate the 'operator delete' cleanup if we finished
1083 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001084 if (operatorDeleteCleanup.isValid())
1085 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001086
John McCallc2f3e7f2011-03-07 03:12:35 +00001087 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001088 conditional.end(*this);
1089
John McCallc2f3e7f2011-03-07 03:12:35 +00001090 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1091 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001092
Jay Foadbbf3bac2011-03-30 11:28:58 +00001093 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001094 PHI->addIncoming(result, notNullBB);
1095 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1096 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001097
John McCallc2f3e7f2011-03-07 03:12:35 +00001098 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001099 }
John McCall1e7fe752010-09-02 09:58:18 +00001100
John McCallc2f3e7f2011-03-07 03:12:35 +00001101 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001102}
1103
Eli Friedman5fe05982009-11-18 00:50:08 +00001104void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1105 llvm::Value *Ptr,
1106 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001107 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1108
Eli Friedman5fe05982009-11-18 00:50:08 +00001109 const FunctionProtoType *DeleteFTy =
1110 DeleteFD->getType()->getAs<FunctionProtoType>();
1111
1112 CallArgList DeleteArgs;
1113
Anders Carlsson871d0782009-12-13 20:04:38 +00001114 // Check if we need to pass the size to the delete operator.
1115 llvm::Value *Size = 0;
1116 QualType SizeTy;
1117 if (DeleteFTy->getNumArgs() == 2) {
1118 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001119 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1120 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1121 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001122 }
1123
Eli Friedman5fe05982009-11-18 00:50:08 +00001124 QualType ArgTy = DeleteFTy->getArgType(0);
1125 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1126 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1127
Anders Carlsson871d0782009-12-13 20:04:38 +00001128 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +00001129 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +00001130
1131 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001132 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001133 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001134 DeleteArgs, DeleteFD);
1135}
1136
John McCall1e7fe752010-09-02 09:58:18 +00001137namespace {
1138 /// Calls the given 'operator delete' on a single object.
1139 struct CallObjectDelete : EHScopeStack::Cleanup {
1140 llvm::Value *Ptr;
1141 const FunctionDecl *OperatorDelete;
1142 QualType ElementType;
1143
1144 CallObjectDelete(llvm::Value *Ptr,
1145 const FunctionDecl *OperatorDelete,
1146 QualType ElementType)
1147 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1148
1149 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1150 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1151 }
1152 };
1153}
1154
1155/// Emit the code for deleting a single object.
1156static void EmitObjectDelete(CodeGenFunction &CGF,
1157 const FunctionDecl *OperatorDelete,
1158 llvm::Value *Ptr,
1159 QualType ElementType) {
1160 // Find the destructor for the type, if applicable. If the
1161 // destructor is virtual, we'll just emit the vcall and return.
1162 const CXXDestructorDecl *Dtor = 0;
1163 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1164 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1165 if (!RD->hasTrivialDestructor()) {
1166 Dtor = RD->getDestructor();
1167
1168 if (Dtor->isVirtual()) {
1169 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001170 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1171 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001172 /*isVariadic=*/false);
1173
1174 llvm::Value *Callee
1175 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1176 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1177 0, 0);
1178
1179 // The dtor took care of deleting the object.
1180 return;
1181 }
1182 }
1183 }
1184
1185 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001186 // This doesn't have to a conditional cleanup because we're going
1187 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001188 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1189 Ptr, OperatorDelete, ElementType);
1190
1191 if (Dtor)
1192 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1193 /*ForVirtualBase=*/false, Ptr);
1194
1195 CGF.PopCleanupBlock();
1196}
1197
1198namespace {
1199 /// Calls the given 'operator delete' on an array of objects.
1200 struct CallArrayDelete : EHScopeStack::Cleanup {
1201 llvm::Value *Ptr;
1202 const FunctionDecl *OperatorDelete;
1203 llvm::Value *NumElements;
1204 QualType ElementType;
1205 CharUnits CookieSize;
1206
1207 CallArrayDelete(llvm::Value *Ptr,
1208 const FunctionDecl *OperatorDelete,
1209 llvm::Value *NumElements,
1210 QualType ElementType,
1211 CharUnits CookieSize)
1212 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1213 ElementType(ElementType), CookieSize(CookieSize) {}
1214
1215 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1216 const FunctionProtoType *DeleteFTy =
1217 OperatorDelete->getType()->getAs<FunctionProtoType>();
1218 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1219
1220 CallArgList Args;
1221
1222 // Pass the pointer as the first argument.
1223 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1224 llvm::Value *DeletePtr
1225 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1226 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1227
1228 // Pass the original requested size as the second argument.
1229 if (DeleteFTy->getNumArgs() == 2) {
1230 QualType size_t = DeleteFTy->getArgType(1);
1231 const llvm::IntegerType *SizeTy
1232 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1233
1234 CharUnits ElementTypeSize =
1235 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1236
1237 // The size of an element, multiplied by the number of elements.
1238 llvm::Value *Size
1239 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1240 Size = CGF.Builder.CreateMul(Size, NumElements);
1241
1242 // Plus the size of the cookie if applicable.
1243 if (!CookieSize.isZero()) {
1244 llvm::Value *CookieSizeV
1245 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1246 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1247 }
1248
1249 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1250 }
1251
1252 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001253 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001254 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1255 ReturnValueSlot(), Args, OperatorDelete);
1256 }
1257 };
1258}
1259
1260/// Emit the code for deleting an array of objects.
1261static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001262 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001263 llvm::Value *Ptr,
1264 QualType ElementType) {
1265 llvm::Value *NumElements = 0;
1266 llvm::Value *AllocatedPtr = 0;
1267 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001268 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001269 NumElements, AllocatedPtr, CookieSize);
1270
1271 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1272
1273 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001274 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001275 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1276 AllocatedPtr, OperatorDelete,
1277 NumElements, ElementType,
1278 CookieSize);
1279
1280 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1281 if (!RD->hasTrivialDestructor()) {
1282 assert(NumElements && "ReadArrayCookie didn't find element count"
1283 " for a class with destructor");
1284 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1285 }
1286 }
1287
1288 CGF.PopCleanupBlock();
1289}
1290
Anders Carlsson16d81b82009-09-22 22:53:17 +00001291void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001292
Douglas Gregor90916562009-09-29 18:16:17 +00001293 // Get at the argument before we performed the implicit conversion
1294 // to void*.
1295 const Expr *Arg = E->getArgument();
1296 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001297 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001298 ICE->getType()->isVoidPointerType())
1299 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001300 else
1301 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001302 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001303
Douglas Gregor90916562009-09-29 18:16:17 +00001304 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001305
1306 // Null check the pointer.
1307 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1308 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1309
Anders Carlssonb9241242011-04-11 00:30:07 +00001310 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001311
1312 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1313 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001314
John McCall1e7fe752010-09-02 09:58:18 +00001315 // We might be deleting a pointer to array. If so, GEP down to the
1316 // first non-array element.
1317 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1318 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1319 if (DeleteTy->isConstantArrayType()) {
1320 llvm::Value *Zero = Builder.getInt32(0);
1321 llvm::SmallVector<llvm::Value*,8> GEP;
1322
1323 GEP.push_back(Zero); // point at the outermost array
1324
1325 // For each layer of array type we're pointing at:
1326 while (const ConstantArrayType *Arr
1327 = getContext().getAsConstantArrayType(DeleteTy)) {
1328 // 1. Unpeel the array type.
1329 DeleteTy = Arr->getElementType();
1330
1331 // 2. GEP to the first element of the array.
1332 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001333 }
John McCall1e7fe752010-09-02 09:58:18 +00001334
1335 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001336 }
1337
Douglas Gregoreede61a2010-09-02 17:38:50 +00001338 assert(ConvertTypeForMem(DeleteTy) ==
1339 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001340
1341 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001342 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001343 } else {
1344 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1345 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001346
Anders Carlsson16d81b82009-09-22 22:53:17 +00001347 EmitBlock(DeleteEnd);
1348}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001349
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001350static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1351 // void __cxa_bad_typeid();
1352
1353 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1354 const llvm::FunctionType *FTy =
1355 llvm::FunctionType::get(VoidTy, false);
1356
1357 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1358}
1359
1360static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001361 llvm::Value *Fn = getBadTypeidFn(CGF);
1362 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001363 CGF.Builder.CreateUnreachable();
1364}
1365
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001366static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1367 const Expr *E,
1368 const llvm::Type *StdTypeInfoPtrTy) {
1369 // Get the vtable pointer.
1370 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1371
1372 // C++ [expr.typeid]p2:
1373 // If the glvalue expression is obtained by applying the unary * operator to
1374 // a pointer and the pointer is a null pointer value, the typeid expression
1375 // throws the std::bad_typeid exception.
1376 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1377 if (UO->getOpcode() == UO_Deref) {
1378 llvm::BasicBlock *BadTypeidBlock =
1379 CGF.createBasicBlock("typeid.bad_typeid");
1380 llvm::BasicBlock *EndBlock =
1381 CGF.createBasicBlock("typeid.end");
1382
1383 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1384 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1385
1386 CGF.EmitBlock(BadTypeidBlock);
1387 EmitBadTypeidCall(CGF);
1388 CGF.EmitBlock(EndBlock);
1389 }
1390 }
1391
1392 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1393 StdTypeInfoPtrTy->getPointerTo());
1394
1395 // Load the type info.
1396 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1397 return CGF.Builder.CreateLoad(Value);
1398}
1399
John McCall3ad32c82011-01-28 08:37:24 +00001400llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001401 const llvm::Type *StdTypeInfoPtrTy =
1402 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001403
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001404 if (E->isTypeOperand()) {
1405 llvm::Constant *TypeInfo =
1406 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001407 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001408 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001409
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001410 // C++ [expr.typeid]p2:
1411 // When typeid is applied to a glvalue expression whose type is a
1412 // polymorphic class type, the result refers to a std::type_info object
1413 // representing the type of the most derived object (that is, the dynamic
1414 // type) to which the glvalue refers.
1415 if (E->getExprOperand()->isGLValue()) {
1416 if (const RecordType *RT =
1417 E->getExprOperand()->getType()->getAs<RecordType>()) {
1418 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1419 if (RD->isPolymorphic())
1420 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1421 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001422 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001423 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001424
1425 QualType OperandTy = E->getExprOperand()->getType();
1426 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1427 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001428}
Mike Stumpc849c052009-11-16 06:50:58 +00001429
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001430static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1431 // void *__dynamic_cast(const void *sub,
1432 // const abi::__class_type_info *src,
1433 // const abi::__class_type_info *dst,
1434 // std::ptrdiff_t src2dst_offset);
1435
1436 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1437 const llvm::Type *PtrDiffTy =
1438 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1439
1440 const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1441
1442 const llvm::FunctionType *FTy =
1443 llvm::FunctionType::get(Int8PtrTy, Args, false);
1444
1445 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1446}
1447
1448static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1449 // void __cxa_bad_cast();
1450
1451 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1452 const llvm::FunctionType *FTy =
1453 llvm::FunctionType::get(VoidTy, false);
1454
1455 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1456}
1457
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001458static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001459 llvm::Value *Fn = getBadCastFn(CGF);
1460 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001461 CGF.Builder.CreateUnreachable();
1462}
1463
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001464static llvm::Value *
1465EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1466 QualType SrcTy, QualType DestTy,
1467 llvm::BasicBlock *CastEnd) {
1468 const llvm::Type *PtrDiffLTy =
1469 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1470 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1471
1472 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1473 if (PTy->getPointeeType()->isVoidType()) {
1474 // C++ [expr.dynamic.cast]p7:
1475 // If T is "pointer to cv void," then the result is a pointer to the
1476 // most derived object pointed to by v.
1477
1478 // Get the vtable pointer.
1479 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1480
1481 // Get the offset-to-top from the vtable.
1482 llvm::Value *OffsetToTop =
1483 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1484 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1485
1486 // Finally, add the offset to the pointer.
1487 Value = CGF.EmitCastToVoidPtr(Value);
1488 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1489
1490 return CGF.Builder.CreateBitCast(Value, DestLTy);
1491 }
1492 }
1493
1494 QualType SrcRecordTy;
1495 QualType DestRecordTy;
1496
1497 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1498 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1499 DestRecordTy = DestPTy->getPointeeType();
1500 } else {
1501 SrcRecordTy = SrcTy;
1502 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1503 }
1504
1505 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1506 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1507
1508 llvm::Value *SrcRTTI =
1509 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1510 llvm::Value *DestRTTI =
1511 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1512
1513 // FIXME: Actually compute a hint here.
1514 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1515
1516 // Emit the call to __dynamic_cast.
1517 Value = CGF.EmitCastToVoidPtr(Value);
1518 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1519 SrcRTTI, DestRTTI, OffsetHint);
1520 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1521
1522 /// C++ [expr.dynamic.cast]p9:
1523 /// A failed cast to reference type throws std::bad_cast
1524 if (DestTy->isReferenceType()) {
1525 llvm::BasicBlock *BadCastBlock =
1526 CGF.createBasicBlock("dynamic_cast.bad_cast");
1527
1528 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1529 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1530
1531 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001532 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001533 }
1534
1535 return Value;
1536}
1537
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001538static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1539 QualType DestTy) {
1540 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1541 if (DestTy->isPointerType())
1542 return llvm::Constant::getNullValue(DestLTy);
1543
1544 /// C++ [expr.dynamic.cast]p9:
1545 /// A failed cast to reference type throws std::bad_cast
1546 EmitBadCastCall(CGF);
1547
1548 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1549 return llvm::UndefValue::get(DestLTy);
1550}
1551
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001552llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001553 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001554 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001555
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001556 if (DCE->isAlwaysNull())
1557 return EmitDynamicCastToNull(*this, DestTy);
1558
1559 QualType SrcTy = DCE->getSubExpr()->getType();
1560
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001561 // C++ [expr.dynamic.cast]p4:
1562 // If the value of v is a null pointer value in the pointer case, the result
1563 // is the null pointer value of type T.
1564 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001565
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001566 llvm::BasicBlock *CastNull = 0;
1567 llvm::BasicBlock *CastNotNull = 0;
1568 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001569
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001570 if (ShouldNullCheckSrcValue) {
1571 CastNull = createBasicBlock("dynamic_cast.null");
1572 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1573
1574 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1575 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1576 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001577 }
1578
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001579 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1580
1581 if (ShouldNullCheckSrcValue) {
1582 EmitBranch(CastEnd);
1583
1584 EmitBlock(CastNull);
1585 EmitBranch(CastEnd);
1586 }
1587
1588 EmitBlock(CastEnd);
1589
1590 if (ShouldNullCheckSrcValue) {
1591 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1592 PHI->addIncoming(Value, CastNotNull);
1593 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1594
1595 Value = PHI;
1596 }
1597
1598 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001599}