blob: 18382bab21c64a43454364ade4cceadc0affeb41 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redlaa4c3732009-02-07 20:10:22 +000014#include "SemaInherit.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroffac5d4f12007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5ee8742008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23
Douglas Gregor24094772008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregorb0212bd2008-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 Redlcd883f72009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd883f72009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000040}
Sebastian Redlb93b49c2008-11-11 11:37:55 +000041
Douglas Gregor24094772008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregor96a32dd2008-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 Redlcd883f72009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor24094772008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregor96a32dd2008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redl0c9da212009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregor96a32dd2008-11-18 14:39:36 +000056}
57
Sebastian Redlb93b49c2008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000059Action::OwningExprResult
Sebastian Redlb93b49c2008-11-11 11:37:55 +000060Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattnerc2a5f512008-11-20 05:51:55 +000063 if (!StdNs)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000064 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Chris Lattnerc2a5f512008-11-20 05:51:55 +000065
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor52ae30c2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerc2a5f512008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000070 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlb93b49c2008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000074 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75 TypeInfoType.withConst(),
76 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlb93b49c2008-11-11 11:37:55 +000077}
78
Steve Naroff5cbb02f2007-09-16 14:56:35 +000079/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000080Action::OwningExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +000081Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +000082 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +000083 "Unknown C++ Boolean value!");
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000084 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85 Context.BoolTy, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +000086}
Chris Lattnera7447ba2008-02-26 00:51:44 +000087
Sebastian Redl5d0ead72009-05-10 18:38:11 +000088/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
89Action::OwningExprResult
90Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
91 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
92}
93
Chris Lattnera7447ba2008-02-26 00:51:44 +000094/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000095Action::OwningExprResult
96Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +000097 Expr *Ex = E.takeAs<Expr>();
98 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
99 return ExprError();
100 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
101}
102
103/// CheckCXXThrowOperand - Validate the operand of a throw.
104bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
105 // C++ [except.throw]p3:
106 // [...] adjusting the type from "array of T" or "function returning T"
107 // to "pointer to T" or "pointer to function returning T", [...]
108 DefaultFunctionArrayConversion(E);
109
110 // If the type of the exception would be an incomplete type or a pointer
111 // to an incomplete type other than (cv) void the program is ill-formed.
112 QualType Ty = E->getType();
113 int isPointer = 0;
114 if (const PointerType* Ptr = Ty->getAsPointerType()) {
115 Ty = Ptr->getPointeeType();
116 isPointer = 1;
117 }
118 if (!isPointer || !Ty->isVoidType()) {
119 if (RequireCompleteType(ThrowLoc, Ty,
120 isPointer ? diag::err_throw_incomplete_ptr
121 : diag::err_throw_incomplete,
122 E->getSourceRange(), SourceRange(), QualType()))
123 return true;
124 }
125
126 // FIXME: Construct a temporary here.
127 return false;
Chris Lattnera7447ba2008-02-26 00:51:44 +0000128}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000129
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000130Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000131 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
132 /// is a non-lvalue expression whose value is the address of the object for
133 /// which the function is called.
134
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000135 if (!isa<FunctionDecl>(CurContext))
136 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000137
138 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
139 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXThisExpr(ThisLoc,
141 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000142
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000143 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000144}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000145
146/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
147/// Can be interpreted either as function-style casting ("int(x)")
148/// or class type construction ("ClassType(x,y,z)")
149/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000150Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000151Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
152 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000153 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000154 SourceLocation *CommaLocs,
155 SourceLocation RParenLoc) {
156 assert(TypeRep && "Missing type!");
157 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000165 exprs.release();
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000166
Douglas Gregorf27b7652009-05-20 18:46:25 +0000167 return Owned(CXXUnresolvedConstructExpr::Create(Context,
168 TypeRange.getBegin(), Ty,
169 LParenLoc,
170 Exprs, NumExprs,
171 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000172 }
173
174
Douglas Gregor861e7902009-01-16 18:33:17 +0000175 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000176 // If the expression list is a single expression, the type conversion
177 // expression is equivalent (in definedness, and if defined in meaning) to the
178 // corresponding cast expression.
179 //
180 if (NumExprs == 1) {
181 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000182 return ExprError();
183 exprs.release();
184 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
185 Ty, TyBeginLoc, Exprs[0],
186 RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000187 }
188
Douglas Gregor861e7902009-01-16 18:33:17 +0000189 if (const RecordType *RT = Ty->getAsRecordType()) {
190 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000191
Anders Carlssonf0967d72009-05-17 18:41:29 +0000192 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
193 // both the ctor and dtor are trivial.
Douglas Gregor861e7902009-01-16 18:33:17 +0000194 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
195 CXXConstructorDecl *Constructor
196 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
197 TypeRange.getBegin(),
198 SourceRange(TypeRange.getBegin(),
199 RParenLoc),
200 DeclarationName(),
201 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000202
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000203 if (!Constructor)
204 return ExprError();
205
206 exprs.release();
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000207 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssona05fa102009-05-30 20:36:53 +0000208 Ty, TyBeginLoc, Exprs,
209 NumExprs, RParenLoc);
210 return MaybeBindToTemporary(E);
Douglas Gregor861e7902009-01-16 18:33:17 +0000211 }
212
213 // Fall through to value-initialize an object of class type that
214 // doesn't have a user-declared default constructor.
215 }
216
217 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000218 // If the expression list specifies more than a single value, the type shall
219 // be a class with a suitably declared constructor.
220 //
221 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000222 return ExprError(Diag(CommaLocs[0],
223 diag::err_builtin_func_cast_more_than_one_arg)
224 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000225
226 assert(NumExprs == 0 && "Expected 0 expressions");
227
Douglas Gregor861e7902009-01-16 18:33:17 +0000228 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000229 // The expression T(), where T is a simple-type-specifier for a non-array
230 // complete object type or the (possibly cv-qualified) void type, creates an
231 // rvalue of the specified type, which is value-initialized.
232 //
233 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000234 return ExprError(Diag(TyBeginLoc,
235 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000236 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000237 RequireCompleteType(TyBeginLoc, Ty,
238 diag::err_invalid_incomplete_type_use, FullRange))
239 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000240
Anders Carlsson412c3402009-03-24 01:19:16 +0000241 if (RequireNonAbstractType(TyBeginLoc, Ty,
242 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000243 return ExprError();
244
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000245 exprs.release();
246 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000247}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000248
249
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000250/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
251/// @code new (memory) int[size][4] @endcode
252/// or
253/// @code ::new Foo(23, "hello") @endcode
254/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000255Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000256Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000257 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000258 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000259 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000260 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000261 SourceLocation ConstructorRParen)
262{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000263 Expr *ArraySize = 0;
264 unsigned Skip = 0;
265 // If the specified type is an array, unwrap it and save the expression.
266 if (D.getNumTypeObjects() > 0 &&
267 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
268 DeclaratorChunk &Chunk = D.getTypeObject(0);
269 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000270 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
271 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000272 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000273 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
274 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000275 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
276 Skip = 1;
277 }
278
279 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattner34c61332009-04-25 08:06:05 +0000280 if (D.isInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000281 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000282
Douglas Gregord8c23702009-05-21 00:00:09 +0000283 // Every dimension shall be of constant size.
284 unsigned i = 1;
285 QualType ElementType = AllocType;
286 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
287 if (!Array->isConstantArrayType()) {
288 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
289 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
290 return ExprError();
291 }
292 ElementType = Array->getElementType();
293 ++i;
294 }
295
296 return BuildCXXNew(StartLoc, UseGlobal,
297 PlacementLParen,
298 move(PlacementArgs),
299 PlacementRParen,
300 ParenTypeId,
301 AllocType,
302 D.getSourceRange().getBegin(),
303 D.getSourceRange(),
304 Owned(ArraySize),
305 ConstructorLParen,
306 move(ConstructorArgs),
307 ConstructorRParen);
308}
309
310Sema::OwningExprResult
311Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
312 SourceLocation PlacementLParen,
313 MultiExprArg PlacementArgs,
314 SourceLocation PlacementRParen,
315 bool ParenTypeId,
316 QualType AllocType,
317 SourceLocation TypeLoc,
318 SourceRange TypeRange,
319 ExprArg ArraySizeE,
320 SourceLocation ConstructorLParen,
321 MultiExprArg ConstructorArgs,
322 SourceLocation ConstructorRParen) {
323 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000324 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000325
Douglas Gregord8c23702009-05-21 00:00:09 +0000326 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000327
328 // That every array dimension except the first is constant was already
329 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000330
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000331 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
332 // or enumeration type with a non-negative value."
Douglas Gregord8c23702009-05-21 00:00:09 +0000333 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000334 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000335 QualType SizeType = ArraySize->getType();
336 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000337 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
338 diag::err_array_size_not_integral)
339 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000340 // Let's see if this is a constant < 0. If so, we reject it out of hand.
341 // We don't care about special rules, so we tell the machinery it's not
342 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000343 if (!ArraySize->isValueDependent()) {
344 llvm::APSInt Value;
345 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
346 if (Value < llvm::APSInt(
347 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000348 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
349 diag::err_typecheck_negative_array_size)
350 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000351 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000352 }
353 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000354
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000355 FunctionDecl *OperatorNew = 0;
356 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000357 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
358 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000359 if (!AllocType->isDependentType() &&
360 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
361 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000362 SourceRange(PlacementLParen, PlacementRParen),
363 UseGlobal, AllocType, ArraySize, PlaceArgs,
364 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000365 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000366
367 bool Init = ConstructorLParen.isValid();
368 // --- Choosing a constructor ---
369 // C++ 5.3.4p15
370 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
371 // the object is not initialized. If the object, or any part of it, is
372 // const-qualified, it's an error.
373 // 2) If T is a POD and there's an empty initializer, the object is value-
374 // initialized.
375 // 3) If T is a POD and there's one initializer argument, the object is copy-
376 // constructed.
377 // 4) If T is a POD and there's more initializer arguments, it's an error.
378 // 5) If T is not a POD, the initializer arguments are used as constructor
379 // arguments.
380 //
381 // Or by the C++0x formulation:
382 // 1) If there's no initializer, the object is default-initialized according
383 // to C++0x rules.
384 // 2) Otherwise, the object is direct-initialized.
385 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000386 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000387 const RecordType *RT;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000388 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000389 if (AllocType->isDependentType()) {
390 // Skip all the checks.
391 }
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000392 else if ((RT = AllocType->getAsRecordType()) &&
393 !AllocType->isAggregateType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000394 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000395 AllocType, ConsArgs, NumConsArgs,
Douglas Gregord8c23702009-05-21 00:00:09 +0000396 TypeLoc,
397 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000398 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000399 NumConsArgs != 0 ? IK_Direct : IK_Default);
400 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000401 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000402 } else {
403 if (!Init) {
404 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000405 if (AllocType.isConstQualified())
406 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord8c23702009-05-21 00:00:09 +0000407 << TypeRange);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000408 } else if (NumConsArgs == 0) {
409 // Object is value-initialized. Do nothing.
410 } else if (NumConsArgs == 1) {
411 // Object is direct-initialized.
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000412 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000413 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000414 DeclarationName() /*AllocType.getAsString()*/,
415 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000416 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000417 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000418 return ExprError(Diag(StartLoc,
419 diag::err_builtin_direct_init_more_than_one_arg)
420 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000421 }
422 }
423
424 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
425
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000426 PlacementArgs.release();
427 ConstructorArgs.release();
Douglas Gregord8c23702009-05-21 00:00:09 +0000428 ArraySizeE.release();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000429 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000430 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000431 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregord8c23702009-05-21 00:00:09 +0000432 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000433}
434
435/// CheckAllocatedType - Checks that a type is suitable as the allocated type
436/// in a new-expression.
437/// dimension off and stores the size expression in ArraySize.
Douglas Gregord8c23702009-05-21 00:00:09 +0000438bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
439 SourceRange R)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000440{
441 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
442 // abstract class type or array thereof.
Douglas Gregor05e28f62009-03-24 19:52:54 +0000443 if (AllocType->isFunctionType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000444 return Diag(Loc, diag::err_bad_new_type)
445 << AllocType << 0 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000446 else if (AllocType->isReferenceType())
Douglas Gregord8c23702009-05-21 00:00:09 +0000447 return Diag(Loc, diag::err_bad_new_type)
448 << AllocType << 1 << R;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000449 else if (!AllocType->isDependentType() &&
Douglas Gregord8c23702009-05-21 00:00:09 +0000450 RequireCompleteType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000451 diag::err_new_incomplete_type,
Douglas Gregord8c23702009-05-21 00:00:09 +0000452 R))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000453 return true;
Douglas Gregord8c23702009-05-21 00:00:09 +0000454 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregor05e28f62009-03-24 19:52:54 +0000455 diag::err_allocation_of_abstract_type))
456 return true;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000457
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000458 return false;
459}
460
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000461/// FindAllocationFunctions - Finds the overloads of operator new and delete
462/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000463bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
464 bool UseGlobal, QualType AllocType,
465 bool IsArray, Expr **PlaceArgs,
466 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000467 FunctionDecl *&OperatorNew,
468 FunctionDecl *&OperatorDelete)
469{
470 // --- Choosing an allocation function ---
471 // C++ 5.3.4p8 - 14 & 18
472 // 1) If UseGlobal is true, only look in the global scope. Else, also look
473 // in the scope of the allocated class.
474 // 2) If an array size is given, look for operator new[], else look for
475 // operator new.
476 // 3) The first argument is always size_t. Append the arguments from the
477 // placement form.
478 // FIXME: Also find the appropriate delete operator.
479
480 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
481 // We don't care about the actual value of this argument.
482 // FIXME: Should the Sema create the expression and embed it in the syntax
483 // tree? Or should the consumer just recalculate the value?
Ted Kremenek0c97e042009-02-07 01:47:29 +0000484 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000485 Context.Target.getPointerWidth(0)),
486 Context.getSizeType(),
487 SourceLocation());
488 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
489
490 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
491 IsArray ? OO_Array_New : OO_New);
492 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000493 CXXRecordDecl *Record
494 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000495 // FIXME: We fail to find inherited overloads.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000496 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000497 AllocArgs.size(), Record, /*AllowMissing=*/true,
498 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000499 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000500 }
501 if (!OperatorNew) {
502 // Didn't find a member overload. Look for a global one.
503 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000504 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000505 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000506 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
507 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000508 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000509 }
510
Sebastian Redlec5f3262008-12-04 22:20:51 +0000511 // FIXME: This is leaked on error. But so much is currently in Sema that it's
512 // easier to clean it in one go.
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000513 AllocArgs[0]->Destroy(Context);
514 return false;
515}
516
Sebastian Redlec5f3262008-12-04 22:20:51 +0000517/// FindAllocationOverload - Find an fitting overload for the allocation
518/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000519bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
520 DeclarationName Name, Expr** Args,
521 unsigned NumArgs, DeclContext *Ctx,
522 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000523{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000524 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000525 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000526 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000527 if (AllowMissing)
528 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000529 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000530 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000531 }
532
533 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000534 for (; Alloc != AllocEnd; ++Alloc) {
535 // Even member operator new/delete are implicitly treated as
536 // static, so don't use AddMemberCandidate.
537 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
538 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
539 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000540 }
541
542 // Do the resolution.
543 OverloadCandidateSet::iterator Best;
544 switch(BestViableFunction(Candidates, Best)) {
545 case OR_Success: {
546 // Got one!
547 FunctionDecl *FnDecl = Best->Function;
548 // The first argument is size_t, and the first parameter must be size_t,
549 // too. This is checked on declaration and can be assumed. (It can't be
550 // asserted on, though, since invalid decls are left in there.)
551 for (unsigned i = 1; i < NumArgs; ++i) {
552 // FIXME: Passing word to diagnostic.
553 if (PerformCopyInitialization(Args[i-1],
554 FnDecl->getParamDecl(i)->getType(),
555 "passing"))
556 return true;
557 }
558 Operator = FnDecl;
559 return false;
560 }
561
562 case OR_No_Viable_Function:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000563 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000564 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000565 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
566 return true;
567
568 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000569 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000570 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000571 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
572 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000573
574 case OR_Deleted:
575 Diag(StartLoc, diag::err_ovl_deleted_call)
576 << Best->Function->isDeleted()
577 << Name << Range;
578 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
579 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000580 }
581 assert(false && "Unreachable, bad result from BestViableFunction");
582 return true;
583}
584
585
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000586/// DeclareGlobalNewDelete - Declare the global forms of operator new and
587/// delete. These are:
588/// @code
589/// void* operator new(std::size_t) throw(std::bad_alloc);
590/// void* operator new[](std::size_t) throw(std::bad_alloc);
591/// void operator delete(void *) throw();
592/// void operator delete[](void *) throw();
593/// @endcode
594/// Note that the placement and nothrow forms of new are *not* implicitly
595/// declared. Their use requires including \<new\>.
596void Sema::DeclareGlobalNewDelete()
597{
598 if (GlobalNewDeleteDeclared)
599 return;
600 GlobalNewDeleteDeclared = true;
601
602 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
603 QualType SizeT = Context.getSizeType();
604
605 // FIXME: Exception specifications are not added.
606 DeclareGlobalAllocationFunction(
607 Context.DeclarationNames.getCXXOperatorName(OO_New),
608 VoidPtr, SizeT);
609 DeclareGlobalAllocationFunction(
610 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
611 VoidPtr, SizeT);
612 DeclareGlobalAllocationFunction(
613 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
614 Context.VoidTy, VoidPtr);
615 DeclareGlobalAllocationFunction(
616 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
617 Context.VoidTy, VoidPtr);
618}
619
620/// DeclareGlobalAllocationFunction - Declares a single implicit global
621/// allocation function if it doesn't already exist.
622void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
623 QualType Return, QualType Argument)
624{
625 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
626
627 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000628 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000629 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000630 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000631 Alloc != AllocEnd; ++Alloc) {
632 // FIXME: Do we need to check for default arguments here?
633 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
634 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000635 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000636 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000637 }
638 }
639
640 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
641 FunctionDecl *Alloc =
642 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000643 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000644 SourceLocation());
645 Alloc->setImplicit();
646 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000647 0, Argument, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000648 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000649
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000650 // FIXME: Also add this declaration to the IdentifierResolver, but
651 // make sure it is at the end of the chain to coincide with the
652 // global scope.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000653 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000654}
655
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000656/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
657/// @code ::delete ptr; @endcode
658/// or
659/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000660Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000661Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000662 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000663{
664 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
665 // having a single conversion function to a pointer type. The result has
666 // type void."
667 // DR599 amends "pointer type" to "pointer to object type" in both cases.
668
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000669 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000670 if (!Ex->isTypeDependent()) {
671 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000672
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000673 if (Type->isRecordType()) {
674 // FIXME: Find that one conversion function and amend the type.
675 }
676
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000677 if (!Type->isPointerType())
678 return ExprError(Diag(StartLoc, diag::err_delete_operand)
679 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000680
681 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000682 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000683 return ExprError(Diag(StartLoc, diag::err_delete_operand)
684 << Type << Ex->getSourceRange());
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000685 else if (!Pointee->isDependentType() &&
686 RequireCompleteType(StartLoc, Pointee,
687 diag::warn_delete_incomplete,
688 Ex->getSourceRange()))
689 return ExprError();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000690
691 // FIXME: Look up the correct operator delete overload and pass a pointer
692 // along.
693 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000694 }
695
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000696 Operand.release();
697 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
698 0, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000699}
700
701
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000702/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
703/// C++ if/switch/while/for statement.
704/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000705Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000706Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
707 Declarator &D,
708 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000709 ExprArg AssignExprVal) {
710 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000711
712 // C++ 6.4p2:
713 // The declarator shall not specify a function or an array.
714 // The type-specifier-seq shall not contain typedef and shall not declare a
715 // new class or enumeration.
716
717 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
718 "Parser allowed 'typedef' as storage class of condition decl.");
719
720 QualType Ty = GetTypeForDeclarator(D, S);
721
722 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
723 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
724 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000725 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
726 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000727 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000728 Diag(StartLoc, diag::err_invalid_use_of_array_type)
729 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000730 } else if (const RecordType *RT = Ty->getAsRecordType()) {
731 RecordDecl *RD = RT->getDecl();
732 // The type-specifier-seq shall not declare a new class...
Chris Lattner5261d0c2009-03-28 19:18:32 +0000733 if (RD->isDefinition() &&
734 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000735 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
736 } else if (const EnumType *ET = Ty->getAsEnumType()) {
737 EnumDecl *ED = ET->getDecl();
738 // ...or enumeration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000739 if (ED->isDefinition() &&
740 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000741 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
742 }
743
Chris Lattner5261d0c2009-03-28 19:18:32 +0000744 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000745 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000746 return ExprError();
Anders Carlssonf9f05b82009-05-30 21:37:25 +0000747 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000748
Douglas Gregor48840c72008-12-10 23:01:14 +0000749 // Mark this variable as one that is declared within a conditional.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000750 // We know that the decl had to be a VarDecl because that is the only type of
751 // decl that can be assigned and the grammar requires an '='.
752 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
753 VD->setDeclaredInCondition(true);
754 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000755}
756
757/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
758bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
759 // C++ 6.4p4:
760 // The value of a condition that is an initialized declaration in a statement
761 // other than a switch statement is the value of the declared variable
762 // implicitly converted to type bool. If that conversion is ill-formed, the
763 // program is ill-formed.
764 // The value of a condition that is an expression is the value of the
765 // expression, implicitly converted to bool.
766 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000767 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000768}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000769
770/// Helper function to determine whether this is the (deprecated) C++
771/// conversion from a string literal to a pointer to non-const char or
772/// non-const wchar_t (for narrow and wide string literals,
773/// respectively).
774bool
775Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
776 // Look inside the implicit cast, if it exists.
777 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
778 From = Cast->getSubExpr();
779
780 // A string literal (2.13.4) that is not a wide string literal can
781 // be converted to an rvalue of type "pointer to char"; a wide
782 // string literal can be converted to an rvalue of type "pointer
783 // to wchar_t" (C++ 4.2p2).
784 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
785 if (const PointerType *ToPtrType = ToType->getAsPointerType())
786 if (const BuiltinType *ToPointeeType
787 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
788 // This conversion is considered only when there is an
789 // explicit appropriate pointer target type (C++ 4.2p2).
790 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
791 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
792 (!StrLit->isWide() &&
793 (ToPointeeType->getKind() == BuiltinType::Char_U ||
794 ToPointeeType->getKind() == BuiltinType::Char_S))))
795 return true;
796 }
797
798 return false;
799}
Douglas Gregorbb461502008-10-24 04:54:22 +0000800
801/// PerformImplicitConversion - Perform an implicit conversion of the
802/// expression From to the type ToType. Returns true if there was an
803/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000804/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000805/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redla55834a2009-04-12 17:16:29 +0000806/// explicit user-defined conversions are permitted. @p Elidable should be true
807/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
808/// resolution works differently in that case.
809bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000810Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +0000811 const char *Flavor, bool AllowExplicit,
812 bool Elidable)
Douglas Gregorbb461502008-10-24 04:54:22 +0000813{
Sebastian Redla55834a2009-04-12 17:16:29 +0000814 ImplicitConversionSequence ICS;
815 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
816 if (Elidable && getLangOptions().CPlusPlus0x) {
817 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
818 AllowExplicit, /*ForceRValue*/true);
819 }
820 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
821 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
822 }
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000823 return PerformImplicitConversion(From, ToType, ICS, Flavor);
824}
825
826/// PerformImplicitConversion - Perform an implicit conversion of the
827/// expression From to the type ToType using the pre-computed implicit
828/// conversion sequence ICS. Returns true if there was an error, false
829/// otherwise. The expression From is replaced with the converted
830/// expression. Flavor is the kind of conversion we're performing,
831/// used in the error message.
832bool
833Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
834 const ImplicitConversionSequence &ICS,
835 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000836 switch (ICS.ConversionKind) {
837 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000838 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000839 return true;
840 break;
841
842 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stumpe127ae32009-05-16 07:39:55 +0000843 // FIXME: This is, of course, wrong. We'll need to actually call the
844 // constructor or conversion operator, and then cope with the standard
845 // conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000846 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000847 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000848 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000849
850 case ImplicitConversionSequence::EllipsisConversion:
851 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000852 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000853
854 case ImplicitConversionSequence::BadConversion:
855 return true;
856 }
857
858 // Everything went well.
859 return false;
860}
861
862/// PerformImplicitConversion - Perform an implicit conversion of the
863/// expression From to the type ToType by following the standard
864/// conversion sequence SCS. Returns true if there was an error, false
865/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000866/// expression. Flavor is the context in which we're performing this
867/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000868bool
869Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000870 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000871 const char *Flavor) {
Mike Stumpe127ae32009-05-16 07:39:55 +0000872 // Overall FIXME: we are recomputing too many types here and doing far too
873 // much extra work. What this means is that we need to keep track of more
874 // information that is computed when we try the implicit conversion initially,
875 // so that we don't need to recompute anything here.
Douglas Gregorbb461502008-10-24 04:54:22 +0000876 QualType FromType = From->getType();
877
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000878 if (SCS.CopyConstructor) {
Anders Carlsson0e098352009-05-19 04:45:15 +0000879 // FIXME: When can ToType be a reference type?
880 assert(!ToType->isReferenceType());
881
Anders Carlsson0e098352009-05-19 04:45:15 +0000882 // FIXME: Keep track of whether the copy constructor is elidable or not.
Anders Carlsson7b7b2552009-05-30 20:56:46 +0000883 From = CXXConstructExpr::Create(Context, ToType,
Anders Carlsson0e098352009-05-19 04:45:15 +0000884 SCS.CopyConstructor, false, &From, 1);
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000885 return false;
886 }
887
Douglas Gregorbb461502008-10-24 04:54:22 +0000888 // Perform the first implicit conversion.
889 switch (SCS.First) {
890 case ICK_Identity:
891 case ICK_Lvalue_To_Rvalue:
892 // Nothing to do.
893 break;
894
895 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000896 FromType = Context.getArrayDecayedType(FromType);
897 ImpCastExprToType(From, FromType);
898 break;
899
900 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000901 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000902 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
903 if (!Fn)
904 return true;
905
Douglas Gregoraa57e862009-02-18 21:56:37 +0000906 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
907 return true;
908
Douglas Gregor45014fd2008-11-10 20:40:00 +0000909 FixOverloadedFunctionReference(From, Fn);
910 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000911 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000912 FromType = Context.getPointerType(FromType);
913 ImpCastExprToType(From, FromType);
914 break;
915
916 default:
917 assert(false && "Improper first standard conversion");
918 break;
919 }
920
921 // Perform the second implicit conversion
922 switch (SCS.Second) {
923 case ICK_Identity:
924 // Nothing to do.
925 break;
926
927 case ICK_Integral_Promotion:
928 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000929 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000930 case ICK_Integral_Conversion:
931 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000932 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000933 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +0000934 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +0000935 case ICK_Compatible_Conversion:
936 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +0000937 FromType = ToType.getUnqualifiedType();
938 ImpCastExprToType(From, FromType);
939 break;
940
941 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000942 if (SCS.IncompatibleObjC) {
943 // Diagnose incompatible Objective-C conversions
944 Diag(From->getSourceRange().getBegin(),
945 diag::ext_typecheck_convert_incompatible_pointer)
946 << From->getType() << ToType << Flavor
947 << From->getSourceRange();
948 }
949
Douglas Gregorbb461502008-10-24 04:54:22 +0000950 if (CheckPointerConversion(From, ToType))
951 return true;
952 ImpCastExprToType(From, ToType);
953 break;
954
955 case ICK_Pointer_Member:
Sebastian Redlba387562009-01-25 19:43:20 +0000956 if (CheckMemberPointerConversion(From, ToType))
957 return true;
958 ImpCastExprToType(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000959 break;
960
961 case ICK_Boolean_Conversion:
962 FromType = Context.BoolTy;
963 ImpCastExprToType(From, FromType);
964 break;
965
966 default:
967 assert(false && "Improper second standard conversion");
968 break;
969 }
970
971 switch (SCS.Third) {
972 case ICK_Identity:
973 // Nothing to do.
974 break;
975
976 case ICK_Qualification:
Mike Stumpe127ae32009-05-16 07:39:55 +0000977 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
978 // references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000979 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000980 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +0000981 break;
982
983 default:
984 assert(false && "Improper second standard conversion");
985 break;
986 }
987
988 return false;
989}
990
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000991Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
992 SourceLocation KWLoc,
993 SourceLocation LParen,
994 TypeTy *Ty,
995 SourceLocation RParen) {
996 // FIXME: Some of the type traits have requirements. Interestingly, only the
Mike Stumpe127ae32009-05-16 07:39:55 +0000997 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++
998 // accepts __is_pod(Incomplete) without complaints, and claims that the type
999 // is indeed a POD.
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001000
1001 // There is no point in eagerly computing the value. The traits are designed
1002 // to be used from type trait templates, so Ty will be a template parameter
1003 // 99% of the time.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001004 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001005 QualType::getFromOpaquePtr(Ty),
1006 RParen, Context.BoolTy));
1007}
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001008
1009QualType Sema::CheckPointerToMemberOperands(
1010 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1011{
1012 const char *OpSpelling = isIndirect ? "->*" : ".*";
1013 // C++ 5.5p2
1014 // The binary operator .* [p3: ->*] binds its second operand, which shall
1015 // be of type "pointer to member of T" (where T is a completely-defined
1016 // class type) [...]
1017 QualType RType = rex->getType();
1018 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00001019 if (!MemPtr) {
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001020 Diag(Loc, diag::err_bad_memptr_rhs)
1021 << OpSpelling << RType << rex->getSourceRange();
1022 return QualType();
Douglas Gregor96b6df92009-05-14 00:28:11 +00001023 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00001024
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001025 QualType Class(MemPtr->getClass(), 0);
1026
1027 // C++ 5.5p2
1028 // [...] to its first operand, which shall be of class T or of a class of
1029 // which T is an unambiguous and accessible base class. [p3: a pointer to
1030 // such a class]
1031 QualType LType = lex->getType();
1032 if (isIndirect) {
1033 if (const PointerType *Ptr = LType->getAsPointerType())
1034 LType = Ptr->getPointeeType().getNonReferenceType();
1035 else {
1036 Diag(Loc, diag::err_bad_memptr_lhs)
1037 << OpSpelling << 1 << LType << lex->getSourceRange();
1038 return QualType();
1039 }
1040 }
1041
1042 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1043 Context.getCanonicalType(LType).getUnqualifiedType()) {
1044 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1045 /*DetectVirtual=*/false);
Mike Stumpe127ae32009-05-16 07:39:55 +00001046 // FIXME: Would it be useful to print full ambiguity paths, or is that
1047 // overkill?
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001048 if (!IsDerivedFrom(LType, Class, Paths) ||
1049 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1050 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1051 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1052 return QualType();
1053 }
1054 }
1055
1056 // C++ 5.5p2
1057 // The result is an object or a function of the type specified by the
1058 // second operand.
1059 // The cv qualifiers are the union of those in the pointer and the left side,
1060 // in accordance with 5.5p5 and 5.2.5.
1061 // FIXME: This returns a dereferenced member function pointer as a normal
1062 // function type. However, the only operation valid on such functions is
Mike Stumpe127ae32009-05-16 07:39:55 +00001063 // calling them. There's also a GCC extension to get a function pointer to the
1064 // thing, which is another complication, because this type - unlike the type
1065 // that is the result of this expression - takes the class as the first
Sebastian Redlaa4c3732009-02-07 20:10:22 +00001066 // argument.
1067 // We probably need a "MemberFunctionClosureType" or something like that.
1068 QualType Result = MemPtr->getPointeeType();
1069 if (LType.isConstQualified())
1070 Result.addConst();
1071 if (LType.isVolatileQualified())
1072 Result.addVolatile();
1073 return Result;
1074}
Sebastian Redlbd261962009-04-16 17:51:27 +00001075
1076/// \brief Get the target type of a standard or user-defined conversion.
1077static QualType TargetType(const ImplicitConversionSequence &ICS) {
1078 assert((ICS.ConversionKind ==
1079 ImplicitConversionSequence::StandardConversion ||
1080 ICS.ConversionKind ==
1081 ImplicitConversionSequence::UserDefinedConversion) &&
1082 "function only valid for standard or user-defined conversions");
1083 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1084 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1085 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1086}
1087
1088/// \brief Try to convert a type to another according to C++0x 5.16p3.
1089///
1090/// This is part of the parameter validation for the ? operator. If either
1091/// value operand is a class type, the two operands are attempted to be
1092/// converted to each other. This function does the conversion in one direction.
1093/// It emits a diagnostic and returns true only if it finds an ambiguous
1094/// conversion.
1095static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1096 SourceLocation QuestionLoc,
1097 ImplicitConversionSequence &ICS)
1098{
1099 // C++0x 5.16p3
1100 // The process for determining whether an operand expression E1 of type T1
1101 // can be converted to match an operand expression E2 of type T2 is defined
1102 // as follows:
1103 // -- If E2 is an lvalue:
1104 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1105 // E1 can be converted to match E2 if E1 can be implicitly converted to
1106 // type "lvalue reference to T2", subject to the constraint that in the
1107 // conversion the reference must bind directly to E1.
1108 if (!Self.CheckReferenceInit(From,
1109 Self.Context.getLValueReferenceType(To->getType()),
1110 &ICS))
1111 {
1112 assert((ICS.ConversionKind ==
1113 ImplicitConversionSequence::StandardConversion ||
1114 ICS.ConversionKind ==
1115 ImplicitConversionSequence::UserDefinedConversion) &&
1116 "expected a definite conversion");
1117 bool DirectBinding =
1118 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1119 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1120 if (DirectBinding)
1121 return false;
1122 }
1123 }
1124 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1125 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1126 // -- if E1 and E2 have class type, and the underlying class types are
1127 // the same or one is a base class of the other:
1128 QualType FTy = From->getType();
1129 QualType TTy = To->getType();
1130 const RecordType *FRec = FTy->getAsRecordType();
1131 const RecordType *TRec = TTy->getAsRecordType();
1132 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1133 if (FRec && TRec && (FRec == TRec ||
1134 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1135 // E1 can be converted to match E2 if the class of T2 is the
1136 // same type as, or a base class of, the class of T1, and
1137 // [cv2 > cv1].
1138 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1139 // Could still fail if there's no copy constructor.
1140 // FIXME: Is this a hard error then, or just a conversion failure? The
1141 // standard doesn't say.
1142 ICS = Self.TryCopyInitialization(From, TTy);
1143 }
1144 } else {
1145 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1146 // implicitly converted to the type that expression E2 would have
1147 // if E2 were converted to an rvalue.
1148 // First find the decayed type.
1149 if (TTy->isFunctionType())
1150 TTy = Self.Context.getPointerType(TTy);
1151 else if(TTy->isArrayType())
1152 TTy = Self.Context.getArrayDecayedType(TTy);
1153
1154 // Now try the implicit conversion.
1155 // FIXME: This doesn't detect ambiguities.
1156 ICS = Self.TryImplicitConversion(From, TTy);
1157 }
1158 return false;
1159}
1160
1161/// \brief Try to find a common type for two according to C++0x 5.16p5.
1162///
1163/// This is part of the parameter validation for the ? operator. If either
1164/// value operand is a class type, overload resolution is used to find a
1165/// conversion to a common type.
1166static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1167 SourceLocation Loc) {
1168 Expr *Args[2] = { LHS, RHS };
1169 OverloadCandidateSet CandidateSet;
1170 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1171
1172 OverloadCandidateSet::iterator Best;
1173 switch (Self.BestViableFunction(CandidateSet, Best)) {
1174 case Sema::OR_Success:
1175 // We found a match. Perform the conversions on the arguments and move on.
1176 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1177 Best->Conversions[0], "converting") ||
1178 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1179 Best->Conversions[1], "converting"))
1180 break;
1181 return false;
1182
1183 case Sema::OR_No_Viable_Function:
1184 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1185 << LHS->getType() << RHS->getType()
1186 << LHS->getSourceRange() << RHS->getSourceRange();
1187 return true;
1188
1189 case Sema::OR_Ambiguous:
1190 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1191 << LHS->getType() << RHS->getType()
1192 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpe127ae32009-05-16 07:39:55 +00001193 // FIXME: Print the possible common types by printing the return types of
1194 // the viable candidates.
Sebastian Redlbd261962009-04-16 17:51:27 +00001195 break;
1196
1197 case Sema::OR_Deleted:
1198 assert(false && "Conditional operator has only built-in overloads");
1199 break;
1200 }
1201 return true;
1202}
1203
Sebastian Redld3169132009-04-17 16:30:52 +00001204/// \brief Perform an "extended" implicit conversion as returned by
1205/// TryClassUnification.
1206///
1207/// TryClassUnification generates ICSs that include reference bindings.
1208/// PerformImplicitConversion is not suitable for this; it chokes if the
1209/// second part of a standard conversion is ICK_DerivedToBase. This function
1210/// handles the reference binding specially.
1211static bool ConvertForConditional(Sema &Self, Expr *&E,
1212 const ImplicitConversionSequence &ICS)
1213{
1214 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1215 ICS.Standard.ReferenceBinding) {
1216 assert(ICS.Standard.DirectBinding &&
1217 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001218 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1219 // redoing all the work.
1220 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1221 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001222 }
1223 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1224 ICS.UserDefined.After.ReferenceBinding) {
1225 assert(ICS.UserDefined.After.DirectBinding &&
1226 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001227 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1228 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001229 }
1230 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1231 return true;
1232 return false;
1233}
1234
Sebastian Redlbd261962009-04-16 17:51:27 +00001235/// \brief Check the operands of ?: under C++ semantics.
1236///
1237/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1238/// extension. In this case, LHS == Cond. (But they're not aliases.)
1239QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1240 SourceLocation QuestionLoc) {
Mike Stumpe127ae32009-05-16 07:39:55 +00001241 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1242 // interface pointers.
Sebastian Redlbd261962009-04-16 17:51:27 +00001243
1244 // C++0x 5.16p1
1245 // The first expression is contextually converted to bool.
1246 if (!Cond->isTypeDependent()) {
1247 if (CheckCXXBooleanCondition(Cond))
1248 return QualType();
1249 }
1250
1251 // Either of the arguments dependent?
1252 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1253 return Context.DependentTy;
1254
1255 // C++0x 5.16p2
1256 // If either the second or the third operand has type (cv) void, ...
1257 QualType LTy = LHS->getType();
1258 QualType RTy = RHS->getType();
1259 bool LVoid = LTy->isVoidType();
1260 bool RVoid = RTy->isVoidType();
1261 if (LVoid || RVoid) {
1262 // ... then the [l2r] conversions are performed on the second and third
1263 // operands ...
1264 DefaultFunctionArrayConversion(LHS);
1265 DefaultFunctionArrayConversion(RHS);
1266 LTy = LHS->getType();
1267 RTy = RHS->getType();
1268
1269 // ... and one of the following shall hold:
1270 // -- The second or the third operand (but not both) is a throw-
1271 // expression; the result is of the type of the other and is an rvalue.
1272 bool LThrow = isa<CXXThrowExpr>(LHS);
1273 bool RThrow = isa<CXXThrowExpr>(RHS);
1274 if (LThrow && !RThrow)
1275 return RTy;
1276 if (RThrow && !LThrow)
1277 return LTy;
1278
1279 // -- Both the second and third operands have type void; the result is of
1280 // type void and is an rvalue.
1281 if (LVoid && RVoid)
1282 return Context.VoidTy;
1283
1284 // Neither holds, error.
1285 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1286 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1287 << LHS->getSourceRange() << RHS->getSourceRange();
1288 return QualType();
1289 }
1290
1291 // Neither is void.
1292
1293 // C++0x 5.16p3
1294 // Otherwise, if the second and third operand have different types, and
1295 // either has (cv) class type, and attempt is made to convert each of those
1296 // operands to the other.
1297 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1298 (LTy->isRecordType() || RTy->isRecordType())) {
1299 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1300 // These return true if a single direction is already ambiguous.
1301 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1302 return QualType();
1303 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1304 return QualType();
1305
1306 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1307 ImplicitConversionSequence::BadConversion;
1308 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1309 ImplicitConversionSequence::BadConversion;
1310 // If both can be converted, [...] the program is ill-formed.
1311 if (HaveL2R && HaveR2L) {
1312 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1313 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1314 return QualType();
1315 }
1316
1317 // If exactly one conversion is possible, that conversion is applied to
1318 // the chosen operand and the converted operands are used in place of the
1319 // original operands for the remainder of this section.
1320 if (HaveL2R) {
Sebastian Redld3169132009-04-17 16:30:52 +00001321 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redlbd261962009-04-16 17:51:27 +00001322 return QualType();
1323 LTy = LHS->getType();
1324 } else if (HaveR2L) {
Sebastian Redld3169132009-04-17 16:30:52 +00001325 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redlbd261962009-04-16 17:51:27 +00001326 return QualType();
1327 RTy = RHS->getType();
1328 }
1329 }
1330
1331 // C++0x 5.16p4
1332 // If the second and third operands are lvalues and have the same type,
1333 // the result is of that type [...]
1334 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1335 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1336 RHS->isLvalue(Context) == Expr::LV_Valid)
1337 return LTy;
1338
1339 // C++0x 5.16p5
1340 // Otherwise, the result is an rvalue. If the second and third operands
1341 // do not have the same type, and either has (cv) class type, ...
1342 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1343 // ... overload resolution is used to determine the conversions (if any)
1344 // to be applied to the operands. If the overload resolution fails, the
1345 // program is ill-formed.
1346 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1347 return QualType();
1348 }
1349
1350 // C++0x 5.16p6
1351 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1352 // conversions are performed on the second and third operands.
1353 DefaultFunctionArrayConversion(LHS);
1354 DefaultFunctionArrayConversion(RHS);
1355 LTy = LHS->getType();
1356 RTy = RHS->getType();
1357
1358 // After those conversions, one of the following shall hold:
1359 // -- The second and third operands have the same type; the result
1360 // is of that type.
1361 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1362 return LTy;
1363
1364 // -- The second and third operands have arithmetic or enumeration type;
1365 // the usual arithmetic conversions are performed to bring them to a
1366 // common type, and the result is of that type.
1367 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1368 UsualArithmeticConversions(LHS, RHS);
1369 return LHS->getType();
1370 }
1371
1372 // -- The second and third operands have pointer type, or one has pointer
1373 // type and the other is a null pointer constant; pointer conversions
1374 // and qualification conversions are performed to bring them to their
1375 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001376 QualType Composite = FindCompositePointerType(LHS, RHS);
1377 if (!Composite.isNull())
1378 return Composite;
Sebastian Redlbd261962009-04-16 17:51:27 +00001379
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001380 // Fourth bullet is same for pointers-to-member. However, the possible
1381 // conversions are far more limited: we have null-to-pointer, upcast of
1382 // containing class, and second-level cv-ness.
1383 // cv-ness is not a union, but must match one of the two operands. (Which,
1384 // frankly, is stupid.)
1385 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1386 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1387 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1388 ImpCastExprToType(RHS, LTy);
1389 return LTy;
1390 }
1391 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1392 ImpCastExprToType(LHS, RTy);
1393 return RTy;
1394 }
1395 if (LMemPtr && RMemPtr) {
1396 QualType LPointee = LMemPtr->getPointeeType();
1397 QualType RPointee = RMemPtr->getPointeeType();
1398 // First, we check that the unqualified pointee type is the same. If it's
1399 // not, there's no conversion that will unify the two pointers.
1400 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1401 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1402 // Second, we take the greater of the two cv qualifications. If neither
1403 // is greater than the other, the conversion is not possible.
1404 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1405 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1406 // Third, we check if either of the container classes is derived from
1407 // the other.
1408 QualType LContainer(LMemPtr->getClass(), 0);
1409 QualType RContainer(RMemPtr->getClass(), 0);
1410 QualType MoreDerived;
1411 if (Context.getCanonicalType(LContainer) ==
1412 Context.getCanonicalType(RContainer))
1413 MoreDerived = LContainer;
1414 else if (IsDerivedFrom(LContainer, RContainer))
1415 MoreDerived = LContainer;
1416 else if (IsDerivedFrom(RContainer, LContainer))
1417 MoreDerived = RContainer;
1418
1419 if (!MoreDerived.isNull()) {
1420 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1421 // We don't use ImpCastExprToType here because this could still fail
1422 // for ambiguous or inaccessible conversions.
1423 QualType Common = Context.getMemberPointerType(
1424 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1425 if (PerformImplicitConversion(LHS, Common, "converting"))
1426 return QualType();
1427 if (PerformImplicitConversion(RHS, Common, "converting"))
1428 return QualType();
1429 return Common;
1430 }
1431 }
1432 }
1433 }
1434
Sebastian Redlbd261962009-04-16 17:51:27 +00001435 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1436 << LHS->getType() << RHS->getType()
1437 << LHS->getSourceRange() << RHS->getSourceRange();
1438 return QualType();
1439}
Sebastian Redl42b81a22009-04-19 19:26:31 +00001440
1441/// \brief Find a merged pointer type and convert the two expressions to it.
1442///
1443/// This finds the composite pointer type for @p E1 and @p E2 according to
1444/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1445/// It does not emit diagnostics.
1446QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1447 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1448 QualType T1 = E1->getType(), T2 = E2->getType();
1449 if(!T1->isPointerType() && !T2->isPointerType())
1450 return QualType();
1451
1452 // C++0x 5.9p2
1453 // Pointer conversions and qualification conversions are performed on
1454 // pointer operands to bring them to their composite pointer type. If
1455 // one operand is a null pointer constant, the composite pointer type is
1456 // the type of the other operand.
1457 if (E1->isNullPointerConstant(Context)) {
1458 ImpCastExprToType(E1, T2);
1459 return T2;
1460 }
1461 if (E2->isNullPointerConstant(Context)) {
1462 ImpCastExprToType(E2, T1);
1463 return T1;
1464 }
1465 // Now both have to be pointers.
1466 if(!T1->isPointerType() || !T2->isPointerType())
1467 return QualType();
1468
1469 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1470 // the other has type "pointer to cv2 T" and the composite pointer type is
1471 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1472 // Otherwise, the composite pointer type is a pointer type similar to the
1473 // type of one of the operands, with a cv-qualification signature that is
1474 // the union of the cv-qualification signatures of the operand types.
1475 // In practice, the first part here is redundant; it's subsumed by the second.
1476 // What we do here is, we build the two possible composite types, and try the
1477 // conversions in both directions. If only one works, or if the two composite
1478 // types are the same, we have succeeded.
1479 llvm::SmallVector<unsigned, 4> QualifierUnion;
1480 QualType Composite1 = T1, Composite2 = T2;
1481 const PointerType *Ptr1, *Ptr2;
1482 while ((Ptr1 = Composite1->getAsPointerType()) &&
1483 (Ptr2 = Composite2->getAsPointerType())) {
1484 Composite1 = Ptr1->getPointeeType();
1485 Composite2 = Ptr2->getPointeeType();
1486 QualifierUnion.push_back(
1487 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1488 }
1489 // Rewrap the composites as pointers with the union CVRs.
1490 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1491 E = QualifierUnion.end(); I != E; ++I) {
1492 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1493 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1494 }
1495
1496 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1497 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1498 ImplicitConversionSequence E1ToC2, E2ToC2;
1499 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1500 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1501 if (Context.getCanonicalType(Composite1) !=
1502 Context.getCanonicalType(Composite2)) {
1503 E1ToC2 = TryImplicitConversion(E1, Composite2);
1504 E2ToC2 = TryImplicitConversion(E2, Composite2);
1505 }
1506
1507 bool ToC1Viable = E1ToC1.ConversionKind !=
1508 ImplicitConversionSequence::BadConversion
1509 && E2ToC1.ConversionKind !=
1510 ImplicitConversionSequence::BadConversion;
1511 bool ToC2Viable = E1ToC2.ConversionKind !=
1512 ImplicitConversionSequence::BadConversion
1513 && E2ToC2.ConversionKind !=
1514 ImplicitConversionSequence::BadConversion;
1515 if (ToC1Viable && !ToC2Viable) {
1516 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1517 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1518 return Composite1;
1519 }
1520 if (ToC2Viable && !ToC1Viable) {
1521 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1522 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1523 return Composite2;
1524 }
1525 return QualType();
1526}
Anders Carlssonf0967d72009-05-17 18:41:29 +00001527
Anders Carlssona05fa102009-05-30 20:36:53 +00001528Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1529 const RecordType *RT = E->getType()->getAsRecordType();
1530 if (!RT)
1531 return Owned(E);
1532
1533 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1534 if (RD->hasTrivialDestructor())
1535 return Owned(E);
1536
1537 CXXTemporary *Temp = CXXTemporary::Create(Context,
1538 RD->getDestructor(Context));
Anders Carlsson1ef0ee92009-05-30 21:21:49 +00001539 ExprTemporaries.push_back(Temp);
1540
Anders Carlssona05fa102009-05-30 20:36:53 +00001541 // FIXME: Add the temporary to the temporaries vector.
1542 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1543}
1544
Anders Carlssonf0967d72009-05-17 18:41:29 +00001545Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1546 Expr *FullExpr = Arg.takeAs<Expr>();
1547 assert(FullExpr && "Null full expr!");
1548
1549 if (!ExprTemporaries.empty()) {
1550 // Create a cleanup expr.
1551 FullExpr =
1552 new (Context) CXXExprWithTemporaries(FullExpr, &ExprTemporaries[0],
1553 ExprTemporaries.size());
1554 ExprTemporaries.clear();
1555 }
1556
1557 return Owned(FullExpr);
1558}