blob: 0a5a2a6473eb9922a7122a70d6c1fa4efdd62ea4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
Douglas Gregor50d62d12009-08-05 05:36:45 +000035 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Douglas Gregor2def4832008-11-17 20:34:05 +000036 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattner572af492008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Douglas Gregorac7610d2009-06-22 20:57:11 +000074 if (!isType) {
75 // C++0x [expr.typeid]p3:
76 // When typeid is applied to an expression other than an lvalue of a
77 // polymorphic class type [...] [the] expression is an unevaluated
78 // operand.
79
80 // FIXME: if the type of the expression is a class type, the class
81 // shall be completely defined.
82 bool isUnevaluatedOperand = true;
83 Expr *E = static_cast<Expr *>(TyOrExpr);
84 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
85 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000086 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000087 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
88 if (RecordD->isPolymorphic())
89 isUnevaluatedOperand = false;
90 }
91 }
92
93 // If this is an unevaluated operand, clear out the set of declaration
94 // references we have been computing.
95 if (isUnevaluatedOperand)
96 PotentiallyReferencedDeclStack.back().clear();
97 }
98
Sebastian Redlf53597f2009-03-15 17:47:39 +000099 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
100 TypeInfoType.withConst(),
101 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000102}
103
Steve Naroff1b273c42007-09-16 14:56:35 +0000104/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000106Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000107 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000109 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
110 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000111}
Chris Lattner50dd2892008-02-26 00:51:44 +0000112
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000113/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
114Action::OwningExprResult
115Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
116 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
117}
118
Chris Lattner50dd2892008-02-26 00:51:44 +0000119/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000120Action::OwningExprResult
121Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000122 Expr *Ex = E.takeAs<Expr>();
123 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
124 return ExprError();
125 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
126}
127
128/// CheckCXXThrowOperand - Validate the operand of a throw.
129bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
130 // C++ [except.throw]p3:
131 // [...] adjusting the type from "array of T" or "function returning T"
132 // to "pointer to T" or "pointer to function returning T", [...]
133 DefaultFunctionArrayConversion(E);
134
135 // If the type of the exception would be an incomplete type or a pointer
136 // to an incomplete type other than (cv) void the program is ill-formed.
137 QualType Ty = E->getType();
138 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000139 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000140 Ty = Ptr->getPointeeType();
141 isPointer = 1;
142 }
143 if (!isPointer || !Ty->isVoidType()) {
144 if (RequireCompleteType(ThrowLoc, Ty,
145 isPointer ? diag::err_throw_incomplete_ptr
146 : diag::err_throw_incomplete,
147 E->getSourceRange(), SourceRange(), QualType()))
148 return true;
149 }
150
151 // FIXME: Construct a temporary here.
152 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000153}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000154
Sebastian Redlf53597f2009-03-15 17:47:39 +0000155Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000156 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
157 /// is a non-lvalue expression whose value is the address of the object for
158 /// which the function is called.
159
Sebastian Redlf53597f2009-03-15 17:47:39 +0000160 if (!isa<FunctionDecl>(CurContext))
161 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000162
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
164 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 return Owned(new (Context) CXXThisExpr(ThisLoc,
166 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000167
Sebastian Redlf53597f2009-03-15 17:47:39 +0000168 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000169}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000170
171/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
172/// Can be interpreted either as function-style casting ("int(x)")
173/// or class type construction ("ClassType(x,y,z)")
174/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000176Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
177 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000178 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000179 SourceLocation *CommaLocs,
180 SourceLocation RParenLoc) {
181 assert(TypeRep && "Missing type!");
182 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000183 unsigned NumExprs = exprs.size();
184 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000185 SourceLocation TyBeginLoc = TypeRange.getBegin();
186 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
187
Sebastian Redlf53597f2009-03-15 17:47:39 +0000188 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000189 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000190 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000191
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000192 return Owned(CXXUnresolvedConstructExpr::Create(Context,
193 TypeRange.getBegin(), Ty,
194 LParenLoc,
195 Exprs, NumExprs,
196 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000197 }
198
199
Douglas Gregor506ae412009-01-16 18:33:17 +0000200 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000201 // If the expression list is a single expression, the type conversion
202 // expression is equivalent (in definedness, and if defined in meaning) to the
203 // corresponding cast expression.
204 //
205 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000206 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
207 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*functional-style*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000208 return ExprError();
209 exprs.release();
210 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000211 Ty, TyBeginLoc, Kind,
Anders Carlssoncdef2b72009-07-31 00:48:10 +0000212 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000213 }
214
Ted Kremenek6217b802009-07-29 21:53:49 +0000215 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000216 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000217
Anders Carlsson165a0a02009-05-17 18:41:29 +0000218 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
219 // both the ctor and dtor are trivial.
Douglas Gregor506ae412009-01-16 18:33:17 +0000220 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
221 CXXConstructorDecl *Constructor
222 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
223 TypeRange.getBegin(),
224 SourceRange(TypeRange.getBegin(),
225 RParenLoc),
226 DeclarationName(),
227 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000228
Sebastian Redlf53597f2009-03-15 17:47:39 +0000229 if (!Constructor)
230 return ExprError();
231
232 exprs.release();
Anders Carlsson8e587a12009-05-30 20:56:46 +0000233 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssondef11992009-05-30 20:36:53 +0000234 Ty, TyBeginLoc, Exprs,
235 NumExprs, RParenLoc);
236 return MaybeBindToTemporary(E);
Douglas Gregor506ae412009-01-16 18:33:17 +0000237 }
238
239 // Fall through to value-initialize an object of class type that
240 // doesn't have a user-declared default constructor.
241 }
242
243 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000244 // If the expression list specifies more than a single value, the type shall
245 // be a class with a suitably declared constructor.
246 //
247 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000248 return ExprError(Diag(CommaLocs[0],
249 diag::err_builtin_func_cast_more_than_one_arg)
250 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000251
252 assert(NumExprs == 0 && "Expected 0 expressions");
253
Douglas Gregor506ae412009-01-16 18:33:17 +0000254 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000255 // The expression T(), where T is a simple-type-specifier for a non-array
256 // complete object type or the (possibly cv-qualified) void type, creates an
257 // rvalue of the specified type, which is value-initialized.
258 //
259 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000260 return ExprError(Diag(TyBeginLoc,
261 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000262 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000263 RequireCompleteType(TyBeginLoc, Ty,
264 diag::err_invalid_incomplete_type_use, FullRange))
265 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000266
Anders Carlsson8211eff2009-03-24 01:19:16 +0000267 if (RequireNonAbstractType(TyBeginLoc, Ty,
268 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000269 return ExprError();
270
Sebastian Redlf53597f2009-03-15 17:47:39 +0000271 exprs.release();
272 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000273}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000274
275
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000276/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
277/// @code new (memory) int[size][4] @endcode
278/// or
279/// @code ::new Foo(23, "hello") @endcode
280/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000281Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000282Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000283 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000284 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000285 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000286 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000287 SourceLocation ConstructorRParen)
288{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000289 Expr *ArraySize = 0;
290 unsigned Skip = 0;
291 // If the specified type is an array, unwrap it and save the expression.
292 if (D.getNumTypeObjects() > 0 &&
293 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
294 DeclaratorChunk &Chunk = D.getTypeObject(0);
295 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000296 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
297 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000298 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000299 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
300 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000301 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
302 Skip = 1;
303 }
304
305 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000306 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000307 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000308
Douglas Gregor3433cf72009-05-21 00:00:09 +0000309 // Every dimension shall be of constant size.
310 unsigned i = 1;
311 QualType ElementType = AllocType;
312 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
313 if (!Array->isConstantArrayType()) {
314 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
315 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
316 return ExprError();
317 }
318 ElementType = Array->getElementType();
319 ++i;
320 }
321
322 return BuildCXXNew(StartLoc, UseGlobal,
323 PlacementLParen,
324 move(PlacementArgs),
325 PlacementRParen,
326 ParenTypeId,
327 AllocType,
328 D.getSourceRange().getBegin(),
329 D.getSourceRange(),
330 Owned(ArraySize),
331 ConstructorLParen,
332 move(ConstructorArgs),
333 ConstructorRParen);
334}
335
336Sema::OwningExprResult
337Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
338 SourceLocation PlacementLParen,
339 MultiExprArg PlacementArgs,
340 SourceLocation PlacementRParen,
341 bool ParenTypeId,
342 QualType AllocType,
343 SourceLocation TypeLoc,
344 SourceRange TypeRange,
345 ExprArg ArraySizeE,
346 SourceLocation ConstructorLParen,
347 MultiExprArg ConstructorArgs,
348 SourceLocation ConstructorRParen) {
349 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000350 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000351
Douglas Gregor3433cf72009-05-21 00:00:09 +0000352 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000353
354 // That every array dimension except the first is constant was already
355 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000356
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000357 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
358 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000359 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000360 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000361 QualType SizeType = ArraySize->getType();
362 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000363 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
364 diag::err_array_size_not_integral)
365 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000366 // Let's see if this is a constant < 0. If so, we reject it out of hand.
367 // We don't care about special rules, so we tell the machinery it's not
368 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000369 if (!ArraySize->isValueDependent()) {
370 llvm::APSInt Value;
371 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
372 if (Value < llvm::APSInt(
373 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000374 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
375 diag::err_typecheck_negative_array_size)
376 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000377 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000378 }
379 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000380
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000381 FunctionDecl *OperatorNew = 0;
382 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
384 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000385 if (!AllocType->isDependentType() &&
386 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
387 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000388 SourceRange(PlacementLParen, PlacementRParen),
389 UseGlobal, AllocType, ArraySize, PlaceArgs,
390 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000392
393 bool Init = ConstructorLParen.isValid();
394 // --- Choosing a constructor ---
395 // C++ 5.3.4p15
396 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
397 // the object is not initialized. If the object, or any part of it, is
398 // const-qualified, it's an error.
399 // 2) If T is a POD and there's an empty initializer, the object is value-
400 // initialized.
401 // 3) If T is a POD and there's one initializer argument, the object is copy-
402 // constructed.
403 // 4) If T is a POD and there's more initializer arguments, it's an error.
404 // 5) If T is not a POD, the initializer arguments are used as constructor
405 // arguments.
406 //
407 // Or by the C++0x formulation:
408 // 1) If there's no initializer, the object is default-initialized according
409 // to C++0x rules.
410 // 2) Otherwise, the object is direct-initialized.
411 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000412 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000413 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000414 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000415 if (AllocType->isDependentType()) {
416 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000417 } else if ((RT = AllocType->getAs<RecordType>()) &&
418 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000419 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000420 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000421 TypeLoc,
422 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000423 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000424 NumConsArgs != 0 ? IK_Direct : IK_Default);
425 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000426 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000427 } else {
428 if (!Init) {
429 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000430 if (AllocType.isConstQualified())
431 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000432 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000433 } else if (NumConsArgs == 0) {
434 // Object is value-initialized. Do nothing.
435 } else if (NumConsArgs == 1) {
436 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000437 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000438 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000439 DeclarationName() /*AllocType.getAsString()*/,
440 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000441 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000442 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 return ExprError(Diag(StartLoc,
444 diag::err_builtin_direct_init_more_than_one_arg)
445 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000446 }
447 }
448
449 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
450
Sebastian Redlf53597f2009-03-15 17:47:39 +0000451 PlacementArgs.release();
452 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000453 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000454 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000455 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000456 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000457 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000458}
459
460/// CheckAllocatedType - Checks that a type is suitable as the allocated type
461/// in a new-expression.
462/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000463bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
464 SourceRange R)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000465{
466 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
467 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000468 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000469 return Diag(Loc, diag::err_bad_new_type)
470 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000471 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000472 return Diag(Loc, diag::err_bad_new_type)
473 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000474 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000475 RequireCompleteType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000476 diag::err_new_incomplete_type,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000477 R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000478 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000479 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000480 diag::err_allocation_of_abstract_type))
481 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000482
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000483 return false;
484}
485
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000486/// FindAllocationFunctions - Finds the overloads of operator new and delete
487/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000488bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
489 bool UseGlobal, QualType AllocType,
490 bool IsArray, Expr **PlaceArgs,
491 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000492 FunctionDecl *&OperatorNew,
493 FunctionDecl *&OperatorDelete)
494{
495 // --- Choosing an allocation function ---
496 // C++ 5.3.4p8 - 14 & 18
497 // 1) If UseGlobal is true, only look in the global scope. Else, also look
498 // in the scope of the allocated class.
499 // 2) If an array size is given, look for operator new[], else look for
500 // operator new.
501 // 3) The first argument is always size_t. Append the arguments from the
502 // placement form.
503 // FIXME: Also find the appropriate delete operator.
504
505 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
506 // We don't care about the actual value of this argument.
507 // FIXME: Should the Sema create the expression and embed it in the syntax
508 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000509 IntegerLiteral Size(llvm::APInt::getNullValue(
510 Context.Target.getPointerWidth(0)),
511 Context.getSizeType(),
512 SourceLocation());
513 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000514 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
515
516 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
517 IsArray ? OO_Array_New : OO_New);
518 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000519 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000520 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000521 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000522 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000523 AllocArgs.size(), Record, /*AllowMissing=*/true,
524 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000525 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000526 }
527 if (!OperatorNew) {
528 // Didn't find a member overload. Look for a global one.
529 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000530 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000531 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000532 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
533 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000534 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000535 }
536
Anders Carlssond9583892009-05-31 20:26:12 +0000537 // FindAllocationOverload can change the passed in arguments, so we need to
538 // copy them back.
539 if (NumPlaceArgs > 0)
540 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
541
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000542 return false;
543}
544
Sebastian Redl7f662392008-12-04 22:20:51 +0000545/// FindAllocationOverload - Find an fitting overload for the allocation
546/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000547bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
548 DeclarationName Name, Expr** Args,
549 unsigned NumArgs, DeclContext *Ctx,
550 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000551{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000552 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000553 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000554 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000555 if (AllowMissing)
556 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000557 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000558 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000559 }
560
561 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000562 for (; Alloc != AllocEnd; ++Alloc) {
563 // Even member operator new/delete are implicitly treated as
564 // static, so don't use AddMemberCandidate.
565 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
566 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
567 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000568 }
569
570 // Do the resolution.
571 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000572 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 case OR_Success: {
574 // Got one!
575 FunctionDecl *FnDecl = Best->Function;
576 // The first argument is size_t, and the first parameter must be size_t,
577 // too. This is checked on declaration and can be assumed. (It can't be
578 // asserted on, though, since invalid decls are left in there.)
579 for (unsigned i = 1; i < NumArgs; ++i) {
580 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000581 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000582 FnDecl->getParamDecl(i)->getType(),
583 "passing"))
584 return true;
585 }
586 Operator = FnDecl;
587 return false;
588 }
589
590 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000591 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000592 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000593 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
594 return true;
595
596 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000598 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
600 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000601
602 case OR_Deleted:
603 Diag(StartLoc, diag::err_ovl_deleted_call)
604 << Best->Function->isDeleted()
605 << Name << Range;
606 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
607 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000608 }
609 assert(false && "Unreachable, bad result from BestViableFunction");
610 return true;
611}
612
613
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000614/// DeclareGlobalNewDelete - Declare the global forms of operator new and
615/// delete. These are:
616/// @code
617/// void* operator new(std::size_t) throw(std::bad_alloc);
618/// void* operator new[](std::size_t) throw(std::bad_alloc);
619/// void operator delete(void *) throw();
620/// void operator delete[](void *) throw();
621/// @endcode
622/// Note that the placement and nothrow forms of new are *not* implicitly
623/// declared. Their use requires including \<new\>.
624void Sema::DeclareGlobalNewDelete()
625{
626 if (GlobalNewDeleteDeclared)
627 return;
628 GlobalNewDeleteDeclared = true;
629
630 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
631 QualType SizeT = Context.getSizeType();
632
633 // FIXME: Exception specifications are not added.
634 DeclareGlobalAllocationFunction(
635 Context.DeclarationNames.getCXXOperatorName(OO_New),
636 VoidPtr, SizeT);
637 DeclareGlobalAllocationFunction(
638 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
639 VoidPtr, SizeT);
640 DeclareGlobalAllocationFunction(
641 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
642 Context.VoidTy, VoidPtr);
643 DeclareGlobalAllocationFunction(
644 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
645 Context.VoidTy, VoidPtr);
646}
647
648/// DeclareGlobalAllocationFunction - Declares a single implicit global
649/// allocation function if it doesn't already exist.
650void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
651 QualType Return, QualType Argument)
652{
653 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
654
655 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000656 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000657 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000658 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000659 Alloc != AllocEnd; ++Alloc) {
660 // FIXME: Do we need to check for default arguments here?
661 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
662 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000663 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000664 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000665 }
666 }
667
668 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
669 FunctionDecl *Alloc =
670 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000671 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000672 SourceLocation());
673 Alloc->setImplicit();
674 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000675 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000676 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000677
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000678 // FIXME: Also add this declaration to the IdentifierResolver, but
679 // make sure it is at the end of the chain to coincide with the
680 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000681 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000682}
683
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000684/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
685/// @code ::delete ptr; @endcode
686/// or
687/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000688Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000689Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000690 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000691{
692 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
693 // having a single conversion function to a pointer type. The result has
694 // type void."
695 // DR599 amends "pointer type" to "pointer to object type" in both cases.
696
Anders Carlssond67c4c32009-08-16 20:29:29 +0000697 FunctionDecl *OperatorDelete = 0;
698
Sebastian Redlf53597f2009-03-15 17:47:39 +0000699 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000700 if (!Ex->isTypeDependent()) {
701 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000702
Sebastian Redl28507842009-02-26 14:39:58 +0000703 if (Type->isRecordType()) {
704 // FIXME: Find that one conversion function and amend the type.
705 }
706
Sebastian Redlf53597f2009-03-15 17:47:39 +0000707 if (!Type->isPointerType())
708 return ExprError(Diag(StartLoc, diag::err_delete_operand)
709 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000710
Ted Kremenek6217b802009-07-29 21:53:49 +0000711 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000712 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000713 return ExprError(Diag(StartLoc, diag::err_delete_operand)
714 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000715 else if (!Pointee->isDependentType() &&
716 RequireCompleteType(StartLoc, Pointee,
717 diag::warn_delete_incomplete,
718 Ex->getSourceRange()))
719 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000720
Anders Carlssond67c4c32009-08-16 20:29:29 +0000721 // FIXME: This should be shared with the code for finding the delete
722 // operator in ActOnCXXNew.
723 IntegerLiteral Size(llvm::APInt::getNullValue(
724 Context.Target.getPointerWidth(0)),
725 Context.getSizeType(),
726 SourceLocation());
727 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
728 CastExpr::CK_Unknown, &Size, false);
729 Expr *DeleteArg = &Cast;
730
731 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
732 ArrayForm ? OO_Array_Delete : OO_Delete);
733
734 if (Pointee->isRecordType() && !UseGlobal) {
735 CXXRecordDecl *Record
736 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
737 // FIXME: We fail to find inherited overloads.
738 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
739 &DeleteArg, 1, Record, /*AllowMissing=*/true,
740 OperatorDelete))
741 return ExprError();
742 }
743
744 if (!OperatorDelete) {
745 // Didn't find a member overload. Look for a global one.
746 DeclareGlobalNewDelete();
747 DeclContext *TUDecl = Context.getTranslationUnitDecl();
748 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
749 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
750 OperatorDelete))
751 return ExprError();
752 }
753
Sebastian Redl28507842009-02-26 14:39:58 +0000754 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000755 }
756
Sebastian Redlf53597f2009-03-15 17:47:39 +0000757 Operand.release();
758 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000759 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000760}
761
762
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000763/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
764/// C++ if/switch/while/for statement.
765/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000766Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000767Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
768 Declarator &D,
769 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000770 ExprArg AssignExprVal) {
771 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000772
773 // C++ 6.4p2:
774 // The declarator shall not specify a function or an array.
775 // The type-specifier-seq shall not contain typedef and shall not declare a
776 // new class or enumeration.
777
778 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
779 "Parser allowed 'typedef' as storage class of condition decl.");
780
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000781 TagDecl *OwnedTag = 0;
782 QualType Ty = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000783
784 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
785 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
786 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000787 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
788 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000789 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000790 Diag(StartLoc, diag::err_invalid_use_of_array_type)
791 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000792 } else if (OwnedTag && OwnedTag->isDefinition()) {
793 // The type-specifier-seq shall not declare a new class or enumeration.
794 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000795 }
796
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000797 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000798 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000799 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000800 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000801
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000802 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000803 // We know that the decl had to be a VarDecl because that is the only type of
804 // decl that can be assigned and the grammar requires an '='.
805 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
806 VD->setDeclaredInCondition(true);
807 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000808}
809
810/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
811bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
812 // C++ 6.4p4:
813 // The value of a condition that is an initialized declaration in a statement
814 // other than a switch statement is the value of the declared variable
815 // implicitly converted to type bool. If that conversion is ill-formed, the
816 // program is ill-formed.
817 // The value of a condition that is an expression is the value of the
818 // expression, implicitly converted to bool.
819 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000820 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000821}
Douglas Gregor77a52232008-09-12 00:47:35 +0000822
823/// Helper function to determine whether this is the (deprecated) C++
824/// conversion from a string literal to a pointer to non-const char or
825/// non-const wchar_t (for narrow and wide string literals,
826/// respectively).
827bool
828Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
829 // Look inside the implicit cast, if it exists.
830 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
831 From = Cast->getSubExpr();
832
833 // A string literal (2.13.4) that is not a wide string literal can
834 // be converted to an rvalue of type "pointer to char"; a wide
835 // string literal can be converted to an rvalue of type "pointer
836 // to wchar_t" (C++ 4.2p2).
837 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000838 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor77a52232008-09-12 00:47:35 +0000839 if (const BuiltinType *ToPointeeType
840 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
841 // This conversion is considered only when there is an
842 // explicit appropriate pointer target type (C++ 4.2p2).
843 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
844 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
845 (!StrLit->isWide() &&
846 (ToPointeeType->getKind() == BuiltinType::Char_U ||
847 ToPointeeType->getKind() == BuiltinType::Char_S))))
848 return true;
849 }
850
851 return false;
852}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000853
854/// PerformImplicitConversion - Perform an implicit conversion of the
855/// expression From to the type ToType. Returns true if there was an
856/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000857/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000858/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000859/// explicit user-defined conversions are permitted. @p Elidable should be true
860/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
861/// resolution works differently in that case.
862bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000863Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000864 const char *Flavor, bool AllowExplicit,
865 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000866{
Sebastian Redle2b68332009-04-12 17:16:29 +0000867 ImplicitConversionSequence ICS;
868 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
869 if (Elidable && getLangOptions().CPlusPlus0x) {
870 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
871 AllowExplicit, /*ForceRValue*/true);
872 }
873 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
874 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
875 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000876 return PerformImplicitConversion(From, ToType, ICS, Flavor);
877}
878
879/// PerformImplicitConversion - Perform an implicit conversion of the
880/// expression From to the type ToType using the pre-computed implicit
881/// conversion sequence ICS. Returns true if there was an error, false
882/// otherwise. The expression From is replaced with the converted
883/// expression. Flavor is the kind of conversion we're performing,
884/// used in the error message.
885bool
886Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
887 const ImplicitConversionSequence &ICS,
888 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000889 switch (ICS.ConversionKind) {
890 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000891 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000892 return true;
893 break;
894
895 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stump390b4cc2009-05-16 07:39:55 +0000896 // FIXME: This is, of course, wrong. We'll need to actually call the
897 // constructor or conversion operator, and then cope with the standard
898 // conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000899 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +0000900 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000901 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000902 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000903
904 case ImplicitConversionSequence::EllipsisConversion:
905 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000906 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000907
908 case ImplicitConversionSequence::BadConversion:
909 return true;
910 }
911
912 // Everything went well.
913 return false;
914}
915
916/// PerformImplicitConversion - Perform an implicit conversion of the
917/// expression From to the type ToType by following the standard
918/// conversion sequence SCS. Returns true if there was an error, false
919/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000920/// expression. Flavor is the context in which we're performing this
921/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000922bool
923Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000924 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000925 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000926 // Overall FIXME: we are recomputing too many types here and doing far too
927 // much extra work. What this means is that we need to keep track of more
928 // information that is computed when we try the implicit conversion initially,
929 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000930 QualType FromType = From->getType();
931
Douglas Gregor225c41e2008-11-03 19:09:14 +0000932 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000933 // FIXME: When can ToType be a reference type?
934 assert(!ToType->isReferenceType());
935
Anders Carlsson9abf2ae2009-08-16 05:13:48 +0000936 From = BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000937 return false;
938 }
939
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000940 // Perform the first implicit conversion.
941 switch (SCS.First) {
942 case ICK_Identity:
943 case ICK_Lvalue_To_Rvalue:
944 // Nothing to do.
945 break;
946
947 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000948 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +0000949 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000950 break;
951
952 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000953 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000954 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
955 if (!Fn)
956 return true;
957
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000958 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
959 return true;
960
Douglas Gregor904eed32008-11-10 20:40:00 +0000961 FixOverloadedFunctionReference(From, Fn);
962 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000963 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000964 FromType = Context.getPointerType(FromType);
965 ImpCastExprToType(From, FromType);
966 break;
967
968 default:
969 assert(false && "Improper first standard conversion");
970 break;
971 }
972
973 // Perform the second implicit conversion
974 switch (SCS.Second) {
975 case ICK_Identity:
976 // Nothing to do.
977 break;
978
979 case ICK_Integral_Promotion:
980 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000981 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000982 case ICK_Integral_Conversion:
983 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000984 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000985 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000986 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000987 case ICK_Compatible_Conversion:
988 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000989 FromType = ToType.getUnqualifiedType();
990 ImpCastExprToType(From, FromType);
991 break;
992
993 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000994 if (SCS.IncompatibleObjC) {
995 // Diagnose incompatible Objective-C conversions
996 Diag(From->getSourceRange().getBegin(),
997 diag::ext_typecheck_convert_incompatible_pointer)
998 << From->getType() << ToType << Flavor
999 << From->getSourceRange();
1000 }
1001
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001002 if (CheckPointerConversion(From, ToType))
1003 return true;
1004 ImpCastExprToType(From, ToType);
1005 break;
1006
1007 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001008 if (CheckMemberPointerConversion(From, ToType))
1009 return true;
1010 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001011 break;
1012
1013 case ICK_Boolean_Conversion:
1014 FromType = Context.BoolTy;
1015 ImpCastExprToType(From, FromType);
1016 break;
1017
1018 default:
1019 assert(false && "Improper second standard conversion");
1020 break;
1021 }
1022
1023 switch (SCS.Third) {
1024 case ICK_Identity:
1025 // Nothing to do.
1026 break;
1027
1028 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001029 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1030 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +00001031 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001032 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001033 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001034 break;
1035
1036 default:
1037 assert(false && "Improper second standard conversion");
1038 break;
1039 }
1040
1041 return false;
1042}
1043
Sebastian Redl64b45f72009-01-05 20:52:13 +00001044Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1045 SourceLocation KWLoc,
1046 SourceLocation LParen,
1047 TypeTy *Ty,
1048 SourceLocation RParen) {
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001049 QualType T = QualType::getFromOpaquePtr(Ty);
1050
1051 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1052 // all traits except __is_class, __is_enum and __is_union require a the type
1053 // to be complete.
1054 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1055 if (RequireCompleteType(KWLoc, T,
1056 diag::err_incomplete_type_used_in_type_trait_expr,
1057 SourceRange(), SourceRange(), T))
1058 return ExprError();
1059 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001060
1061 // There is no point in eagerly computing the value. The traits are designed
1062 // to be used from type trait templates, so Ty will be a template parameter
1063 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001064 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1065 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001066}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001067
1068QualType Sema::CheckPointerToMemberOperands(
1069 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1070{
1071 const char *OpSpelling = isIndirect ? "->*" : ".*";
1072 // C++ 5.5p2
1073 // The binary operator .* [p3: ->*] binds its second operand, which shall
1074 // be of type "pointer to member of T" (where T is a completely-defined
1075 // class type) [...]
1076 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001077 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001078 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001079 Diag(Loc, diag::err_bad_memptr_rhs)
1080 << OpSpelling << RType << rex->getSourceRange();
1081 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001082 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001083
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001084 QualType Class(MemPtr->getClass(), 0);
1085
1086 // C++ 5.5p2
1087 // [...] to its first operand, which shall be of class T or of a class of
1088 // which T is an unambiguous and accessible base class. [p3: a pointer to
1089 // such a class]
1090 QualType LType = lex->getType();
1091 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001092 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001093 LType = Ptr->getPointeeType().getNonReferenceType();
1094 else {
1095 Diag(Loc, diag::err_bad_memptr_lhs)
1096 << OpSpelling << 1 << LType << lex->getSourceRange();
1097 return QualType();
1098 }
1099 }
1100
1101 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1102 Context.getCanonicalType(LType).getUnqualifiedType()) {
1103 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1104 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001105 // FIXME: Would it be useful to print full ambiguity paths, or is that
1106 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001107 if (!IsDerivedFrom(LType, Class, Paths) ||
1108 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1109 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1110 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1111 return QualType();
1112 }
1113 }
1114
1115 // C++ 5.5p2
1116 // The result is an object or a function of the type specified by the
1117 // second operand.
1118 // The cv qualifiers are the union of those in the pointer and the left side,
1119 // in accordance with 5.5p5 and 5.2.5.
1120 // FIXME: This returns a dereferenced member function pointer as a normal
1121 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001122 // calling them. There's also a GCC extension to get a function pointer to the
1123 // thing, which is another complication, because this type - unlike the type
1124 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001125 // argument.
1126 // We probably need a "MemberFunctionClosureType" or something like that.
1127 QualType Result = MemPtr->getPointeeType();
1128 if (LType.isConstQualified())
1129 Result.addConst();
1130 if (LType.isVolatileQualified())
1131 Result.addVolatile();
1132 return Result;
1133}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001134
1135/// \brief Get the target type of a standard or user-defined conversion.
1136static QualType TargetType(const ImplicitConversionSequence &ICS) {
1137 assert((ICS.ConversionKind ==
1138 ImplicitConversionSequence::StandardConversion ||
1139 ICS.ConversionKind ==
1140 ImplicitConversionSequence::UserDefinedConversion) &&
1141 "function only valid for standard or user-defined conversions");
1142 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1143 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1144 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1145}
1146
1147/// \brief Try to convert a type to another according to C++0x 5.16p3.
1148///
1149/// This is part of the parameter validation for the ? operator. If either
1150/// value operand is a class type, the two operands are attempted to be
1151/// converted to each other. This function does the conversion in one direction.
1152/// It emits a diagnostic and returns true only if it finds an ambiguous
1153/// conversion.
1154static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1155 SourceLocation QuestionLoc,
1156 ImplicitConversionSequence &ICS)
1157{
1158 // C++0x 5.16p3
1159 // The process for determining whether an operand expression E1 of type T1
1160 // can be converted to match an operand expression E2 of type T2 is defined
1161 // as follows:
1162 // -- If E2 is an lvalue:
1163 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1164 // E1 can be converted to match E2 if E1 can be implicitly converted to
1165 // type "lvalue reference to T2", subject to the constraint that in the
1166 // conversion the reference must bind directly to E1.
1167 if (!Self.CheckReferenceInit(From,
1168 Self.Context.getLValueReferenceType(To->getType()),
1169 &ICS))
1170 {
1171 assert((ICS.ConversionKind ==
1172 ImplicitConversionSequence::StandardConversion ||
1173 ICS.ConversionKind ==
1174 ImplicitConversionSequence::UserDefinedConversion) &&
1175 "expected a definite conversion");
1176 bool DirectBinding =
1177 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1178 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1179 if (DirectBinding)
1180 return false;
1181 }
1182 }
1183 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1184 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1185 // -- if E1 and E2 have class type, and the underlying class types are
1186 // the same or one is a base class of the other:
1187 QualType FTy = From->getType();
1188 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001189 const RecordType *FRec = FTy->getAs<RecordType>();
1190 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001191 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1192 if (FRec && TRec && (FRec == TRec ||
1193 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1194 // E1 can be converted to match E2 if the class of T2 is the
1195 // same type as, or a base class of, the class of T1, and
1196 // [cv2 > cv1].
1197 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1198 // Could still fail if there's no copy constructor.
1199 // FIXME: Is this a hard error then, or just a conversion failure? The
1200 // standard doesn't say.
1201 ICS = Self.TryCopyInitialization(From, TTy);
1202 }
1203 } else {
1204 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1205 // implicitly converted to the type that expression E2 would have
1206 // if E2 were converted to an rvalue.
1207 // First find the decayed type.
1208 if (TTy->isFunctionType())
1209 TTy = Self.Context.getPointerType(TTy);
1210 else if(TTy->isArrayType())
1211 TTy = Self.Context.getArrayDecayedType(TTy);
1212
1213 // Now try the implicit conversion.
1214 // FIXME: This doesn't detect ambiguities.
1215 ICS = Self.TryImplicitConversion(From, TTy);
1216 }
1217 return false;
1218}
1219
1220/// \brief Try to find a common type for two according to C++0x 5.16p5.
1221///
1222/// This is part of the parameter validation for the ? operator. If either
1223/// value operand is a class type, overload resolution is used to find a
1224/// conversion to a common type.
1225static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1226 SourceLocation Loc) {
1227 Expr *Args[2] = { LHS, RHS };
1228 OverloadCandidateSet CandidateSet;
1229 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1230
1231 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001232 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001233 case Sema::OR_Success:
1234 // We found a match. Perform the conversions on the arguments and move on.
1235 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1236 Best->Conversions[0], "converting") ||
1237 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1238 Best->Conversions[1], "converting"))
1239 break;
1240 return false;
1241
1242 case Sema::OR_No_Viable_Function:
1243 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1244 << LHS->getType() << RHS->getType()
1245 << LHS->getSourceRange() << RHS->getSourceRange();
1246 return true;
1247
1248 case Sema::OR_Ambiguous:
1249 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1250 << LHS->getType() << RHS->getType()
1251 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001252 // FIXME: Print the possible common types by printing the return types of
1253 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001254 break;
1255
1256 case Sema::OR_Deleted:
1257 assert(false && "Conditional operator has only built-in overloads");
1258 break;
1259 }
1260 return true;
1261}
1262
Sebastian Redl76458502009-04-17 16:30:52 +00001263/// \brief Perform an "extended" implicit conversion as returned by
1264/// TryClassUnification.
1265///
1266/// TryClassUnification generates ICSs that include reference bindings.
1267/// PerformImplicitConversion is not suitable for this; it chokes if the
1268/// second part of a standard conversion is ICK_DerivedToBase. This function
1269/// handles the reference binding specially.
1270static bool ConvertForConditional(Sema &Self, Expr *&E,
1271 const ImplicitConversionSequence &ICS)
1272{
1273 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1274 ICS.Standard.ReferenceBinding) {
1275 assert(ICS.Standard.DirectBinding &&
1276 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001277 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1278 // redoing all the work.
1279 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1280 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001281 }
1282 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1283 ICS.UserDefined.After.ReferenceBinding) {
1284 assert(ICS.UserDefined.After.DirectBinding &&
1285 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001286 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1287 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001288 }
1289 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1290 return true;
1291 return false;
1292}
1293
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001294/// \brief Check the operands of ?: under C++ semantics.
1295///
1296/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1297/// extension. In this case, LHS == Cond. (But they're not aliases.)
1298QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1299 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001300 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1301 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001302
1303 // C++0x 5.16p1
1304 // The first expression is contextually converted to bool.
1305 if (!Cond->isTypeDependent()) {
1306 if (CheckCXXBooleanCondition(Cond))
1307 return QualType();
1308 }
1309
1310 // Either of the arguments dependent?
1311 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1312 return Context.DependentTy;
1313
1314 // C++0x 5.16p2
1315 // If either the second or the third operand has type (cv) void, ...
1316 QualType LTy = LHS->getType();
1317 QualType RTy = RHS->getType();
1318 bool LVoid = LTy->isVoidType();
1319 bool RVoid = RTy->isVoidType();
1320 if (LVoid || RVoid) {
1321 // ... then the [l2r] conversions are performed on the second and third
1322 // operands ...
1323 DefaultFunctionArrayConversion(LHS);
1324 DefaultFunctionArrayConversion(RHS);
1325 LTy = LHS->getType();
1326 RTy = RHS->getType();
1327
1328 // ... and one of the following shall hold:
1329 // -- The second or the third operand (but not both) is a throw-
1330 // expression; the result is of the type of the other and is an rvalue.
1331 bool LThrow = isa<CXXThrowExpr>(LHS);
1332 bool RThrow = isa<CXXThrowExpr>(RHS);
1333 if (LThrow && !RThrow)
1334 return RTy;
1335 if (RThrow && !LThrow)
1336 return LTy;
1337
1338 // -- Both the second and third operands have type void; the result is of
1339 // type void and is an rvalue.
1340 if (LVoid && RVoid)
1341 return Context.VoidTy;
1342
1343 // Neither holds, error.
1344 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1345 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1346 << LHS->getSourceRange() << RHS->getSourceRange();
1347 return QualType();
1348 }
1349
1350 // Neither is void.
1351
1352 // C++0x 5.16p3
1353 // Otherwise, if the second and third operand have different types, and
1354 // either has (cv) class type, and attempt is made to convert each of those
1355 // operands to the other.
1356 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1357 (LTy->isRecordType() || RTy->isRecordType())) {
1358 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1359 // These return true if a single direction is already ambiguous.
1360 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1361 return QualType();
1362 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1363 return QualType();
1364
1365 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1366 ImplicitConversionSequence::BadConversion;
1367 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1368 ImplicitConversionSequence::BadConversion;
1369 // If both can be converted, [...] the program is ill-formed.
1370 if (HaveL2R && HaveR2L) {
1371 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1372 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1373 return QualType();
1374 }
1375
1376 // If exactly one conversion is possible, that conversion is applied to
1377 // the chosen operand and the converted operands are used in place of the
1378 // original operands for the remainder of this section.
1379 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001380 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001381 return QualType();
1382 LTy = LHS->getType();
1383 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001384 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001385 return QualType();
1386 RTy = RHS->getType();
1387 }
1388 }
1389
1390 // C++0x 5.16p4
1391 // If the second and third operands are lvalues and have the same type,
1392 // the result is of that type [...]
1393 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1394 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1395 RHS->isLvalue(Context) == Expr::LV_Valid)
1396 return LTy;
1397
1398 // C++0x 5.16p5
1399 // Otherwise, the result is an rvalue. If the second and third operands
1400 // do not have the same type, and either has (cv) class type, ...
1401 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1402 // ... overload resolution is used to determine the conversions (if any)
1403 // to be applied to the operands. If the overload resolution fails, the
1404 // program is ill-formed.
1405 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1406 return QualType();
1407 }
1408
1409 // C++0x 5.16p6
1410 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1411 // conversions are performed on the second and third operands.
1412 DefaultFunctionArrayConversion(LHS);
1413 DefaultFunctionArrayConversion(RHS);
1414 LTy = LHS->getType();
1415 RTy = RHS->getType();
1416
1417 // After those conversions, one of the following shall hold:
1418 // -- The second and third operands have the same type; the result
1419 // is of that type.
1420 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1421 return LTy;
1422
1423 // -- The second and third operands have arithmetic or enumeration type;
1424 // the usual arithmetic conversions are performed to bring them to a
1425 // common type, and the result is of that type.
1426 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1427 UsualArithmeticConversions(LHS, RHS);
1428 return LHS->getType();
1429 }
1430
1431 // -- The second and third operands have pointer type, or one has pointer
1432 // type and the other is a null pointer constant; pointer conversions
1433 // and qualification conversions are performed to bring them to their
1434 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001435 QualType Composite = FindCompositePointerType(LHS, RHS);
1436 if (!Composite.isNull())
1437 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001438
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001439 // Fourth bullet is same for pointers-to-member. However, the possible
1440 // conversions are far more limited: we have null-to-pointer, upcast of
1441 // containing class, and second-level cv-ness.
1442 // cv-ness is not a union, but must match one of the two operands. (Which,
1443 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001444 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1445 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001446 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1447 ImpCastExprToType(RHS, LTy);
1448 return LTy;
1449 }
1450 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1451 ImpCastExprToType(LHS, RTy);
1452 return RTy;
1453 }
1454 if (LMemPtr && RMemPtr) {
1455 QualType LPointee = LMemPtr->getPointeeType();
1456 QualType RPointee = RMemPtr->getPointeeType();
1457 // First, we check that the unqualified pointee type is the same. If it's
1458 // not, there's no conversion that will unify the two pointers.
1459 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1460 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1461 // Second, we take the greater of the two cv qualifications. If neither
1462 // is greater than the other, the conversion is not possible.
1463 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1464 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1465 // Third, we check if either of the container classes is derived from
1466 // the other.
1467 QualType LContainer(LMemPtr->getClass(), 0);
1468 QualType RContainer(RMemPtr->getClass(), 0);
1469 QualType MoreDerived;
1470 if (Context.getCanonicalType(LContainer) ==
1471 Context.getCanonicalType(RContainer))
1472 MoreDerived = LContainer;
1473 else if (IsDerivedFrom(LContainer, RContainer))
1474 MoreDerived = LContainer;
1475 else if (IsDerivedFrom(RContainer, LContainer))
1476 MoreDerived = RContainer;
1477
1478 if (!MoreDerived.isNull()) {
1479 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1480 // We don't use ImpCastExprToType here because this could still fail
1481 // for ambiguous or inaccessible conversions.
1482 QualType Common = Context.getMemberPointerType(
1483 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1484 if (PerformImplicitConversion(LHS, Common, "converting"))
1485 return QualType();
1486 if (PerformImplicitConversion(RHS, Common, "converting"))
1487 return QualType();
1488 return Common;
1489 }
1490 }
1491 }
1492 }
1493
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001494 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1495 << LHS->getType() << RHS->getType()
1496 << LHS->getSourceRange() << RHS->getSourceRange();
1497 return QualType();
1498}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001499
1500/// \brief Find a merged pointer type and convert the two expressions to it.
1501///
1502/// This finds the composite pointer type for @p E1 and @p E2 according to
1503/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1504/// It does not emit diagnostics.
1505QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1506 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1507 QualType T1 = E1->getType(), T2 = E2->getType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001508 if(!T1->isAnyPointerType() && !T2->isAnyPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001509 return QualType();
1510
1511 // C++0x 5.9p2
1512 // Pointer conversions and qualification conversions are performed on
1513 // pointer operands to bring them to their composite pointer type. If
1514 // one operand is a null pointer constant, the composite pointer type is
1515 // the type of the other operand.
1516 if (E1->isNullPointerConstant(Context)) {
1517 ImpCastExprToType(E1, T2);
1518 return T2;
1519 }
1520 if (E2->isNullPointerConstant(Context)) {
1521 ImpCastExprToType(E2, T1);
1522 return T1;
1523 }
1524 // Now both have to be pointers.
1525 if(!T1->isPointerType() || !T2->isPointerType())
1526 return QualType();
1527
1528 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1529 // the other has type "pointer to cv2 T" and the composite pointer type is
1530 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1531 // Otherwise, the composite pointer type is a pointer type similar to the
1532 // type of one of the operands, with a cv-qualification signature that is
1533 // the union of the cv-qualification signatures of the operand types.
1534 // In practice, the first part here is redundant; it's subsumed by the second.
1535 // What we do here is, we build the two possible composite types, and try the
1536 // conversions in both directions. If only one works, or if the two composite
1537 // types are the same, we have succeeded.
1538 llvm::SmallVector<unsigned, 4> QualifierUnion;
1539 QualType Composite1 = T1, Composite2 = T2;
1540 const PointerType *Ptr1, *Ptr2;
Ted Kremenek6217b802009-07-29 21:53:49 +00001541 while ((Ptr1 = Composite1->getAs<PointerType>()) &&
1542 (Ptr2 = Composite2->getAs<PointerType>())) {
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001543 Composite1 = Ptr1->getPointeeType();
1544 Composite2 = Ptr2->getPointeeType();
1545 QualifierUnion.push_back(
1546 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1547 }
1548 // Rewrap the composites as pointers with the union CVRs.
1549 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1550 E = QualifierUnion.end(); I != E; ++I) {
1551 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1552 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1553 }
1554
1555 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1556 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1557 ImplicitConversionSequence E1ToC2, E2ToC2;
1558 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1559 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1560 if (Context.getCanonicalType(Composite1) !=
1561 Context.getCanonicalType(Composite2)) {
1562 E1ToC2 = TryImplicitConversion(E1, Composite2);
1563 E2ToC2 = TryImplicitConversion(E2, Composite2);
1564 }
1565
1566 bool ToC1Viable = E1ToC1.ConversionKind !=
1567 ImplicitConversionSequence::BadConversion
1568 && E2ToC1.ConversionKind !=
1569 ImplicitConversionSequence::BadConversion;
1570 bool ToC2Viable = E1ToC2.ConversionKind !=
1571 ImplicitConversionSequence::BadConversion
1572 && E2ToC2.ConversionKind !=
1573 ImplicitConversionSequence::BadConversion;
1574 if (ToC1Viable && !ToC2Viable) {
1575 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1576 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1577 return Composite1;
1578 }
1579 if (ToC2Viable && !ToC1Viable) {
1580 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1581 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1582 return Composite2;
1583 }
1584 return QualType();
1585}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001586
Anders Carlssondef11992009-05-30 20:36:53 +00001587Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001588 if (!Context.getLangOptions().CPlusPlus)
1589 return Owned(E);
1590
Ted Kremenek6217b802009-07-29 21:53:49 +00001591 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001592 if (!RT)
1593 return Owned(E);
1594
1595 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1596 if (RD->hasTrivialDestructor())
1597 return Owned(E);
1598
1599 CXXTemporary *Temp = CXXTemporary::Create(Context,
1600 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001601 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001602 if (CXXDestructorDecl *Destructor =
1603 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1604 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001605 // FIXME: Add the temporary to the temporaries vector.
1606 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1607}
1608
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001609Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001610 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001611 assert(SubExpr && "sub expression can't be null!");
1612
1613 if (ExprTemporaries.empty())
1614 return SubExpr;
1615
1616 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1617 &ExprTemporaries[0],
1618 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001619 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001620 ExprTemporaries.clear();
1621
1622 return E;
1623}
1624
Anders Carlsson165a0a02009-05-17 18:41:29 +00001625Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1626 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001627 if (FullExpr)
Anders Carlssonf54741e2009-06-16 03:37:31 +00001628 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1629 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001630
1631 return Owned(FullExpr);
1632}