blob: 92df67aa47da136188645681472206bd4e983f3d [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
88/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000089Action::OwningExprResult
90Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl9949a5e2009-04-27 20:27:31 +000091 Expr *Ex = E.takeAs<Expr>();
92 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
93 return ExprError();
94 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
95}
96
97/// CheckCXXThrowOperand - Validate the operand of a throw.
98bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
99 // C++ [except.throw]p3:
100 // [...] adjusting the type from "array of T" or "function returning T"
101 // to "pointer to T" or "pointer to function returning T", [...]
102 DefaultFunctionArrayConversion(E);
103
104 // If the type of the exception would be an incomplete type or a pointer
105 // to an incomplete type other than (cv) void the program is ill-formed.
106 QualType Ty = E->getType();
107 int isPointer = 0;
108 if (const PointerType* Ptr = Ty->getAsPointerType()) {
109 Ty = Ptr->getPointeeType();
110 isPointer = 1;
111 }
112 if (!isPointer || !Ty->isVoidType()) {
113 if (RequireCompleteType(ThrowLoc, Ty,
114 isPointer ? diag::err_throw_incomplete_ptr
115 : diag::err_throw_incomplete,
116 E->getSourceRange(), SourceRange(), QualType()))
117 return true;
118 }
119
120 // FIXME: Construct a temporary here.
121 return false;
Chris Lattnera7447ba2008-02-26 00:51:44 +0000122}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000123
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000124Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000125 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
126 /// is a non-lvalue expression whose value is the address of the object for
127 /// which the function is called.
128
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000129 if (!isa<FunctionDecl>(CurContext))
130 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000131
132 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
133 if (MD->isInstance())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000134 return Owned(new (Context) CXXThisExpr(ThisLoc,
135 MD->getThisType(Context)));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000136
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000137 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000138}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000139
140/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
141/// Can be interpreted either as function-style casting ("int(x)")
142/// or class type construction ("ClassType(x,y,z)")
143/// or creation of a value-initialized type ("int()").
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000144Action::OwningExprResult
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000145Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
146 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000147 MultiExprArg exprs,
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000148 SourceLocation *CommaLocs,
149 SourceLocation RParenLoc) {
150 assert(TypeRep && "Missing type!");
151 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000152 unsigned NumExprs = exprs.size();
153 Expr **Exprs = (Expr**)exprs.get();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000154 SourceLocation TyBeginLoc = TypeRange.getBegin();
155 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
156
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000157 if (Ty->isDependentType() ||
Douglas Gregor396f1142009-03-13 21:01:28 +0000158 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000159 exprs.release();
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000160
161 // FIXME: Is this correct?
162 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
Anders Carlssonaf443ed2009-04-24 05:44:25 +0000163 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty,
164 TyBeginLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000165 Exprs, NumExprs,
166 RParenLoc));
Douglas Gregor396f1142009-03-13 21:01:28 +0000167 }
168
169
Douglas Gregor861e7902009-01-16 18:33:17 +0000170 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000171 // If the expression list is a single expression, the type conversion
172 // expression is equivalent (in definedness, and if defined in meaning) to the
173 // corresponding cast expression.
174 //
175 if (NumExprs == 1) {
176 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000177 return ExprError();
178 exprs.release();
179 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
180 Ty, TyBeginLoc, Exprs[0],
181 RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000182 }
183
Douglas Gregor861e7902009-01-16 18:33:17 +0000184 if (const RecordType *RT = Ty->getAsRecordType()) {
185 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000186
Douglas Gregor861e7902009-01-16 18:33:17 +0000187 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
188 CXXConstructorDecl *Constructor
189 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
190 TypeRange.getBegin(),
191 SourceRange(TypeRange.getBegin(),
192 RParenLoc),
193 DeclarationName(),
194 IK_Direct);
Douglas Gregor861e7902009-01-16 18:33:17 +0000195
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000196 if (!Constructor)
197 return ExprError();
198
Anders Carlssonebbd7cd2009-04-24 05:23:13 +0000199 CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
200
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000201 exprs.release();
Anders Carlssonaf443ed2009-04-24 05:44:25 +0000202 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
203 Constructor, Ty,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000204 TyBeginLoc, Exprs,
205 NumExprs, RParenLoc));
Douglas Gregor861e7902009-01-16 18:33:17 +0000206 }
207
208 // Fall through to value-initialize an object of class type that
209 // doesn't have a user-declared default constructor.
210 }
211
212 // C++ [expr.type.conv]p1:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000213 // If the expression list specifies more than a single value, the type shall
214 // be a class with a suitably declared constructor.
215 //
216 if (NumExprs > 1)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000217 return ExprError(Diag(CommaLocs[0],
218 diag::err_builtin_func_cast_more_than_one_arg)
219 << FullRange);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000220
221 assert(NumExprs == 0 && "Expected 0 expressions");
222
Douglas Gregor861e7902009-01-16 18:33:17 +0000223 // C++ [expr.type.conv]p2:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000224 // The expression T(), where T is a simple-type-specifier for a non-array
225 // complete object type or the (possibly cv-qualified) void type, creates an
226 // rvalue of the specified type, which is value-initialized.
227 //
228 if (Ty->isArrayType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000229 return ExprError(Diag(TyBeginLoc,
230 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000231 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000232 RequireCompleteType(TyBeginLoc, Ty,
233 diag::err_invalid_incomplete_type_use, FullRange))
234 return ExprError();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000235
Anders Carlsson412c3402009-03-24 01:19:16 +0000236 if (RequireNonAbstractType(TyBeginLoc, Ty,
237 diag::err_allocation_of_abstract_type))
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000238 return ExprError();
239
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000240 exprs.release();
241 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000242}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000243
244
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000245/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
246/// @code new (memory) int[size][4] @endcode
247/// or
248/// @code ::new Foo(23, "hello") @endcode
249/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000250Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000251Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000252 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000253 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000254 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000255 MultiExprArg ConstructorArgs,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000256 SourceLocation ConstructorRParen)
257{
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000258 Expr *ArraySize = 0;
259 unsigned Skip = 0;
260 // If the specified type is an array, unwrap it and save the expression.
261 if (D.getNumTypeObjects() > 0 &&
262 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
263 DeclaratorChunk &Chunk = D.getTypeObject(0);
264 if (Chunk.Arr.hasStatic)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000265 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
266 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000267 if (!Chunk.Arr.NumElts)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000268 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
269 << D.getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000270 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
271 Skip = 1;
272 }
273
274 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
Chris Lattner34c61332009-04-25 08:06:05 +0000275 if (D.isInvalidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000276 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000277
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000278 if (CheckAllocatedType(AllocType, D))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000279 return ExprError();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000280
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000281 QualType ResultType = AllocType->isDependentType()
282 ? Context.DependentTy
283 : Context.getPointerType(AllocType);
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000284
285 // That every array dimension except the first is constant was already
286 // checked by the type check above.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000287
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000288 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
289 // or enumeration type with a non-negative value."
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000290 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000291 QualType SizeType = ArraySize->getType();
292 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000293 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
294 diag::err_array_size_not_integral)
295 << SizeType << ArraySize->getSourceRange());
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000296 // Let's see if this is a constant < 0. If so, we reject it out of hand.
297 // We don't care about special rules, so we tell the machinery it's not
298 // evaluated - it gives us a result in more cases.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000299 if (!ArraySize->isValueDependent()) {
300 llvm::APSInt Value;
301 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
302 if (Value < llvm::APSInt(
303 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000304 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
305 diag::err_typecheck_negative_array_size)
306 << ArraySize->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000307 }
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000308 }
309 }
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000310
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000311 FunctionDecl *OperatorNew = 0;
312 FunctionDecl *OperatorDelete = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000313 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
314 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000315 if (!AllocType->isDependentType() &&
316 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
317 FindAllocationFunctions(StartLoc,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000318 SourceRange(PlacementLParen, PlacementRParen),
319 UseGlobal, AllocType, ArraySize, PlaceArgs,
320 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000321 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000322
323 bool Init = ConstructorLParen.isValid();
324 // --- Choosing a constructor ---
325 // C++ 5.3.4p15
326 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
327 // the object is not initialized. If the object, or any part of it, is
328 // const-qualified, it's an error.
329 // 2) If T is a POD and there's an empty initializer, the object is value-
330 // initialized.
331 // 3) If T is a POD and there's one initializer argument, the object is copy-
332 // constructed.
333 // 4) If T is a POD and there's more initializer arguments, it's an error.
334 // 5) If T is not a POD, the initializer arguments are used as constructor
335 // arguments.
336 //
337 // Or by the C++0x formulation:
338 // 1) If there's no initializer, the object is default-initialized according
339 // to C++0x rules.
340 // 2) Otherwise, the object is direct-initialized.
341 CXXConstructorDecl *Constructor = 0;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000342 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000343 const RecordType *RT;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000344 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000345 if (AllocType->isDependentType()) {
346 // Skip all the checks.
347 }
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000348 else if ((RT = AllocType->getAsRecordType()) &&
349 !AllocType->isAggregateType()) {
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000350 Constructor = PerformInitializationByConstructor(
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000351 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000352 D.getSourceRange().getBegin(),
353 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000354 ConstructorRParen),
Chris Lattner271d4c22008-11-24 05:29:24 +0000355 RT->getDecl()->getDeclName(),
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000356 NumConsArgs != 0 ? IK_Direct : IK_Default);
357 if (!Constructor)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000358 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000359 } else {
360 if (!Init) {
361 // FIXME: Check that no subpart is const.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000362 if (AllocType.isConstQualified())
363 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
364 << D.getSourceRange());
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000365 } else if (NumConsArgs == 0) {
366 // Object is value-initialized. Do nothing.
367 } else if (NumConsArgs == 1) {
368 // Object is direct-initialized.
Sebastian Redl091cf8d2009-05-07 16:14:23 +0000369 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000370 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000371 DeclarationName() /*AllocType.getAsString()*/,
372 /*DirectInit=*/true))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000373 return ExprError();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000374 } else {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000375 return ExprError(Diag(StartLoc,
376 diag::err_builtin_direct_init_more_than_one_arg)
377 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000378 }
379 }
380
381 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
382
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000383 PlacementArgs.release();
384 ConstructorArgs.release();
385 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000386 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000387 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000388 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000389}
390
391/// CheckAllocatedType - Checks that a type is suitable as the allocated type
392/// in a new-expression.
393/// dimension off and stores the size expression in ArraySize.
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000394bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000395{
396 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
397 // abstract class type or array thereof.
Douglas Gregor05e28f62009-03-24 19:52:54 +0000398 if (AllocType->isFunctionType())
399 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
400 << AllocType << 0 << D.getSourceRange();
401 else if (AllocType->isReferenceType())
402 return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
403 << AllocType << 1 << D.getSourceRange();
404 else if (!AllocType->isDependentType() &&
405 RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
406 diag::err_new_incomplete_type,
407 D.getSourceRange()))
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000408 return true;
Douglas Gregor05e28f62009-03-24 19:52:54 +0000409 else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
410 diag::err_allocation_of_abstract_type))
411 return true;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000412
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000413 // Every dimension shall be of constant size.
414 unsigned i = 1;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000415 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
416 if (!Array->isConstantArrayType()) {
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000417 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
418 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000419 return true;
420 }
421 AllocType = Array->getElementType();
Sebastian Redl66df3ef2008-12-02 14:43:59 +0000422 ++i;
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000423 }
424
425 return false;
426}
427
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000428/// FindAllocationFunctions - Finds the overloads of operator new and delete
429/// that are appropriate for the allocation.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000430bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
431 bool UseGlobal, QualType AllocType,
432 bool IsArray, Expr **PlaceArgs,
433 unsigned NumPlaceArgs,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000434 FunctionDecl *&OperatorNew,
435 FunctionDecl *&OperatorDelete)
436{
437 // --- Choosing an allocation function ---
438 // C++ 5.3.4p8 - 14 & 18
439 // 1) If UseGlobal is true, only look in the global scope. Else, also look
440 // in the scope of the allocated class.
441 // 2) If an array size is given, look for operator new[], else look for
442 // operator new.
443 // 3) The first argument is always size_t. Append the arguments from the
444 // placement form.
445 // FIXME: Also find the appropriate delete operator.
446
447 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
448 // We don't care about the actual value of this argument.
449 // FIXME: Should the Sema create the expression and embed it in the syntax
450 // tree? Or should the consumer just recalculate the value?
Ted Kremenek0c97e042009-02-07 01:47:29 +0000451 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000452 Context.Target.getPointerWidth(0)),
453 Context.getSizeType(),
454 SourceLocation());
455 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
456
457 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
458 IsArray ? OO_Array_New : OO_New);
459 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregor2e047592009-02-28 01:32:25 +0000460 CXXRecordDecl *Record
461 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redlec5f3262008-12-04 22:20:51 +0000462 // FIXME: We fail to find inherited overloads.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000463 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000464 AllocArgs.size(), Record, /*AllowMissing=*/true,
465 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000466 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000467 }
468 if (!OperatorNew) {
469 // Didn't find a member overload. Look for a global one.
470 DeclareGlobalNewDelete();
Sebastian Redlec5f3262008-12-04 22:20:51 +0000471 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000472 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redlec5f3262008-12-04 22:20:51 +0000473 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
474 OperatorNew))
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000475 return true;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000476 }
477
Sebastian Redlec5f3262008-12-04 22:20:51 +0000478 // FIXME: This is leaked on error. But so much is currently in Sema that it's
479 // easier to clean it in one go.
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000480 AllocArgs[0]->Destroy(Context);
481 return false;
482}
483
Sebastian Redlec5f3262008-12-04 22:20:51 +0000484/// FindAllocationOverload - Find an fitting overload for the allocation
485/// function in the specified scope.
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000486bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
487 DeclarationName Name, Expr** Args,
488 unsigned NumArgs, DeclContext *Ctx,
489 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redlec5f3262008-12-04 22:20:51 +0000490{
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000491 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000492 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000493 if (Alloc == AllocEnd) {
Sebastian Redlec5f3262008-12-04 22:20:51 +0000494 if (AllowMissing)
495 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000496 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000497 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000498 }
499
500 OverloadCandidateSet Candidates;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000501 for (; Alloc != AllocEnd; ++Alloc) {
502 // Even member operator new/delete are implicitly treated as
503 // static, so don't use AddMemberCandidate.
504 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
505 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
506 /*SuppressUserConversions=*/false);
Sebastian Redlec5f3262008-12-04 22:20:51 +0000507 }
508
509 // Do the resolution.
510 OverloadCandidateSet::iterator Best;
511 switch(BestViableFunction(Candidates, Best)) {
512 case OR_Success: {
513 // Got one!
514 FunctionDecl *FnDecl = Best->Function;
515 // The first argument is size_t, and the first parameter must be size_t,
516 // too. This is checked on declaration and can be assumed. (It can't be
517 // asserted on, though, since invalid decls are left in there.)
518 for (unsigned i = 1; i < NumArgs; ++i) {
519 // FIXME: Passing word to diagnostic.
520 if (PerformCopyInitialization(Args[i-1],
521 FnDecl->getParamDecl(i)->getType(),
522 "passing"))
523 return true;
524 }
525 Operator = FnDecl;
526 return false;
527 }
528
529 case OR_No_Viable_Function:
530 if (AllowMissing)
531 return false;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000532 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +0000533 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000534 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
535 return true;
536
537 case OR_Ambiguous:
Sebastian Redlec5f3262008-12-04 22:20:51 +0000538 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl3b7ec4b2009-02-09 18:24:27 +0000539 << Name << Range;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000540 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
541 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +0000542
543 case OR_Deleted:
544 Diag(StartLoc, diag::err_ovl_deleted_call)
545 << Best->Function->isDeleted()
546 << Name << Range;
547 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
548 return true;
Sebastian Redlec5f3262008-12-04 22:20:51 +0000549 }
550 assert(false && "Unreachable, bad result from BestViableFunction");
551 return true;
552}
553
554
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000555/// DeclareGlobalNewDelete - Declare the global forms of operator new and
556/// delete. These are:
557/// @code
558/// void* operator new(std::size_t) throw(std::bad_alloc);
559/// void* operator new[](std::size_t) throw(std::bad_alloc);
560/// void operator delete(void *) throw();
561/// void operator delete[](void *) throw();
562/// @endcode
563/// Note that the placement and nothrow forms of new are *not* implicitly
564/// declared. Their use requires including \<new\>.
565void Sema::DeclareGlobalNewDelete()
566{
567 if (GlobalNewDeleteDeclared)
568 return;
569 GlobalNewDeleteDeclared = true;
570
571 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
572 QualType SizeT = Context.getSizeType();
573
574 // FIXME: Exception specifications are not added.
575 DeclareGlobalAllocationFunction(
576 Context.DeclarationNames.getCXXOperatorName(OO_New),
577 VoidPtr, SizeT);
578 DeclareGlobalAllocationFunction(
579 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
580 VoidPtr, SizeT);
581 DeclareGlobalAllocationFunction(
582 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
583 Context.VoidTy, VoidPtr);
584 DeclareGlobalAllocationFunction(
585 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
586 Context.VoidTy, VoidPtr);
587}
588
589/// DeclareGlobalAllocationFunction - Declares a single implicit global
590/// allocation function if it doesn't already exist.
591void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
592 QualType Return, QualType Argument)
593{
594 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
595
596 // Check if this function is already declared.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000597 {
Douglas Gregor7c865852008-12-23 22:05:29 +0000598 DeclContext::lookup_iterator Alloc, AllocEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000599 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000600 Alloc != AllocEnd; ++Alloc) {
601 // FIXME: Do we need to check for default arguments here?
602 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
603 if (Func->getNumParams() == 1 &&
Ted Kremenek0c97e042009-02-07 01:47:29 +0000604 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000605 return;
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000606 }
607 }
608
609 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
610 FunctionDecl *Alloc =
611 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000612 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000613 SourceLocation());
614 Alloc->setImplicit();
615 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000616 0, Argument, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000617 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000618
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000619 // FIXME: Also add this declaration to the IdentifierResolver, but
620 // make sure it is at the end of the chain to coincide with the
621 // global scope.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000622 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000623}
624
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000625/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
626/// @code ::delete ptr; @endcode
627/// or
628/// @code delete [] ptr; @endcode
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000629Action::OwningExprResult
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000630Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000631 bool ArrayForm, ExprArg Operand)
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000632{
633 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
634 // having a single conversion function to a pointer type. The result has
635 // type void."
636 // DR599 amends "pointer type" to "pointer to object type" in both cases.
637
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000638 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000639 if (!Ex->isTypeDependent()) {
640 QualType Type = Ex->getType();
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000641
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000642 if (Type->isRecordType()) {
643 // FIXME: Find that one conversion function and amend the type.
644 }
645
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000646 if (!Type->isPointerType())
647 return ExprError(Diag(StartLoc, diag::err_delete_operand)
648 << Type << Ex->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000649
650 QualType Pointee = Type->getAsPointerType()->getPointeeType();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000651 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000652 return ExprError(Diag(StartLoc, diag::err_delete_operand)
653 << Type << Ex->getSourceRange());
Douglas Gregorcde3a2d2009-03-24 20:13:58 +0000654 else if (!Pointee->isDependentType() &&
655 RequireCompleteType(StartLoc, Pointee,
656 diag::warn_delete_incomplete,
657 Ex->getSourceRange()))
658 return ExprError();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +0000659
660 // FIXME: Look up the correct operator delete overload and pass a pointer
661 // along.
662 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000663 }
664
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000665 Operand.release();
666 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
667 0, Ex, StartLoc));
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000668}
669
670
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000671/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
672/// C++ if/switch/while/for statement.
673/// e.g: "if (int x = f()) {...}"
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000674Action::OwningExprResult
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000675Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
676 Declarator &D,
677 SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000678 ExprArg AssignExprVal) {
679 assert(AssignExprVal.get() && "Null assignment expression");
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000680
681 // C++ 6.4p2:
682 // The declarator shall not specify a function or an array.
683 // The type-specifier-seq shall not contain typedef and shall not declare a
684 // new class or enumeration.
685
686 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
687 "Parser allowed 'typedef' as storage class of condition decl.");
688
689 QualType Ty = GetTypeForDeclarator(D, S);
690
691 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
692 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
693 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000694 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
695 << SourceRange(StartLoc, EqualLoc));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000696 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattner9d2cf082008-11-19 05:27:50 +0000697 Diag(StartLoc, diag::err_invalid_use_of_array_type)
698 << SourceRange(StartLoc, EqualLoc);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000699 } else if (const RecordType *RT = Ty->getAsRecordType()) {
700 RecordDecl *RD = RT->getDecl();
701 // The type-specifier-seq shall not declare a new class...
Chris Lattner5261d0c2009-03-28 19:18:32 +0000702 if (RD->isDefinition() &&
703 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000704 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
705 } else if (const EnumType *ET = Ty->getAsEnumType()) {
706 EnumDecl *ED = ET->getDecl();
707 // ...or enumeration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000708 if (ED->isDefinition() &&
709 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000710 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
711 }
712
Chris Lattner5261d0c2009-03-28 19:18:32 +0000713 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000714 if (!Dcl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000715 return ExprError();
716 AddInitializerToDecl(Dcl, move(AssignExprVal));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000717
Douglas Gregor48840c72008-12-10 23:01:14 +0000718 // Mark this variable as one that is declared within a conditional.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000719 // We know that the decl had to be a VarDecl because that is the only type of
720 // decl that can be assigned and the grammar requires an '='.
721 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
722 VD->setDeclaredInCondition(true);
723 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000724}
725
726/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
727bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
728 // C++ 6.4p4:
729 // The value of a condition that is an initialized declaration in a statement
730 // other than a switch statement is the value of the declared variable
731 // implicitly converted to type bool. If that conversion is ill-formed, the
732 // program is ill-formed.
733 // The value of a condition that is an expression is the value of the
734 // expression, implicitly converted to bool.
735 //
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000736 return PerformContextuallyConvertToBool(CondExpr);
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000737}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000738
739/// Helper function to determine whether this is the (deprecated) C++
740/// conversion from a string literal to a pointer to non-const char or
741/// non-const wchar_t (for narrow and wide string literals,
742/// respectively).
743bool
744Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
745 // Look inside the implicit cast, if it exists.
746 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
747 From = Cast->getSubExpr();
748
749 // A string literal (2.13.4) that is not a wide string literal can
750 // be converted to an rvalue of type "pointer to char"; a wide
751 // string literal can be converted to an rvalue of type "pointer
752 // to wchar_t" (C++ 4.2p2).
753 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
754 if (const PointerType *ToPtrType = ToType->getAsPointerType())
755 if (const BuiltinType *ToPointeeType
756 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
757 // This conversion is considered only when there is an
758 // explicit appropriate pointer target type (C++ 4.2p2).
759 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
760 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
761 (!StrLit->isWide() &&
762 (ToPointeeType->getKind() == BuiltinType::Char_U ||
763 ToPointeeType->getKind() == BuiltinType::Char_S))))
764 return true;
765 }
766
767 return false;
768}
Douglas Gregorbb461502008-10-24 04:54:22 +0000769
770/// PerformImplicitConversion - Perform an implicit conversion of the
771/// expression From to the type ToType. Returns true if there was an
772/// error, false otherwise. The expression From is replaced with the
Douglas Gregor6fd35572008-12-19 17:40:08 +0000773/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000774/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redla55834a2009-04-12 17:16:29 +0000775/// explicit user-defined conversions are permitted. @p Elidable should be true
776/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
777/// resolution works differently in that case.
778bool
Douglas Gregor6fd35572008-12-19 17:40:08 +0000779Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +0000780 const char *Flavor, bool AllowExplicit,
781 bool Elidable)
Douglas Gregorbb461502008-10-24 04:54:22 +0000782{
Sebastian Redla55834a2009-04-12 17:16:29 +0000783 ImplicitConversionSequence ICS;
784 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
785 if (Elidable && getLangOptions().CPlusPlus0x) {
786 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
787 AllowExplicit, /*ForceRValue*/true);
788 }
789 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
790 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
791 }
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000792 return PerformImplicitConversion(From, ToType, ICS, Flavor);
793}
794
795/// PerformImplicitConversion - Perform an implicit conversion of the
796/// expression From to the type ToType using the pre-computed implicit
797/// conversion sequence ICS. Returns true if there was an error, false
798/// otherwise. The expression From is replaced with the converted
799/// expression. Flavor is the kind of conversion we're performing,
800/// used in the error message.
801bool
802Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
803 const ImplicitConversionSequence &ICS,
804 const char* Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000805 switch (ICS.ConversionKind) {
806 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000807 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregorbb461502008-10-24 04:54:22 +0000808 return true;
809 break;
810
811 case ImplicitConversionSequence::UserDefinedConversion:
812 // FIXME: This is, of course, wrong. We'll need to actually call
813 // the constructor or conversion operator, and then cope with the
814 // standard conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000815 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000816 ToType->isLValueReferenceType());
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000817 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000818
819 case ImplicitConversionSequence::EllipsisConversion:
820 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000821 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +0000822
823 case ImplicitConversionSequence::BadConversion:
824 return true;
825 }
826
827 // Everything went well.
828 return false;
829}
830
831/// PerformImplicitConversion - Perform an implicit conversion of the
832/// expression From to the type ToType by following the standard
833/// conversion sequence SCS. Returns true if there was an error, false
834/// otherwise. The expression From is replaced with the converted
Douglas Gregor6fd35572008-12-19 17:40:08 +0000835/// expression. Flavor is the context in which we're performing this
836/// conversion, for use in error messages.
Douglas Gregorbb461502008-10-24 04:54:22 +0000837bool
838Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000839 const StandardConversionSequence& SCS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000840 const char *Flavor) {
Douglas Gregorbb461502008-10-24 04:54:22 +0000841 // Overall FIXME: we are recomputing too many types here and doing
842 // far too much extra work. What this means is that we need to keep
843 // track of more information that is computed when we try the
844 // implicit conversion initially, so that we don't need to recompute
845 // anything here.
846 QualType FromType = From->getType();
847
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000848 if (SCS.CopyConstructor) {
849 // FIXME: Create a temporary object by calling the copy
850 // constructor.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000851 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000852 ToType->isLValueReferenceType());
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000853 return false;
854 }
855
Douglas Gregorbb461502008-10-24 04:54:22 +0000856 // Perform the first implicit conversion.
857 switch (SCS.First) {
858 case ICK_Identity:
859 case ICK_Lvalue_To_Rvalue:
860 // Nothing to do.
861 break;
862
863 case ICK_Array_To_Pointer:
Douglas Gregoraa57e862009-02-18 21:56:37 +0000864 FromType = Context.getArrayDecayedType(FromType);
865 ImpCastExprToType(From, FromType);
866 break;
867
868 case ICK_Function_To_Pointer:
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000869 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +0000870 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
871 if (!Fn)
872 return true;
873
Douglas Gregoraa57e862009-02-18 21:56:37 +0000874 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
875 return true;
876
Douglas Gregor45014fd2008-11-10 20:40:00 +0000877 FixOverloadedFunctionReference(From, Fn);
878 FromType = From->getType();
Douglas Gregor45014fd2008-11-10 20:40:00 +0000879 }
Douglas Gregorbb461502008-10-24 04:54:22 +0000880 FromType = Context.getPointerType(FromType);
881 ImpCastExprToType(From, FromType);
882 break;
883
884 default:
885 assert(false && "Improper first standard conversion");
886 break;
887 }
888
889 // Perform the second implicit conversion
890 switch (SCS.Second) {
891 case ICK_Identity:
892 // Nothing to do.
893 break;
894
895 case ICK_Integral_Promotion:
896 case ICK_Floating_Promotion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000897 case ICK_Complex_Promotion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000898 case ICK_Integral_Conversion:
899 case ICK_Floating_Conversion:
Douglas Gregore819caf2009-02-12 00:15:05 +0000900 case ICK_Complex_Conversion:
Douglas Gregorbb461502008-10-24 04:54:22 +0000901 case ICK_Floating_Integral:
Douglas Gregore819caf2009-02-12 00:15:05 +0000902 case ICK_Complex_Real:
Douglas Gregorfcb19192009-02-11 23:02:49 +0000903 case ICK_Compatible_Conversion:
904 // FIXME: Go deeper to get the unqualified type!
Douglas Gregorbb461502008-10-24 04:54:22 +0000905 FromType = ToType.getUnqualifiedType();
906 ImpCastExprToType(From, FromType);
907 break;
908
909 case ICK_Pointer_Conversion:
Douglas Gregor6fd35572008-12-19 17:40:08 +0000910 if (SCS.IncompatibleObjC) {
911 // Diagnose incompatible Objective-C conversions
912 Diag(From->getSourceRange().getBegin(),
913 diag::ext_typecheck_convert_incompatible_pointer)
914 << From->getType() << ToType << Flavor
915 << From->getSourceRange();
916 }
917
Douglas Gregorbb461502008-10-24 04:54:22 +0000918 if (CheckPointerConversion(From, ToType))
919 return true;
920 ImpCastExprToType(From, ToType);
921 break;
922
923 case ICK_Pointer_Member:
Sebastian Redlba387562009-01-25 19:43:20 +0000924 if (CheckMemberPointerConversion(From, ToType))
925 return true;
926 ImpCastExprToType(From, ToType);
Douglas Gregorbb461502008-10-24 04:54:22 +0000927 break;
928
929 case ICK_Boolean_Conversion:
930 FromType = Context.BoolTy;
931 ImpCastExprToType(From, FromType);
932 break;
933
934 default:
935 assert(false && "Improper second standard conversion");
936 break;
937 }
938
939 switch (SCS.Third) {
940 case ICK_Identity:
941 // Nothing to do.
942 break;
943
944 case ICK_Qualification:
Sebastian Redlce6fff02009-03-16 23:22:08 +0000945 // FIXME: Not sure about lvalue vs rvalue here in the presence of
946 // rvalue references.
Douglas Gregor5ac8ffa2009-01-16 19:38:23 +0000947 ImpCastExprToType(From, ToType.getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +0000948 ToType->isLValueReferenceType());
Douglas Gregorbb461502008-10-24 04:54:22 +0000949 break;
950
951 default:
952 assert(false && "Improper second standard conversion");
953 break;
954 }
955
956 return false;
957}
958
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000959Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
960 SourceLocation KWLoc,
961 SourceLocation LParen,
962 TypeTy *Ty,
963 SourceLocation RParen) {
964 // FIXME: Some of the type traits have requirements. Interestingly, only the
965 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
966 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
967 // type is indeed a POD.
968
969 // There is no point in eagerly computing the value. The traits are designed
970 // to be used from type trait templates, so Ty will be a template parameter
971 // 99% of the time.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000972 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000973 QualType::getFromOpaquePtr(Ty),
974 RParen, Context.BoolTy));
975}
Sebastian Redlaa4c3732009-02-07 20:10:22 +0000976
977QualType Sema::CheckPointerToMemberOperands(
978 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
979{
980 const char *OpSpelling = isIndirect ? "->*" : ".*";
981 // C++ 5.5p2
982 // The binary operator .* [p3: ->*] binds its second operand, which shall
983 // be of type "pointer to member of T" (where T is a completely-defined
984 // class type) [...]
985 QualType RType = rex->getType();
986 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
Douglas Gregor05e28f62009-03-24 19:52:54 +0000987 if (!MemPtr) {
Sebastian Redlaa4c3732009-02-07 20:10:22 +0000988 Diag(Loc, diag::err_bad_memptr_rhs)
989 << OpSpelling << RType << rex->getSourceRange();
990 return QualType();
Douglas Gregor05e28f62009-03-24 19:52:54 +0000991 } else if (RequireCompleteType(Loc, QualType(MemPtr->getClass(), 0),
992 diag::err_memptr_rhs_incomplete,
993 rex->getSourceRange()))
994 return QualType();
995
Sebastian Redlaa4c3732009-02-07 20:10:22 +0000996 QualType Class(MemPtr->getClass(), 0);
997
998 // C++ 5.5p2
999 // [...] to its first operand, which shall be of class T or of a class of
1000 // which T is an unambiguous and accessible base class. [p3: a pointer to
1001 // such a class]
1002 QualType LType = lex->getType();
1003 if (isIndirect) {
1004 if (const PointerType *Ptr = LType->getAsPointerType())
1005 LType = Ptr->getPointeeType().getNonReferenceType();
1006 else {
1007 Diag(Loc, diag::err_bad_memptr_lhs)
1008 << OpSpelling << 1 << LType << lex->getSourceRange();
1009 return QualType();
1010 }
1011 }
1012
1013 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1014 Context.getCanonicalType(LType).getUnqualifiedType()) {
1015 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1016 /*DetectVirtual=*/false);
1017 // FIXME: Would it be useful to print full ambiguity paths,
1018 // or is that overkill?
1019 if (!IsDerivedFrom(LType, Class, Paths) ||
1020 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1021 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1022 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1023 return QualType();
1024 }
1025 }
1026
1027 // C++ 5.5p2
1028 // The result is an object or a function of the type specified by the
1029 // second operand.
1030 // The cv qualifiers are the union of those in the pointer and the left side,
1031 // in accordance with 5.5p5 and 5.2.5.
1032 // FIXME: This returns a dereferenced member function pointer as a normal
1033 // function type. However, the only operation valid on such functions is
1034 // calling them. There's also a GCC extension to get a function pointer to
1035 // the thing, which is another complication, because this type - unlike the
1036 // type that is the result of this expression - takes the class as the first
1037 // argument.
1038 // We probably need a "MemberFunctionClosureType" or something like that.
1039 QualType Result = MemPtr->getPointeeType();
1040 if (LType.isConstQualified())
1041 Result.addConst();
1042 if (LType.isVolatileQualified())
1043 Result.addVolatile();
1044 return Result;
1045}
Sebastian Redlbd261962009-04-16 17:51:27 +00001046
1047/// \brief Get the target type of a standard or user-defined conversion.
1048static QualType TargetType(const ImplicitConversionSequence &ICS) {
1049 assert((ICS.ConversionKind ==
1050 ImplicitConversionSequence::StandardConversion ||
1051 ICS.ConversionKind ==
1052 ImplicitConversionSequence::UserDefinedConversion) &&
1053 "function only valid for standard or user-defined conversions");
1054 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1055 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1056 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1057}
1058
1059/// \brief Try to convert a type to another according to C++0x 5.16p3.
1060///
1061/// This is part of the parameter validation for the ? operator. If either
1062/// value operand is a class type, the two operands are attempted to be
1063/// converted to each other. This function does the conversion in one direction.
1064/// It emits a diagnostic and returns true only if it finds an ambiguous
1065/// conversion.
1066static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1067 SourceLocation QuestionLoc,
1068 ImplicitConversionSequence &ICS)
1069{
1070 // C++0x 5.16p3
1071 // The process for determining whether an operand expression E1 of type T1
1072 // can be converted to match an operand expression E2 of type T2 is defined
1073 // as follows:
1074 // -- If E2 is an lvalue:
1075 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1076 // E1 can be converted to match E2 if E1 can be implicitly converted to
1077 // type "lvalue reference to T2", subject to the constraint that in the
1078 // conversion the reference must bind directly to E1.
1079 if (!Self.CheckReferenceInit(From,
1080 Self.Context.getLValueReferenceType(To->getType()),
1081 &ICS))
1082 {
1083 assert((ICS.ConversionKind ==
1084 ImplicitConversionSequence::StandardConversion ||
1085 ICS.ConversionKind ==
1086 ImplicitConversionSequence::UserDefinedConversion) &&
1087 "expected a definite conversion");
1088 bool DirectBinding =
1089 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1090 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1091 if (DirectBinding)
1092 return false;
1093 }
1094 }
1095 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1096 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1097 // -- if E1 and E2 have class type, and the underlying class types are
1098 // the same or one is a base class of the other:
1099 QualType FTy = From->getType();
1100 QualType TTy = To->getType();
1101 const RecordType *FRec = FTy->getAsRecordType();
1102 const RecordType *TRec = TTy->getAsRecordType();
1103 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1104 if (FRec && TRec && (FRec == TRec ||
1105 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1106 // E1 can be converted to match E2 if the class of T2 is the
1107 // same type as, or a base class of, the class of T1, and
1108 // [cv2 > cv1].
1109 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1110 // Could still fail if there's no copy constructor.
1111 // FIXME: Is this a hard error then, or just a conversion failure? The
1112 // standard doesn't say.
1113 ICS = Self.TryCopyInitialization(From, TTy);
1114 }
1115 } else {
1116 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1117 // implicitly converted to the type that expression E2 would have
1118 // if E2 were converted to an rvalue.
1119 // First find the decayed type.
1120 if (TTy->isFunctionType())
1121 TTy = Self.Context.getPointerType(TTy);
1122 else if(TTy->isArrayType())
1123 TTy = Self.Context.getArrayDecayedType(TTy);
1124
1125 // Now try the implicit conversion.
1126 // FIXME: This doesn't detect ambiguities.
1127 ICS = Self.TryImplicitConversion(From, TTy);
1128 }
1129 return false;
1130}
1131
1132/// \brief Try to find a common type for two according to C++0x 5.16p5.
1133///
1134/// This is part of the parameter validation for the ? operator. If either
1135/// value operand is a class type, overload resolution is used to find a
1136/// conversion to a common type.
1137static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1138 SourceLocation Loc) {
1139 Expr *Args[2] = { LHS, RHS };
1140 OverloadCandidateSet CandidateSet;
1141 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1142
1143 OverloadCandidateSet::iterator Best;
1144 switch (Self.BestViableFunction(CandidateSet, Best)) {
1145 case Sema::OR_Success:
1146 // We found a match. Perform the conversions on the arguments and move on.
1147 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1148 Best->Conversions[0], "converting") ||
1149 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1150 Best->Conversions[1], "converting"))
1151 break;
1152 return false;
1153
1154 case Sema::OR_No_Viable_Function:
1155 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1156 << LHS->getType() << RHS->getType()
1157 << LHS->getSourceRange() << RHS->getSourceRange();
1158 return true;
1159
1160 case Sema::OR_Ambiguous:
1161 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1162 << LHS->getType() << RHS->getType()
1163 << LHS->getSourceRange() << RHS->getSourceRange();
1164 // FIXME: Print the possible common types by printing the return types
1165 // of the viable candidates.
1166 break;
1167
1168 case Sema::OR_Deleted:
1169 assert(false && "Conditional operator has only built-in overloads");
1170 break;
1171 }
1172 return true;
1173}
1174
Sebastian Redld3169132009-04-17 16:30:52 +00001175/// \brief Perform an "extended" implicit conversion as returned by
1176/// TryClassUnification.
1177///
1178/// TryClassUnification generates ICSs that include reference bindings.
1179/// PerformImplicitConversion is not suitable for this; it chokes if the
1180/// second part of a standard conversion is ICK_DerivedToBase. This function
1181/// handles the reference binding specially.
1182static bool ConvertForConditional(Sema &Self, Expr *&E,
1183 const ImplicitConversionSequence &ICS)
1184{
1185 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1186 ICS.Standard.ReferenceBinding) {
1187 assert(ICS.Standard.DirectBinding &&
1188 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001189 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1190 // redoing all the work.
1191 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1192 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001193 }
1194 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1195 ICS.UserDefined.After.ReferenceBinding) {
1196 assert(ICS.UserDefined.After.DirectBinding &&
1197 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf6b86182009-04-26 11:21:02 +00001198 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1199 TargetType(ICS)));
Sebastian Redld3169132009-04-17 16:30:52 +00001200 }
1201 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1202 return true;
1203 return false;
1204}
1205
Sebastian Redlbd261962009-04-16 17:51:27 +00001206/// \brief Check the operands of ?: under C++ semantics.
1207///
1208/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1209/// extension. In this case, LHS == Cond. (But they're not aliases.)
1210QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1211 SourceLocation QuestionLoc) {
1212 // FIXME: Handle C99's complex types, vector types, block pointers and
1213 // Obj-C++ interface pointers.
1214
1215 // C++0x 5.16p1
1216 // The first expression is contextually converted to bool.
1217 if (!Cond->isTypeDependent()) {
1218 if (CheckCXXBooleanCondition(Cond))
1219 return QualType();
1220 }
1221
1222 // Either of the arguments dependent?
1223 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1224 return Context.DependentTy;
1225
1226 // C++0x 5.16p2
1227 // If either the second or the third operand has type (cv) void, ...
1228 QualType LTy = LHS->getType();
1229 QualType RTy = RHS->getType();
1230 bool LVoid = LTy->isVoidType();
1231 bool RVoid = RTy->isVoidType();
1232 if (LVoid || RVoid) {
1233 // ... then the [l2r] conversions are performed on the second and third
1234 // operands ...
1235 DefaultFunctionArrayConversion(LHS);
1236 DefaultFunctionArrayConversion(RHS);
1237 LTy = LHS->getType();
1238 RTy = RHS->getType();
1239
1240 // ... and one of the following shall hold:
1241 // -- The second or the third operand (but not both) is a throw-
1242 // expression; the result is of the type of the other and is an rvalue.
1243 bool LThrow = isa<CXXThrowExpr>(LHS);
1244 bool RThrow = isa<CXXThrowExpr>(RHS);
1245 if (LThrow && !RThrow)
1246 return RTy;
1247 if (RThrow && !LThrow)
1248 return LTy;
1249
1250 // -- Both the second and third operands have type void; the result is of
1251 // type void and is an rvalue.
1252 if (LVoid && RVoid)
1253 return Context.VoidTy;
1254
1255 // Neither holds, error.
1256 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1257 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1258 << LHS->getSourceRange() << RHS->getSourceRange();
1259 return QualType();
1260 }
1261
1262 // Neither is void.
1263
1264 // C++0x 5.16p3
1265 // Otherwise, if the second and third operand have different types, and
1266 // either has (cv) class type, and attempt is made to convert each of those
1267 // operands to the other.
1268 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1269 (LTy->isRecordType() || RTy->isRecordType())) {
1270 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1271 // These return true if a single direction is already ambiguous.
1272 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1273 return QualType();
1274 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1275 return QualType();
1276
1277 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1278 ImplicitConversionSequence::BadConversion;
1279 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1280 ImplicitConversionSequence::BadConversion;
1281 // If both can be converted, [...] the program is ill-formed.
1282 if (HaveL2R && HaveR2L) {
1283 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1284 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1285 return QualType();
1286 }
1287
1288 // If exactly one conversion is possible, that conversion is applied to
1289 // the chosen operand and the converted operands are used in place of the
1290 // original operands for the remainder of this section.
1291 if (HaveL2R) {
Sebastian Redld3169132009-04-17 16:30:52 +00001292 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redlbd261962009-04-16 17:51:27 +00001293 return QualType();
1294 LTy = LHS->getType();
1295 } else if (HaveR2L) {
Sebastian Redld3169132009-04-17 16:30:52 +00001296 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redlbd261962009-04-16 17:51:27 +00001297 return QualType();
1298 RTy = RHS->getType();
1299 }
1300 }
1301
1302 // C++0x 5.16p4
1303 // If the second and third operands are lvalues and have the same type,
1304 // the result is of that type [...]
1305 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1306 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1307 RHS->isLvalue(Context) == Expr::LV_Valid)
1308 return LTy;
1309
1310 // C++0x 5.16p5
1311 // Otherwise, the result is an rvalue. If the second and third operands
1312 // do not have the same type, and either has (cv) class type, ...
1313 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1314 // ... overload resolution is used to determine the conversions (if any)
1315 // to be applied to the operands. If the overload resolution fails, the
1316 // program is ill-formed.
1317 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1318 return QualType();
1319 }
1320
1321 // C++0x 5.16p6
1322 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1323 // conversions are performed on the second and third operands.
1324 DefaultFunctionArrayConversion(LHS);
1325 DefaultFunctionArrayConversion(RHS);
1326 LTy = LHS->getType();
1327 RTy = RHS->getType();
1328
1329 // After those conversions, one of the following shall hold:
1330 // -- The second and third operands have the same type; the result
1331 // is of that type.
1332 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1333 return LTy;
1334
1335 // -- The second and third operands have arithmetic or enumeration type;
1336 // the usual arithmetic conversions are performed to bring them to a
1337 // common type, and the result is of that type.
1338 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1339 UsualArithmeticConversions(LHS, RHS);
1340 return LHS->getType();
1341 }
1342
1343 // -- The second and third operands have pointer type, or one has pointer
1344 // type and the other is a null pointer constant; pointer conversions
1345 // and qualification conversions are performed to bring them to their
1346 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl42b81a22009-04-19 19:26:31 +00001347 QualType Composite = FindCompositePointerType(LHS, RHS);
1348 if (!Composite.isNull())
1349 return Composite;
Sebastian Redlbd261962009-04-16 17:51:27 +00001350
Sebastian Redl5b3fcf82009-04-19 21:15:26 +00001351 // Fourth bullet is same for pointers-to-member. However, the possible
1352 // conversions are far more limited: we have null-to-pointer, upcast of
1353 // containing class, and second-level cv-ness.
1354 // cv-ness is not a union, but must match one of the two operands. (Which,
1355 // frankly, is stupid.)
1356 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1357 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1358 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1359 ImpCastExprToType(RHS, LTy);
1360 return LTy;
1361 }
1362 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1363 ImpCastExprToType(LHS, RTy);
1364 return RTy;
1365 }
1366 if (LMemPtr && RMemPtr) {
1367 QualType LPointee = LMemPtr->getPointeeType();
1368 QualType RPointee = RMemPtr->getPointeeType();
1369 // First, we check that the unqualified pointee type is the same. If it's
1370 // not, there's no conversion that will unify the two pointers.
1371 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1372 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1373 // Second, we take the greater of the two cv qualifications. If neither
1374 // is greater than the other, the conversion is not possible.
1375 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1376 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1377 // Third, we check if either of the container classes is derived from
1378 // the other.
1379 QualType LContainer(LMemPtr->getClass(), 0);
1380 QualType RContainer(RMemPtr->getClass(), 0);
1381 QualType MoreDerived;
1382 if (Context.getCanonicalType(LContainer) ==
1383 Context.getCanonicalType(RContainer))
1384 MoreDerived = LContainer;
1385 else if (IsDerivedFrom(LContainer, RContainer))
1386 MoreDerived = LContainer;
1387 else if (IsDerivedFrom(RContainer, LContainer))
1388 MoreDerived = RContainer;
1389
1390 if (!MoreDerived.isNull()) {
1391 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1392 // We don't use ImpCastExprToType here because this could still fail
1393 // for ambiguous or inaccessible conversions.
1394 QualType Common = Context.getMemberPointerType(
1395 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1396 if (PerformImplicitConversion(LHS, Common, "converting"))
1397 return QualType();
1398 if (PerformImplicitConversion(RHS, Common, "converting"))
1399 return QualType();
1400 return Common;
1401 }
1402 }
1403 }
1404 }
1405
Sebastian Redlbd261962009-04-16 17:51:27 +00001406 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1407 << LHS->getType() << RHS->getType()
1408 << LHS->getSourceRange() << RHS->getSourceRange();
1409 return QualType();
1410}
Sebastian Redl42b81a22009-04-19 19:26:31 +00001411
1412/// \brief Find a merged pointer type and convert the two expressions to it.
1413///
1414/// This finds the composite pointer type for @p E1 and @p E2 according to
1415/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1416/// It does not emit diagnostics.
1417QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1418 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1419 QualType T1 = E1->getType(), T2 = E2->getType();
1420 if(!T1->isPointerType() && !T2->isPointerType())
1421 return QualType();
1422
1423 // C++0x 5.9p2
1424 // Pointer conversions and qualification conversions are performed on
1425 // pointer operands to bring them to their composite pointer type. If
1426 // one operand is a null pointer constant, the composite pointer type is
1427 // the type of the other operand.
1428 if (E1->isNullPointerConstant(Context)) {
1429 ImpCastExprToType(E1, T2);
1430 return T2;
1431 }
1432 if (E2->isNullPointerConstant(Context)) {
1433 ImpCastExprToType(E2, T1);
1434 return T1;
1435 }
1436 // Now both have to be pointers.
1437 if(!T1->isPointerType() || !T2->isPointerType())
1438 return QualType();
1439
1440 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1441 // the other has type "pointer to cv2 T" and the composite pointer type is
1442 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1443 // Otherwise, the composite pointer type is a pointer type similar to the
1444 // type of one of the operands, with a cv-qualification signature that is
1445 // the union of the cv-qualification signatures of the operand types.
1446 // In practice, the first part here is redundant; it's subsumed by the second.
1447 // What we do here is, we build the two possible composite types, and try the
1448 // conversions in both directions. If only one works, or if the two composite
1449 // types are the same, we have succeeded.
1450 llvm::SmallVector<unsigned, 4> QualifierUnion;
1451 QualType Composite1 = T1, Composite2 = T2;
1452 const PointerType *Ptr1, *Ptr2;
1453 while ((Ptr1 = Composite1->getAsPointerType()) &&
1454 (Ptr2 = Composite2->getAsPointerType())) {
1455 Composite1 = Ptr1->getPointeeType();
1456 Composite2 = Ptr2->getPointeeType();
1457 QualifierUnion.push_back(
1458 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1459 }
1460 // Rewrap the composites as pointers with the union CVRs.
1461 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1462 E = QualifierUnion.end(); I != E; ++I) {
1463 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1464 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1465 }
1466
1467 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1468 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1469 ImplicitConversionSequence E1ToC2, E2ToC2;
1470 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1471 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1472 if (Context.getCanonicalType(Composite1) !=
1473 Context.getCanonicalType(Composite2)) {
1474 E1ToC2 = TryImplicitConversion(E1, Composite2);
1475 E2ToC2 = TryImplicitConversion(E2, Composite2);
1476 }
1477
1478 bool ToC1Viable = E1ToC1.ConversionKind !=
1479 ImplicitConversionSequence::BadConversion
1480 && E2ToC1.ConversionKind !=
1481 ImplicitConversionSequence::BadConversion;
1482 bool ToC2Viable = E1ToC2.ConversionKind !=
1483 ImplicitConversionSequence::BadConversion
1484 && E2ToC2.ConversionKind !=
1485 ImplicitConversionSequence::BadConversion;
1486 if (ToC1Viable && !ToC2Viable) {
1487 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1488 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1489 return Composite1;
1490 }
1491 if (ToC2Viable && !ToC1Viable) {
1492 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1493 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1494 return Composite2;
1495 }
1496 return QualType();
1497}