blob: ed6b67787a3828810443f12c39f2f5f63c03e278 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Steve Naroffaac94152007-08-25 14:02:58 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000023using namespace clang;
24
Sebastian Redlc4704762008-11-11 11:37:55 +000025/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redl6d4256c2009-03-15 17:47:39 +000026Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +000027Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
28 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor87f54062009-09-15 22:30:29 +000029 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000030 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +000031
32 if (isType)
33 // FIXME: Preserve type source info.
34 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
35
Chris Lattnerec7f7732008-11-20 05:51:55 +000036 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall9f3059a2009-10-09 21:13:30 +000037 LookupResult R;
38 LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
39 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc4704762008-11-11 11:37:55 +000040 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattnerec7f7732008-11-20 05:51:55 +000041 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +000042 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc4704762008-11-11 11:37:55 +000043
44 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
45
Douglas Gregor0b6a6242009-06-22 20:57:11 +000046 if (!isType) {
47 // C++0x [expr.typeid]p3:
Mike Stump11289f42009-09-09 15:08:12 +000048 // When typeid is applied to an expression other than an lvalue of a
49 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregor0b6a6242009-06-22 20:57:11 +000050 // operand.
Mike Stump11289f42009-09-09 15:08:12 +000051
Douglas Gregor0b6a6242009-06-22 20:57:11 +000052 // FIXME: if the type of the expression is a class type, the class
53 // shall be completely defined.
54 bool isUnevaluatedOperand = true;
55 Expr *E = static_cast<Expr *>(TyOrExpr);
56 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
57 QualType T = E->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +000058 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000059 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
60 if (RecordD->isPolymorphic())
61 isUnevaluatedOperand = false;
62 }
63 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Douglas Gregor0b6a6242009-06-22 20:57:11 +000065 // If this is an unevaluated operand, clear out the set of declaration
66 // references we have been computing.
67 if (isUnevaluatedOperand)
68 PotentiallyReferencedDeclStack.back().clear();
69 }
Mike Stump11289f42009-09-09 15:08:12 +000070
Sebastian Redl6d4256c2009-03-15 17:47:39 +000071 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
72 TypeInfoType.withConst(),
73 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc4704762008-11-11 11:37:55 +000074}
75
Steve Naroff66356bd2007-09-16 14:56:35 +000076/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +000077Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +000078Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +000079 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +000080 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +000081 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
82 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +000083}
Chris Lattnerb7e656b2008-02-26 00:51:44 +000084
Sebastian Redl576fd422009-05-10 18:38:11 +000085/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
86Action::OwningExprResult
87Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
88 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
89}
90
Chris Lattnerb7e656b2008-02-26 00:51:44 +000091/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +000092Action::OwningExprResult
93Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +000094 Expr *Ex = E.takeAs<Expr>();
95 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
96 return ExprError();
97 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
98}
99
100/// CheckCXXThrowOperand - Validate the operand of a throw.
101bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
102 // C++ [except.throw]p3:
103 // [...] adjusting the type from "array of T" or "function returning T"
104 // to "pointer to T" or "pointer to function returning T", [...]
105 DefaultFunctionArrayConversion(E);
106
107 // If the type of the exception would be an incomplete type or a pointer
108 // to an incomplete type other than (cv) void the program is ill-formed.
109 QualType Ty = E->getType();
110 int isPointer = 0;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000111 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000112 Ty = Ptr->getPointeeType();
113 isPointer = 1;
114 }
115 if (!isPointer || !Ty->isVoidType()) {
116 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000117 PDiag(isPointer ? diag::err_throw_incomplete_ptr
118 : diag::err_throw_incomplete)
119 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000120 return true;
121 }
122
123 // FIXME: Construct a temporary here.
124 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000125}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000126
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000127Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000128 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
129 /// is a non-lvalue expression whose value is the address of the object for
130 /// which the function is called.
131
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000132 if (!isa<FunctionDecl>(CurContext))
133 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000134
135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
136 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000137 return Owned(new (Context) CXXThisExpr(ThisLoc,
138 MD->getThisType(Context)));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000139
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000140 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000141}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000142
143/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
144/// Can be interpreted either as function-style casting ("int(x)")
145/// or class type construction ("ClassType(x,y,z)")
146/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000147Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000148Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
149 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000150 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000151 SourceLocation *CommaLocs,
152 SourceLocation RParenLoc) {
153 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000154 // FIXME: Preserve type source info.
155 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000156 unsigned NumExprs = exprs.size();
157 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000158 SourceLocation TyBeginLoc = TypeRange.getBegin();
159 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
160
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000161 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000162 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000163 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000164
165 return Owned(CXXUnresolvedConstructExpr::Create(Context,
166 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000167 LParenLoc,
168 Exprs, NumExprs,
169 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000170 }
171
Anders Carlsson55243162009-08-27 03:53:50 +0000172 if (Ty->isArrayType())
173 return ExprError(Diag(TyBeginLoc,
174 diag::err_value_init_for_array_type) << FullRange);
175 if (!Ty->isVoidType() &&
176 RequireCompleteType(TyBeginLoc, Ty,
177 PDiag(diag::err_invalid_incomplete_type_use)
178 << FullRange))
179 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000180
Anders Carlsson55243162009-08-27 03:53:50 +0000181 if (RequireNonAbstractType(TyBeginLoc, Ty,
182 diag::err_allocation_of_abstract_type))
183 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000184
185
Douglas Gregordd04d332009-01-16 18:33:17 +0000186 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000187 // If the expression list is a single expression, the type conversion
188 // expression is equivalent (in definedness, and if defined in meaning) to the
189 // corresponding cast expression.
190 //
191 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000192 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000193 CXXMethodDecl *Method = 0;
194 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
195 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000196 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000197
198 exprs.release();
199 if (Method) {
200 OwningExprResult CastArg
201 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
202 Kind, Method, Owned(Exprs[0]));
203 if (CastArg.isInvalid())
204 return ExprError();
205
206 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian8b899e42009-08-28 15:11:24 +0000207 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000208
209 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
210 Ty, TyBeginLoc, Kind,
211 Exprs[0], RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000212 }
213
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000214 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000215 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000216
Mike Stump11289f42009-09-09 15:08:12 +0000217 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000218 !Record->hasTrivialDestructor()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000219 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
220
Douglas Gregordd04d332009-01-16 18:33:17 +0000221 CXXConstructorDecl *Constructor
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000222 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregordd04d332009-01-16 18:33:17 +0000223 TypeRange.getBegin(),
224 SourceRange(TypeRange.getBegin(),
225 RParenLoc),
226 DeclarationName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000227 IK_Direct,
228 ConstructorArgs);
Douglas Gregordd04d332009-01-16 18:33:17 +0000229
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000230 if (!Constructor)
231 return ExprError();
232
Mike Stump11289f42009-09-09 15:08:12 +0000233 OwningExprResult Result =
234 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000235 move_arg(ConstructorArgs), RParenLoc);
Anders Carlsson574315a2009-08-27 05:08:22 +0000236 if (Result.isInvalid())
237 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlsson574315a2009-08-27 05:08:22 +0000239 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregordd04d332009-01-16 18:33:17 +0000240 }
241
242 // Fall through to value-initialize an object of class type that
243 // doesn't have a user-declared default constructor.
244 }
245
246 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000247 // If the expression list specifies more than a single value, the type shall
248 // be a class with a suitably declared constructor.
249 //
250 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000251 return ExprError(Diag(CommaLocs[0],
252 diag::err_builtin_func_cast_more_than_one_arg)
253 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000254
255 assert(NumExprs == 0 && "Expected 0 expressions");
Fariborz Jahanian11565482009-10-27 16:51:19 +0000256
257 if (const RecordType *Record = Ty->getAs<RecordType>()) {
258 if (!Record->getDecl()->isUnion()) {
259 // As clarified in C++ DR302, generate constructor for
260 // value-initialization cases, even if the implementation technique
261 // doesn't call the constructor at that point.
262 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
263 (void)PerformInitializationByConstructor(Ty, MultiExprArg(*this, 0, 0),
264 TypeRange.getBegin(),
265 TypeRange, DeclarationName(),
266 IK_Default, ConstructorArgs);
267 }
268 }
269
Douglas Gregordd04d332009-01-16 18:33:17 +0000270 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000271 // The expression T(), where T is a simple-type-specifier for a non-array
272 // complete object type or the (possibly cv-qualified) void type, creates an
273 // rvalue of the specified type, which is value-initialized.
274 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000275 exprs.release();
276 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000277}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000278
279
Sebastian Redlbd150f42008-11-21 19:14:01 +0000280/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
281/// @code new (memory) int[size][4] @endcode
282/// or
283/// @code ::new Foo(23, "hello") @endcode
284/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000285Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000286Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000287 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000288 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000289 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000290 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000291 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000292 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000293 // If the specified type is an array, unwrap it and save the expression.
294 if (D.getNumTypeObjects() > 0 &&
295 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
296 DeclaratorChunk &Chunk = D.getTypeObject(0);
297 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000298 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
299 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000300 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000301 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
302 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000303
304 if (ParenTypeId) {
305 // Can't have dynamic array size when the type-id is in parentheses.
306 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
307 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
308 !NumElts->isIntegerConstantExpr(Context)) {
309 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
310 << NumElts->getSourceRange();
311 return ExprError();
312 }
313 }
314
Sebastian Redl351bb782008-12-02 14:43:59 +0000315 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000316 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000317 }
318
Douglas Gregor73341c42009-09-11 00:18:58 +0000319 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000320 if (ArraySize) {
321 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000322 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
323 break;
324
325 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
326 if (Expr *NumElts = (Expr *)Array.NumElts) {
327 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
328 !NumElts->isIntegerConstantExpr(Context)) {
329 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
330 << NumElts->getSourceRange();
331 return ExprError();
332 }
333 }
334 }
335 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000336
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000337 //FIXME: Store DeclaratorInfo in CXXNew expression.
338 DeclaratorInfo *DInfo = 0;
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000339 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000340 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000341 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000342
Mike Stump11289f42009-09-09 15:08:12 +0000343 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000344 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000345 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000346 PlacementRParen,
347 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000348 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000349 D.getSourceRange().getBegin(),
350 D.getSourceRange(),
351 Owned(ArraySize),
352 ConstructorLParen,
353 move(ConstructorArgs),
354 ConstructorRParen);
355}
356
Mike Stump11289f42009-09-09 15:08:12 +0000357Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000358Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
359 SourceLocation PlacementLParen,
360 MultiExprArg PlacementArgs,
361 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000362 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000363 QualType AllocType,
364 SourceLocation TypeLoc,
365 SourceRange TypeRange,
366 ExprArg ArraySizeE,
367 SourceLocation ConstructorLParen,
368 MultiExprArg ConstructorArgs,
369 SourceLocation ConstructorRParen) {
370 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000371 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000372
Douglas Gregord0fefba2009-05-21 00:00:09 +0000373 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000374
375 // That every array dimension except the first is constant was already
376 // checked by the type check above.
Sebastian Redl351bb782008-12-02 14:43:59 +0000377
Sebastian Redlbd150f42008-11-21 19:14:01 +0000378 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
379 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000380 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000381 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000382 QualType SizeType = ArraySize->getType();
383 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000384 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
385 diag::err_array_size_not_integral)
386 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000387 // Let's see if this is a constant < 0. If so, we reject it out of hand.
388 // We don't care about special rules, so we tell the machinery it's not
389 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000390 if (!ArraySize->isValueDependent()) {
391 llvm::APSInt Value;
392 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
393 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000394 llvm::APInt::getNullValue(Value.getBitWidth()),
395 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000396 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
397 diag::err_typecheck_negative_array_size)
398 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000399 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000400 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000401
Eli Friedman06ed2a52009-10-20 08:27:19 +0000402 ImpCastExprToType(ArraySize, Context.getSizeType(),
403 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000404 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000405
Sebastian Redlbd150f42008-11-21 19:14:01 +0000406 FunctionDecl *OperatorNew = 0;
407 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000408 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
409 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000410
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000411 if (!AllocType->isDependentType() &&
412 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
413 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000414 SourceRange(PlacementLParen, PlacementRParen),
415 UseGlobal, AllocType, ArraySize, PlaceArgs,
416 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000417 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000418
419 bool Init = ConstructorLParen.isValid();
420 // --- Choosing a constructor ---
421 // C++ 5.3.4p15
422 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
423 // the object is not initialized. If the object, or any part of it, is
424 // const-qualified, it's an error.
425 // 2) If T is a POD and there's an empty initializer, the object is value-
426 // initialized.
427 // 3) If T is a POD and there's one initializer argument, the object is copy-
428 // constructed.
429 // 4) If T is a POD and there's more initializer arguments, it's an error.
430 // 5) If T is not a POD, the initializer arguments are used as constructor
431 // arguments.
432 //
433 // Or by the C++0x formulation:
434 // 1) If there's no initializer, the object is default-initialized according
435 // to C++0x rules.
436 // 2) Otherwise, the object is direct-initialized.
437 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000438 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redlfb23ddf2009-05-07 16:14:23 +0000439 const RecordType *RT;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000440 unsigned NumConsArgs = ConstructorArgs.size();
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000441
442 if (AllocType->isDependentType() ||
443 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000444 // Skip all the checks.
Mike Stump12b8ce12009-08-04 21:02:39 +0000445 } else if ((RT = AllocType->getAs<RecordType>()) &&
446 !AllocType->isAggregateType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000447 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
448
Sebastian Redlbd150f42008-11-21 19:14:01 +0000449 Constructor = PerformInitializationByConstructor(
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000450 AllocType, move(ConstructorArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000451 TypeLoc,
452 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000453 RT->getDecl()->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000454 NumConsArgs != 0 ? IK_Direct : IK_Default,
455 ConvertedConstructorArgs);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000456 if (!Constructor)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000457 return ExprError();
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000458
459 // Take the converted constructor arguments and use them for the new
460 // expression.
461 NumConsArgs = ConvertedConstructorArgs.size();
462 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000463 } else {
464 if (!Init) {
465 // FIXME: Check that no subpart is const.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000466 if (AllocType.isConstQualified())
467 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregord0fefba2009-05-21 00:00:09 +0000468 << TypeRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +0000469 } else if (NumConsArgs == 0) {
Fariborz Jahanian11565482009-10-27 16:51:19 +0000470 // Object is value-initialized.
471 if (const RecordType *Record = AllocType->getAs<RecordType>()) {
472 if (!Record->getDecl()->isUnion()) {
473 // As clarified in C++ DR302, generate constructor for
474 // value-initialization cases, even if the implementation technique
475 // doesn't call the constructor at that point.
476 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
477 (void)PerformInitializationByConstructor(AllocType,
478 MultiExprArg(*this, 0, 0),
479 TypeRange.getBegin(),
480 TypeRange, DeclarationName(),
481 IK_Default,
482 ConstructorArgs);
483 }
484 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000485 } else if (NumConsArgs == 1) {
486 // Object is direct-initialized.
Sebastian Redlfb23ddf2009-05-07 16:14:23 +0000487 // FIXME: What DeclarationName do we pass in here?
Sebastian Redl351bb782008-12-02 14:43:59 +0000488 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +0000489 DeclarationName() /*AllocType.getAsString()*/,
490 /*DirectInit=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000491 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000492 } else {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000493 return ExprError(Diag(StartLoc,
494 diag::err_builtin_direct_init_more_than_one_arg)
495 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000496 }
497 }
498
499 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000500
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000501 PlacementArgs.release();
502 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000503 ArraySizeE.release();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000504 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek5a201952009-02-07 01:47:29 +0000505 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000506 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump11289f42009-09-09 15:08:12 +0000507 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000508}
509
510/// CheckAllocatedType - Checks that a type is suitable as the allocated type
511/// in a new-expression.
512/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000513bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000514 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000515 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
516 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000517 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000518 return Diag(Loc, diag::err_bad_new_type)
519 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000520 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000521 return Diag(Loc, diag::err_bad_new_type)
522 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000523 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000524 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000525 PDiag(diag::err_new_incomplete_type)
526 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000527 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000528 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000529 diag::err_allocation_of_abstract_type))
530 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000531
Sebastian Redlbd150f42008-11-21 19:14:01 +0000532 return false;
533}
534
Sebastian Redlfaf68082008-12-03 20:26:15 +0000535/// FindAllocationFunctions - Finds the overloads of operator new and delete
536/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000537bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
538 bool UseGlobal, QualType AllocType,
539 bool IsArray, Expr **PlaceArgs,
540 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000541 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000542 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000543 // --- Choosing an allocation function ---
544 // C++ 5.3.4p8 - 14 & 18
545 // 1) If UseGlobal is true, only look in the global scope. Else, also look
546 // in the scope of the allocated class.
547 // 2) If an array size is given, look for operator new[], else look for
548 // operator new.
549 // 3) The first argument is always size_t. Append the arguments from the
550 // placement form.
551 // FIXME: Also find the appropriate delete operator.
552
553 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
554 // We don't care about the actual value of this argument.
555 // FIXME: Should the Sema create the expression and embed it in the syntax
556 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000557 IntegerLiteral Size(llvm::APInt::getNullValue(
558 Context.Target.getPointerWidth(0)),
559 Context.getSizeType(),
560 SourceLocation());
561 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000562 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
563
564 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
565 IsArray ? OO_Array_New : OO_New);
566 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000567 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000568 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl33a31012008-12-04 22:20:51 +0000569 // FIXME: We fail to find inherited overloads.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000570 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000571 AllocArgs.size(), Record, /*AllowMissing=*/true,
572 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000573 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000574 }
575 if (!OperatorNew) {
576 // Didn't find a member overload. Look for a global one.
577 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000578 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000579 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000580 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
581 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000582 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000583 }
584
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000585 // FindAllocationOverload can change the passed in arguments, so we need to
586 // copy them back.
587 if (NumPlaceArgs > 0)
588 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000589
Sebastian Redlfaf68082008-12-03 20:26:15 +0000590 return false;
591}
592
Sebastian Redl33a31012008-12-04 22:20:51 +0000593/// FindAllocationOverload - Find an fitting overload for the allocation
594/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000595bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
596 DeclarationName Name, Expr** Args,
597 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +0000598 bool AllowMissing, FunctionDecl *&Operator) {
John McCall9f3059a2009-10-09 21:13:30 +0000599 LookupResult R;
600 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
601 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000602 if (AllowMissing)
603 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +0000604 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000605 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000606 }
607
John McCall9f3059a2009-10-09 21:13:30 +0000608 // FIXME: handle ambiguity
609
Sebastian Redl33a31012008-12-04 22:20:51 +0000610 OverloadCandidateSet Candidates;
Douglas Gregor80a6cc52009-09-30 00:03:47 +0000611 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
612 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +0000613 // Even member operator new/delete are implicitly treated as
614 // static, so don't use AddMemberCandidate.
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000615 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor55297ac2008-12-23 00:26:44 +0000616 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
617 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000618 continue;
619 }
620
621 // FIXME: Handle function templates
Sebastian Redl33a31012008-12-04 22:20:51 +0000622 }
623
624 // Do the resolution.
625 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000626 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000627 case OR_Success: {
628 // Got one!
629 FunctionDecl *FnDecl = Best->Function;
630 // The first argument is size_t, and the first parameter must be size_t,
631 // too. This is checked on declaration and can be assumed. (It can't be
632 // asserted on, though, since invalid decls are left in there.)
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000633 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl33a31012008-12-04 22:20:51 +0000634 // FIXME: Passing word to diagnostic.
Anders Carlsson24187122009-05-31 19:49:47 +0000635 if (PerformCopyInitialization(Args[i],
Sebastian Redl33a31012008-12-04 22:20:51 +0000636 FnDecl->getParamDecl(i)->getType(),
637 "passing"))
638 return true;
639 }
640 Operator = FnDecl;
641 return false;
642 }
643
644 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +0000645 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +0000646 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000647 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
648 return true;
649
650 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +0000651 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000652 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +0000653 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
654 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000655
656 case OR_Deleted:
657 Diag(StartLoc, diag::err_ovl_deleted_call)
658 << Best->Function->isDeleted()
659 << Name << Range;
660 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
661 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +0000662 }
663 assert(false && "Unreachable, bad result from BestViableFunction");
664 return true;
665}
666
667
Sebastian Redlfaf68082008-12-03 20:26:15 +0000668/// DeclareGlobalNewDelete - Declare the global forms of operator new and
669/// delete. These are:
670/// @code
671/// void* operator new(std::size_t) throw(std::bad_alloc);
672/// void* operator new[](std::size_t) throw(std::bad_alloc);
673/// void operator delete(void *) throw();
674/// void operator delete[](void *) throw();
675/// @endcode
676/// Note that the placement and nothrow forms of new are *not* implicitly
677/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +0000678void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000679 if (GlobalNewDeleteDeclared)
680 return;
Douglas Gregor87f54062009-09-15 22:30:29 +0000681
682 // C++ [basic.std.dynamic]p2:
683 // [...] The following allocation and deallocation functions (18.4) are
684 // implicitly declared in global scope in each translation unit of a
685 // program
686 //
687 // void* operator new(std::size_t) throw(std::bad_alloc);
688 // void* operator new[](std::size_t) throw(std::bad_alloc);
689 // void operator delete(void*) throw();
690 // void operator delete[](void*) throw();
691 //
692 // These implicit declarations introduce only the function names operator
693 // new, operator new[], operator delete, operator delete[].
694 //
695 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
696 // "std" or "bad_alloc" as necessary to form the exception specification.
697 // However, we do not make these implicit declarations visible to name
698 // lookup.
699 if (!StdNamespace) {
700 // The "std" namespace has not yet been defined, so build one implicitly.
701 StdNamespace = NamespaceDecl::Create(Context,
702 Context.getTranslationUnitDecl(),
703 SourceLocation(),
704 &PP.getIdentifierTable().get("std"));
705 StdNamespace->setImplicit(true);
706 }
707
708 if (!StdBadAlloc) {
709 // The "std::bad_alloc" class has not yet been declared, so build it
710 // implicitly.
711 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
712 StdNamespace,
713 SourceLocation(),
714 &PP.getIdentifierTable().get("bad_alloc"),
715 SourceLocation(), 0);
716 StdBadAlloc->setImplicit(true);
717 }
718
Sebastian Redlfaf68082008-12-03 20:26:15 +0000719 GlobalNewDeleteDeclared = true;
720
721 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
722 QualType SizeT = Context.getSizeType();
723
Sebastian Redlfaf68082008-12-03 20:26:15 +0000724 DeclareGlobalAllocationFunction(
725 Context.DeclarationNames.getCXXOperatorName(OO_New),
726 VoidPtr, SizeT);
727 DeclareGlobalAllocationFunction(
728 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
729 VoidPtr, SizeT);
730 DeclareGlobalAllocationFunction(
731 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
732 Context.VoidTy, VoidPtr);
733 DeclareGlobalAllocationFunction(
734 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
735 Context.VoidTy, VoidPtr);
736}
737
738/// DeclareGlobalAllocationFunction - Declares a single implicit global
739/// allocation function if it doesn't already exist.
740void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType Return, QualType Argument) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000742 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
743
744 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000745 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +0000746 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000747 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000748 Alloc != AllocEnd; ++Alloc) {
749 // FIXME: Do we need to check for default arguments here?
750 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
751 if (Func->getNumParams() == 1 &&
Ted Kremenek5a201952009-02-07 01:47:29 +0000752 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlfaf68082008-12-03 20:26:15 +0000753 return;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000754 }
755 }
756
Douglas Gregor87f54062009-09-15 22:30:29 +0000757 QualType BadAllocType;
758 bool HasBadAllocExceptionSpec
759 = (Name.getCXXOverloadedOperator() == OO_New ||
760 Name.getCXXOverloadedOperator() == OO_Array_New);
761 if (HasBadAllocExceptionSpec) {
762 assert(StdBadAlloc && "Must have std::bad_alloc declared");
763 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
764 }
765
766 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
767 true, false,
768 HasBadAllocExceptionSpec? 1 : 0,
769 &BadAllocType);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000770 FunctionDecl *Alloc =
771 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000772 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000773 Alloc->setImplicit();
774 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000775 0, Argument, /*DInfo=*/0,
776 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +0000777 Alloc->setParams(Context, &Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000778
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000779 // FIXME: Also add this declaration to the IdentifierResolver, but
780 // make sure it is at the end of the chain to coincide with the
781 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000782 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +0000783}
784
Sebastian Redlbd150f42008-11-21 19:14:01 +0000785/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
786/// @code ::delete ptr; @endcode
787/// or
788/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000789Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000790Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +0000791 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000792 // C++ [expr.delete]p1:
793 // The operand shall have a pointer type, or a class type having a single
794 // conversion function to a pointer type. The result has type void.
795 //
Sebastian Redlbd150f42008-11-21 19:14:01 +0000796 // DR599 amends "pointer type" to "pointer to object type" in both cases.
797
Anders Carlssona471db02009-08-16 20:29:29 +0000798 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000799
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000800 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000801 if (!Ex->isTypeDependent()) {
802 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000803
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000804 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000805 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +0000806 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
807 OverloadedFunctionDecl *Conversions =
Fariborz Jahanianb394f502009-09-12 18:26:03 +0000808 RD->getVisibleConversionFunctions();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000809
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000810 for (OverloadedFunctionDecl::function_iterator
811 Func = Conversions->function_begin(),
812 FuncEnd = Conversions->function_end();
813 Func != FuncEnd; ++Func) {
814 // Skip over templated conversion functions; they aren't considered.
815 if (isa<FunctionTemplateDecl>(*Func))
816 continue;
817
818 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
819
820 QualType ConvType = Conv->getConversionType().getNonReferenceType();
821 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
822 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000823 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000824 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +0000825 if (ObjectPtrConversions.size() == 1) {
826 // We have a single conversion to a pointer-to-object type. Perform
827 // that conversion.
828 Operand.release();
829 if (!PerformImplicitConversion(Ex,
830 ObjectPtrConversions.front()->getConversionType(),
831 "converting")) {
832 Operand = Owned(Ex);
833 Type = Ex->getType();
834 }
835 }
836 else if (ObjectPtrConversions.size() > 1) {
837 Diag(StartLoc, diag::err_ambiguous_delete_operand)
838 << Type << Ex->getSourceRange();
839 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
840 CXXConversionDecl *Conv = ObjectPtrConversions[i];
841 Diag(Conv->getLocation(), diag::err_ovl_candidate);
842 }
843 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +0000844 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000845 }
846
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000847 if (!Type->isPointerType())
848 return ExprError(Diag(StartLoc, diag::err_delete_operand)
849 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000850
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000851 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000852 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000853 return ExprError(Diag(StartLoc, diag::err_delete_operand)
854 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000855 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +0000856 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000857 PDiag(diag::warn_delete_incomplete)
858 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +0000859 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000860
Douglas Gregor98496dc2009-09-29 21:38:53 +0000861 // C++ [expr.delete]p2:
862 // [Note: a pointer to a const type can be the operand of a
863 // delete-expression; it is not necessary to cast away the constness
864 // (5.2.11) of the pointer expression before it is used as the operand
865 // of the delete-expression. ]
866 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
867 CastExpr::CK_NoOp);
868
869 // Update the operand.
870 Operand.take();
871 Operand = ExprArg(*this, Ex);
872
Anders Carlssona471db02009-08-16 20:29:29 +0000873 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
874 ArrayForm ? OO_Array_Delete : OO_Delete);
875
876 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000877 CXXRecordDecl *Record
Anders Carlssona471db02009-08-16 20:29:29 +0000878 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000879
880 // Try to find operator delete/operator delete[] in class scope.
John McCall9f3059a2009-10-09 21:13:30 +0000881 LookupResult Found;
882 LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000883 // FIXME: Diagnose ambiguity properly
884 assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
885 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
886 F != FEnd; ++F) {
887 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
888 if (Delete->isUsualDeallocationFunction()) {
889 OperatorDelete = Delete;
890 break;
891 }
892 }
893
Fariborz Jahanian37d06562009-09-03 23:18:17 +0000894 if (!Record->hasTrivialDestructor())
895 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +0000896 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +0000897 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +0000898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899
Anders Carlssona471db02009-08-16 20:29:29 +0000900 if (!OperatorDelete) {
901 // Didn't find a member overload. Look for a global one.
902 DeclareGlobalNewDelete();
903 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000904 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +0000905 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +0000906 OperatorDelete))
907 return ExprError();
908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000910 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +0000911 }
912
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000913 Operand.release();
914 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +0000915 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000916}
917
918
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000919/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
920/// C++ if/switch/while/for statement.
921/// e.g: "if (int x = f()) {...}"
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000922Action::OwningExprResult
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000923Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
924 Declarator &D,
925 SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000926 ExprArg AssignExprVal) {
927 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000928
929 // C++ 6.4p2:
930 // The declarator shall not specify a function or an array.
931 // The type-specifier-seq shall not contain typedef and shall not declare a
932 // new class or enumeration.
933
934 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
935 "Parser allowed 'typedef' as storage class of condition decl.");
936
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000937 // FIXME: Store DeclaratorInfo in the expression.
938 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidisae438f82009-08-11 05:20:41 +0000939 TagDecl *OwnedTag = 0;
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000940 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000942 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
943 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
944 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000945 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
946 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000947 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerf490e152008-11-19 05:27:50 +0000948 Diag(StartLoc, diag::err_invalid_use_of_array_type)
949 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidisae438f82009-08-11 05:20:41 +0000950 } else if (OwnedTag && OwnedTag->isDefinition()) {
951 // The type-specifier-seq shall not declare a new class or enumeration.
952 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000953 }
954
Douglas Gregor4a75be22009-06-23 21:43:56 +0000955 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000956 if (!Dcl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000957 return ExprError();
Anders Carlsson5e9444f2009-05-30 21:37:25 +0000958 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000959
Douglas Gregor85970ca2008-12-10 23:01:14 +0000960 // Mark this variable as one that is declared within a conditional.
Chris Lattner83f095c2009-03-28 19:18:32 +0000961 // We know that the decl had to be a VarDecl because that is the only type of
962 // decl that can be assigned and the grammar requires an '='.
963 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
964 VD->setDeclaredInCondition(true);
965 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000966}
967
968/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
969bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
970 // C++ 6.4p4:
971 // The value of a condition that is an initialized declaration in a statement
972 // other than a switch statement is the value of the declared variable
973 // implicitly converted to type bool. If that conversion is ill-formed, the
974 // program is ill-formed.
975 // The value of a condition that is an expression is the value of the
976 // expression, implicitly converted to bool.
977 //
Douglas Gregor5fb53972009-01-14 15:45:31 +0000978 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000979}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000980
981/// Helper function to determine whether this is the (deprecated) C++
982/// conversion from a string literal to a pointer to non-const char or
983/// non-const wchar_t (for narrow and wide string literals,
984/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +0000985bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000986Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
987 // Look inside the implicit cast, if it exists.
988 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
989 From = Cast->getSubExpr();
990
991 // A string literal (2.13.4) that is not a wide string literal can
992 // be converted to an rvalue of type "pointer to char"; a wide
993 // string literal can be converted to an rvalue of type "pointer
994 // to wchar_t" (C++ 4.2p2).
995 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000996 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +0000997 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +0000998 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000999 // This conversion is considered only when there is an
1000 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001001 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001002 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1003 (!StrLit->isWide() &&
1004 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1005 ToPointeeType->getKind() == BuiltinType::Char_S))))
1006 return true;
1007 }
1008
1009 return false;
1010}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001011
1012/// PerformImplicitConversion - Perform an implicit conversion of the
1013/// expression From to the type ToType. Returns true if there was an
1014/// error, false otherwise. The expression From is replaced with the
Douglas Gregor47d3f272008-12-19 17:40:08 +00001015/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor5fb53972009-01-14 15:45:31 +00001016/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001017/// explicit user-defined conversions are permitted. @p Elidable should be true
1018/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1019/// resolution works differently in that case.
1020bool
Douglas Gregor47d3f272008-12-19 17:40:08 +00001021Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001022 const char *Flavor, bool AllowExplicit,
Mike Stump11289f42009-09-09 15:08:12 +00001023 bool Elidable) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001024 ImplicitConversionSequence ICS;
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00001025 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1026 Elidable, ICS);
1027}
1028
1029bool
1030Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1031 const char *Flavor, bool AllowExplicit,
1032 bool Elidable,
1033 ImplicitConversionSequence& ICS) {
Sebastian Redl42e92c42009-04-12 17:16:29 +00001034 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1035 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00001036 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001037 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00001038 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001039 /*ForceRValue=*/true,
1040 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001041 }
1042 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump11289f42009-09-09 15:08:12 +00001043 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001044 /*SuppressUserConversions=*/false,
1045 AllowExplicit,
Anders Carlsson228eea32009-08-28 15:33:32 +00001046 /*ForceRValue=*/false,
1047 /*InOverloadResolution=*/false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001048 }
Douglas Gregor5fb53972009-01-14 15:45:31 +00001049 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1050}
1051
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001052/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1053/// for the derived to base conversion of the expression 'From'. All
1054/// necessary information is passed in ICS.
1055bool
1056Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1057 const ImplicitConversionSequence& ICS,
1058 const char *Flavor) {
1059 QualType BaseType =
1060 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1061 // Must do additional defined to base conversion.
1062 QualType DerivedType =
1063 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1064
1065 From = new (Context) ImplicitCastExpr(
1066 DerivedType.getNonReferenceType(),
1067 CastKind,
1068 From,
1069 DerivedType->isLValueReferenceType());
1070 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1071 CastExpr::CK_DerivedToBase, From,
1072 BaseType->isLValueReferenceType());
1073 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1074 OwningExprResult FromResult =
1075 BuildCXXConstructExpr(
1076 ICS.UserDefined.After.CopyConstructor->getLocation(),
1077 BaseType,
1078 ICS.UserDefined.After.CopyConstructor,
1079 MultiExprArg(*this, (void **)&From, 1));
1080 if (FromResult.isInvalid())
1081 return true;
1082 From = FromResult.takeAs<Expr>();
1083 return false;
1084}
1085
Douglas Gregor5fb53972009-01-14 15:45:31 +00001086/// PerformImplicitConversion - Perform an implicit conversion of the
1087/// expression From to the type ToType using the pre-computed implicit
1088/// conversion sequence ICS. Returns true if there was an error, false
1089/// otherwise. The expression From is replaced with the converted
1090/// expression. Flavor is the kind of conversion we're performing,
1091/// used in the error message.
1092bool
1093Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1094 const ImplicitConversionSequence &ICS,
1095 const char* Flavor) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001096 switch (ICS.ConversionKind) {
1097 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor47d3f272008-12-19 17:40:08 +00001098 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001099 return true;
1100 break;
1101
Anders Carlsson110b07b2009-09-15 06:28:28 +00001102 case ImplicitConversionSequence::UserDefinedConversion: {
1103
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001104 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1105 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001106 QualType BeforeToType;
1107 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001108 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001109
1110 // If the user-defined conversion is specified by a conversion function,
1111 // the initial standard conversion sequence converts the source type to
1112 // the implicit object parameter of the conversion function.
1113 BeforeToType = Context.getTagDeclType(Conv->getParent());
1114 } else if (const CXXConstructorDecl *Ctor =
1115 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001116 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001117
1118 // If the user-defined conversion is specified by a constructor, the
1119 // initial standard conversion sequence converts the source type to the
1120 // type required by the argument of the constructor
1121 BeforeToType = Ctor->getParamDecl(0)->getType();
1122 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001123 else
1124 assert(0 && "Unknown conversion function kind!");
1125
Anders Carlsson110b07b2009-09-15 06:28:28 +00001126 if (PerformImplicitConversion(From, BeforeToType,
1127 ICS.UserDefined.Before, "converting"))
1128 return true;
1129
Anders Carlssone9766d52009-09-09 21:33:21 +00001130 OwningExprResult CastArg
1131 = BuildCXXCastArgument(From->getLocStart(),
1132 ToType.getNonReferenceType(),
1133 CastKind, cast<CXXMethodDecl>(FD),
1134 Owned(From));
1135
1136 if (CastArg.isInvalid())
1137 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001138
1139 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1140 ICS.UserDefined.After.CopyConstructor) {
1141 From = CastArg.takeAs<Expr>();
1142 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1143 }
Fariborz Jahanianc9af8fd2009-10-23 18:08:22 +00001144
1145 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1146 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1147 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlssone9766d52009-09-09 21:33:21 +00001148
Anders Carlsson611da282009-09-15 05:49:31 +00001149 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001150 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson611da282009-09-15 05:49:31 +00001151 ToType->isLValueReferenceType());
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001152 return false;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001153 }
1154
Douglas Gregor39c16d42008-10-24 04:54:22 +00001155 case ImplicitConversionSequence::EllipsisConversion:
1156 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001158
1159 case ImplicitConversionSequence::BadConversion:
1160 return true;
1161 }
1162
1163 // Everything went well.
1164 return false;
1165}
1166
1167/// PerformImplicitConversion - Perform an implicit conversion of the
1168/// expression From to the type ToType by following the standard
1169/// conversion sequence SCS. Returns true if there was an error, false
1170/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001171/// expression. Flavor is the context in which we're performing this
1172/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001173bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001174Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001175 const StandardConversionSequence& SCS,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001176 const char *Flavor) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001177 // Overall FIXME: we are recomputing too many types here and doing far too
1178 // much extra work. What this means is that we need to keep track of more
1179 // information that is computed when we try the implicit conversion initially,
1180 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001181 QualType FromType = From->getType();
1182
Douglas Gregor2fe98832008-11-03 19:09:14 +00001183 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001184 // FIXME: When can ToType be a reference type?
1185 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001186 if (SCS.Second == ICK_Derived_To_Base) {
1187 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1188 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1189 MultiExprArg(*this, (void **)&From, 1),
1190 /*FIXME:ConstructLoc*/SourceLocation(),
1191 ConstructorArgs))
1192 return true;
1193 OwningExprResult FromResult =
1194 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1195 ToType, SCS.CopyConstructor,
1196 move_arg(ConstructorArgs));
1197 if (FromResult.isInvalid())
1198 return true;
1199 From = FromResult.takeAs<Expr>();
1200 return false;
1201 }
Mike Stump11289f42009-09-09 15:08:12 +00001202 OwningExprResult FromResult =
1203 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1204 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001205 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001206
Anders Carlsson6eb55572009-08-25 05:12:04 +00001207 if (FromResult.isInvalid())
1208 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001209
Anders Carlsson6eb55572009-08-25 05:12:04 +00001210 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001211 return false;
1212 }
1213
Douglas Gregor39c16d42008-10-24 04:54:22 +00001214 // Perform the first implicit conversion.
1215 switch (SCS.First) {
1216 case ICK_Identity:
1217 case ICK_Lvalue_To_Rvalue:
1218 // Nothing to do.
1219 break;
1220
1221 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001222 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001223 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001224 break;
1225
1226 case ICK_Function_To_Pointer:
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001227 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00001228 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1229 if (!Fn)
1230 return true;
1231
Douglas Gregor171c45a2009-02-18 21:56:37 +00001232 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1233 return true;
1234
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001235 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregorcd695e52008-11-10 20:40:00 +00001236 FromType = From->getType();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001237
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001238 // If there's already an address-of operator in the expression, we have
1239 // the right type already, and the code below would just introduce an
1240 // invalid additional pointer level.
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00001241 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redlfef1c0d2009-10-17 20:50:27 +00001242 break;
Douglas Gregorcd695e52008-11-10 20:40:00 +00001243 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001244 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001245 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001246 break;
1247
1248 default:
1249 assert(false && "Improper first standard conversion");
1250 break;
1251 }
1252
1253 // Perform the second implicit conversion
1254 switch (SCS.Second) {
1255 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001256 // If both sides are functions (or pointers/references to them), there could
1257 // be incompatible exception declarations.
1258 if (CheckExceptionSpecCompatibility(From, ToType))
1259 return true;
1260 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001261 break;
1262
1263 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001264 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001265 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1266 break;
1267
1268 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001269 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001270 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1271 break;
1272
1273 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001274 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001275 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1276 break;
1277
Douglas Gregor39c16d42008-10-24 04:54:22 +00001278 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001279 if (ToType->isFloatingType())
1280 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1281 else
1282 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1283 break;
1284
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001285 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001286 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1287 break;
1288
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001289 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001290 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001291 break;
1292
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001293 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001294 if (SCS.IncompatibleObjC) {
1295 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001296 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001297 diag::ext_typecheck_convert_incompatible_pointer)
1298 << From->getType() << ToType << Flavor
1299 << From->getSourceRange();
1300 }
1301
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001302
1303 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1304 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001305 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001306 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001307 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001308 }
1309
1310 case ICK_Pointer_Member: {
1311 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1312 if (CheckMemberPointerConversion(From, ToType, Kind))
1313 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001314 if (CheckExceptionSpecCompatibility(From, ToType))
1315 return true;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001316 ImpCastExprToType(From, ToType, Kind);
1317 break;
1318 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001319 case ICK_Boolean_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001320 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001321 break;
1322
1323 default:
1324 assert(false && "Improper second standard conversion");
1325 break;
1326 }
1327
1328 switch (SCS.Third) {
1329 case ICK_Identity:
1330 // Nothing to do.
1331 break;
1332
1333 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001334 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1335 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001336 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman06ed2a52009-10-20 08:27:19 +00001337 CastExpr::CK_NoOp,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001338 ToType->isLValueReferenceType());
Douglas Gregor39c16d42008-10-24 04:54:22 +00001339 break;
1340
1341 default:
1342 assert(false && "Improper second standard conversion");
1343 break;
1344 }
1345
1346 return false;
1347}
1348
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001349Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1350 SourceLocation KWLoc,
1351 SourceLocation LParen,
1352 TypeTy *Ty,
1353 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001354 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001355
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001356 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1357 // all traits except __is_class, __is_enum and __is_union require a the type
1358 // to be complete.
1359 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001360 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001361 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001362 return ExprError();
1363 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001364
1365 // There is no point in eagerly computing the value. The traits are designed
1366 // to be used from type trait templates, so Ty will be a template parameter
1367 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001368 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1369 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001370}
Sebastian Redl5822f082009-02-07 20:10:22 +00001371
1372QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001373 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001374 const char *OpSpelling = isIndirect ? "->*" : ".*";
1375 // C++ 5.5p2
1376 // The binary operator .* [p3: ->*] binds its second operand, which shall
1377 // be of type "pointer to member of T" (where T is a completely-defined
1378 // class type) [...]
1379 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001380 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001381 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001382 Diag(Loc, diag::err_bad_memptr_rhs)
1383 << OpSpelling << RType << rex->getSourceRange();
1384 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001385 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001386
Sebastian Redl5822f082009-02-07 20:10:22 +00001387 QualType Class(MemPtr->getClass(), 0);
1388
1389 // C++ 5.5p2
1390 // [...] to its first operand, which shall be of class T or of a class of
1391 // which T is an unambiguous and accessible base class. [p3: a pointer to
1392 // such a class]
1393 QualType LType = lex->getType();
1394 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001395 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001396 LType = Ptr->getPointeeType().getNonReferenceType();
1397 else {
1398 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001399 << OpSpelling << 1 << LType
1400 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001401 return QualType();
1402 }
1403 }
1404
1405 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1406 Context.getCanonicalType(LType).getUnqualifiedType()) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001407 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1408 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001409 // FIXME: Would it be useful to print full ambiguity paths, or is that
1410 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001411 if (!IsDerivedFrom(LType, Class, Paths) ||
1412 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001413 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl5822f082009-02-07 20:10:22 +00001414 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001415 << (int)isIndirect << lex->getType() <<
1416 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl5822f082009-02-07 20:10:22 +00001417 return QualType();
1418 }
1419 }
1420
1421 // C++ 5.5p2
1422 // The result is an object or a function of the type specified by the
1423 // second operand.
1424 // The cv qualifiers are the union of those in the pointer and the left side,
1425 // in accordance with 5.5p5 and 5.2.5.
1426 // FIXME: This returns a dereferenced member function pointer as a normal
1427 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001428 // calling them. There's also a GCC extension to get a function pointer to the
1429 // thing, which is another complication, because this type - unlike the type
1430 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001431 // argument.
1432 // We probably need a "MemberFunctionClosureType" or something like that.
1433 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001434 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001435 return Result;
1436}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001437
1438/// \brief Get the target type of a standard or user-defined conversion.
1439static QualType TargetType(const ImplicitConversionSequence &ICS) {
1440 assert((ICS.ConversionKind ==
1441 ImplicitConversionSequence::StandardConversion ||
1442 ICS.ConversionKind ==
1443 ImplicitConversionSequence::UserDefinedConversion) &&
1444 "function only valid for standard or user-defined conversions");
1445 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1446 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1447 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1448}
1449
1450/// \brief Try to convert a type to another according to C++0x 5.16p3.
1451///
1452/// This is part of the parameter validation for the ? operator. If either
1453/// value operand is a class type, the two operands are attempted to be
1454/// converted to each other. This function does the conversion in one direction.
1455/// It emits a diagnostic and returns true only if it finds an ambiguous
1456/// conversion.
1457static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1458 SourceLocation QuestionLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001459 ImplicitConversionSequence &ICS) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001460 // C++0x 5.16p3
1461 // The process for determining whether an operand expression E1 of type T1
1462 // can be converted to match an operand expression E2 of type T2 is defined
1463 // as follows:
1464 // -- If E2 is an lvalue:
1465 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1466 // E1 can be converted to match E2 if E1 can be implicitly converted to
1467 // type "lvalue reference to T2", subject to the constraint that in the
1468 // conversion the reference must bind directly to E1.
1469 if (!Self.CheckReferenceInit(From,
1470 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001471 To->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001472 /*SuppressUserConversions=*/false,
1473 /*AllowExplicit=*/false,
1474 /*ForceRValue=*/false,
1475 &ICS))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001476 {
1477 assert((ICS.ConversionKind ==
1478 ImplicitConversionSequence::StandardConversion ||
1479 ICS.ConversionKind ==
1480 ImplicitConversionSequence::UserDefinedConversion) &&
1481 "expected a definite conversion");
1482 bool DirectBinding =
1483 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1484 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1485 if (DirectBinding)
1486 return false;
1487 }
1488 }
1489 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1490 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1491 // -- if E1 and E2 have class type, and the underlying class types are
1492 // the same or one is a base class of the other:
1493 QualType FTy = From->getType();
1494 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001495 const RecordType *FRec = FTy->getAs<RecordType>();
1496 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl1a99f442009-04-16 17:51:27 +00001497 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1498 if (FRec && TRec && (FRec == TRec ||
1499 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1500 // E1 can be converted to match E2 if the class of T2 is the
1501 // same type as, or a base class of, the class of T1, and
1502 // [cv2 > cv1].
1503 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1504 // Could still fail if there's no copy constructor.
1505 // FIXME: Is this a hard error then, or just a conversion failure? The
1506 // standard doesn't say.
Mike Stump11289f42009-09-09 15:08:12 +00001507 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlsson03068aa2009-08-27 17:18:13 +00001508 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00001509 /*ForceRValue=*/false,
1510 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001511 }
1512 } else {
1513 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1514 // implicitly converted to the type that expression E2 would have
1515 // if E2 were converted to an rvalue.
1516 // First find the decayed type.
1517 if (TTy->isFunctionType())
1518 TTy = Self.Context.getPointerType(TTy);
Mike Stump11289f42009-09-09 15:08:12 +00001519 else if (TTy->isArrayType())
Sebastian Redl1a99f442009-04-16 17:51:27 +00001520 TTy = Self.Context.getArrayDecayedType(TTy);
1521
1522 // Now try the implicit conversion.
1523 // FIXME: This doesn't detect ambiguities.
Anders Carlssonef4c7212009-08-27 17:24:15 +00001524 ICS = Self.TryImplicitConversion(From, TTy,
1525 /*SuppressUserConversions=*/false,
1526 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001527 /*ForceRValue=*/false,
1528 /*InOverloadResolution=*/false);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001529 }
1530 return false;
1531}
1532
1533/// \brief Try to find a common type for two according to C++0x 5.16p5.
1534///
1535/// This is part of the parameter validation for the ? operator. If either
1536/// value operand is a class type, overload resolution is used to find a
1537/// conversion to a common type.
1538static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1539 SourceLocation Loc) {
1540 Expr *Args[2] = { LHS, RHS };
1541 OverloadCandidateSet CandidateSet;
Douglas Gregorc02cfe22009-10-21 23:19:44 +00001542 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001543
1544 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001545 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001546 case Sema::OR_Success:
1547 // We found a match. Perform the conversions on the arguments and move on.
1548 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1549 Best->Conversions[0], "converting") ||
1550 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1551 Best->Conversions[1], "converting"))
1552 break;
1553 return false;
1554
1555 case Sema::OR_No_Viable_Function:
1556 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1557 << LHS->getType() << RHS->getType()
1558 << LHS->getSourceRange() << RHS->getSourceRange();
1559 return true;
1560
1561 case Sema::OR_Ambiguous:
1562 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1563 << LHS->getType() << RHS->getType()
1564 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00001565 // FIXME: Print the possible common types by printing the return types of
1566 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001567 break;
1568
1569 case Sema::OR_Deleted:
1570 assert(false && "Conditional operator has only built-in overloads");
1571 break;
1572 }
1573 return true;
1574}
1575
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001576/// \brief Perform an "extended" implicit conversion as returned by
1577/// TryClassUnification.
1578///
1579/// TryClassUnification generates ICSs that include reference bindings.
1580/// PerformImplicitConversion is not suitable for this; it chokes if the
1581/// second part of a standard conversion is ICK_DerivedToBase. This function
1582/// handles the reference binding specially.
1583static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump11289f42009-09-09 15:08:12 +00001584 const ImplicitConversionSequence &ICS) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001585 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1586 ICS.Standard.ReferenceBinding) {
1587 assert(ICS.Standard.DirectBinding &&
1588 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001589 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1590 // redoing all the work.
1591 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001592 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001593 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001594 /*SuppressUserConversions=*/false,
1595 /*AllowExplicit=*/false,
1596 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001597 }
1598 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1599 ICS.UserDefined.After.ReferenceBinding) {
1600 assert(ICS.UserDefined.After.DirectBinding &&
1601 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redlf79d3972009-04-26 11:21:02 +00001602 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson271e3a42009-08-27 17:30:43 +00001603 TargetType(ICS)),
Douglas Gregorc809cc22009-09-23 23:04:10 +00001604 /*FIXME:*/E->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001605 /*SuppressUserConversions=*/false,
1606 /*AllowExplicit=*/false,
1607 /*ForceRValue=*/false);
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001608 }
1609 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1610 return true;
1611 return false;
1612}
1613
Sebastian Redl1a99f442009-04-16 17:51:27 +00001614/// \brief Check the operands of ?: under C++ semantics.
1615///
1616/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1617/// extension. In this case, LHS == Cond. (But they're not aliases.)
1618QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1619 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001620 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1621 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001622
1623 // C++0x 5.16p1
1624 // The first expression is contextually converted to bool.
1625 if (!Cond->isTypeDependent()) {
1626 if (CheckCXXBooleanCondition(Cond))
1627 return QualType();
1628 }
1629
1630 // Either of the arguments dependent?
1631 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1632 return Context.DependentTy;
1633
1634 // C++0x 5.16p2
1635 // If either the second or the third operand has type (cv) void, ...
1636 QualType LTy = LHS->getType();
1637 QualType RTy = RHS->getType();
1638 bool LVoid = LTy->isVoidType();
1639 bool RVoid = RTy->isVoidType();
1640 if (LVoid || RVoid) {
1641 // ... then the [l2r] conversions are performed on the second and third
1642 // operands ...
1643 DefaultFunctionArrayConversion(LHS);
1644 DefaultFunctionArrayConversion(RHS);
1645 LTy = LHS->getType();
1646 RTy = RHS->getType();
1647
1648 // ... and one of the following shall hold:
1649 // -- The second or the third operand (but not both) is a throw-
1650 // expression; the result is of the type of the other and is an rvalue.
1651 bool LThrow = isa<CXXThrowExpr>(LHS);
1652 bool RThrow = isa<CXXThrowExpr>(RHS);
1653 if (LThrow && !RThrow)
1654 return RTy;
1655 if (RThrow && !LThrow)
1656 return LTy;
1657
1658 // -- Both the second and third operands have type void; the result is of
1659 // type void and is an rvalue.
1660 if (LVoid && RVoid)
1661 return Context.VoidTy;
1662
1663 // Neither holds, error.
1664 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1665 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1666 << LHS->getSourceRange() << RHS->getSourceRange();
1667 return QualType();
1668 }
1669
1670 // Neither is void.
1671
1672 // C++0x 5.16p3
1673 // Otherwise, if the second and third operand have different types, and
1674 // either has (cv) class type, and attempt is made to convert each of those
1675 // operands to the other.
1676 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1677 (LTy->isRecordType() || RTy->isRecordType())) {
1678 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1679 // These return true if a single direction is already ambiguous.
1680 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1681 return QualType();
1682 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1683 return QualType();
1684
1685 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1686 ImplicitConversionSequence::BadConversion;
1687 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1688 ImplicitConversionSequence::BadConversion;
1689 // If both can be converted, [...] the program is ill-formed.
1690 if (HaveL2R && HaveR2L) {
1691 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1692 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1693 return QualType();
1694 }
1695
1696 // If exactly one conversion is possible, that conversion is applied to
1697 // the chosen operand and the converted operands are used in place of the
1698 // original operands for the remainder of this section.
1699 if (HaveL2R) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001700 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001701 return QualType();
1702 LTy = LHS->getType();
1703 } else if (HaveR2L) {
Sebastian Redl5775af1a2009-04-17 16:30:52 +00001704 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl1a99f442009-04-16 17:51:27 +00001705 return QualType();
1706 RTy = RHS->getType();
1707 }
1708 }
1709
1710 // C++0x 5.16p4
1711 // If the second and third operands are lvalues and have the same type,
1712 // the result is of that type [...]
1713 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1714 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1715 RHS->isLvalue(Context) == Expr::LV_Valid)
1716 return LTy;
1717
1718 // C++0x 5.16p5
1719 // Otherwise, the result is an rvalue. If the second and third operands
1720 // do not have the same type, and either has (cv) class type, ...
1721 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1722 // ... overload resolution is used to determine the conversions (if any)
1723 // to be applied to the operands. If the overload resolution fails, the
1724 // program is ill-formed.
1725 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1726 return QualType();
1727 }
1728
1729 // C++0x 5.16p6
1730 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1731 // conversions are performed on the second and third operands.
1732 DefaultFunctionArrayConversion(LHS);
1733 DefaultFunctionArrayConversion(RHS);
1734 LTy = LHS->getType();
1735 RTy = RHS->getType();
1736
1737 // After those conversions, one of the following shall hold:
1738 // -- The second and third operands have the same type; the result
1739 // is of that type.
1740 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1741 return LTy;
1742
1743 // -- The second and third operands have arithmetic or enumeration type;
1744 // the usual arithmetic conversions are performed to bring them to a
1745 // common type, and the result is of that type.
1746 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1747 UsualArithmeticConversions(LHS, RHS);
1748 return LHS->getType();
1749 }
1750
1751 // -- The second and third operands have pointer type, or one has pointer
1752 // type and the other is a null pointer constant; pointer conversions
1753 // and qualification conversions are performed to bring them to their
1754 // composite pointer type. The result is of the composite pointer type.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001755 QualType Composite = FindCompositePointerType(LHS, RHS);
1756 if (!Composite.isNull())
1757 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001758
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001759 // Fourth bullet is same for pointers-to-member. However, the possible
1760 // conversions are far more limited: we have null-to-pointer, upcast of
1761 // containing class, and second-level cv-ness.
1762 // cv-ness is not a union, but must match one of the two operands. (Which,
1763 // frankly, is stupid.)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001764 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1765 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregor56751b52009-09-25 04:25:58 +00001766 if (LMemPtr &&
1767 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001768 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001769 return LTy;
1770 }
Douglas Gregor56751b52009-09-25 04:25:58 +00001771 if (RMemPtr &&
1772 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001773 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001774 return RTy;
1775 }
1776 if (LMemPtr && RMemPtr) {
1777 QualType LPointee = LMemPtr->getPointeeType();
1778 QualType RPointee = RMemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001779
1780 QualifierCollector LPQuals, RPQuals;
1781 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1782 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1783
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001784 // First, we check that the unqualified pointee type is the same. If it's
1785 // not, there's no conversion that will unify the two pointers.
John McCall8ccfcb52009-09-24 19:53:00 +00001786 if (LPCan == RPCan) {
1787
1788 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001789 // is greater than the other, the conversion is not possible.
John McCall8ccfcb52009-09-24 19:53:00 +00001790
1791 Qualifiers MergedQuals = LPQuals + RPQuals;
1792
1793 bool CompatibleQuals = true;
1794 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1795 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1796 CompatibleQuals = false;
1797 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1798 // FIXME:
1799 // C99 6.5.15 as modified by TR 18037:
1800 // If the second and third operands are pointers into different
1801 // address spaces, the address spaces must overlap.
1802 CompatibleQuals = false;
1803 // FIXME: GC qualifiers?
1804
1805 if (CompatibleQuals) {
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001806 // Third, we check if either of the container classes is derived from
1807 // the other.
1808 QualType LContainer(LMemPtr->getClass(), 0);
1809 QualType RContainer(RMemPtr->getClass(), 0);
1810 QualType MoreDerived;
1811 if (Context.getCanonicalType(LContainer) ==
1812 Context.getCanonicalType(RContainer))
1813 MoreDerived = LContainer;
1814 else if (IsDerivedFrom(LContainer, RContainer))
1815 MoreDerived = LContainer;
1816 else if (IsDerivedFrom(RContainer, LContainer))
1817 MoreDerived = RContainer;
1818
1819 if (!MoreDerived.isNull()) {
1820 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1821 // We don't use ImpCastExprToType here because this could still fail
1822 // for ambiguous or inaccessible conversions.
John McCall8ccfcb52009-09-24 19:53:00 +00001823 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1824 QualType Common
1825 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl0753c6f2009-04-19 21:15:26 +00001826 if (PerformImplicitConversion(LHS, Common, "converting"))
1827 return QualType();
1828 if (PerformImplicitConversion(RHS, Common, "converting"))
1829 return QualType();
1830 return Common;
1831 }
1832 }
1833 }
1834 }
1835
Sebastian Redl1a99f442009-04-16 17:51:27 +00001836 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1837 << LHS->getType() << RHS->getType()
1838 << LHS->getSourceRange() << RHS->getSourceRange();
1839 return QualType();
1840}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001841
1842/// \brief Find a merged pointer type and convert the two expressions to it.
1843///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001844/// This finds the composite pointer type (or member pointer type) for @p E1
1845/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1846/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001847/// It does not emit diagnostics.
1848QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1849 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1850 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001852 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1853 !T2->isPointerType() && !T2->isMemberPointerType())
1854 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001855
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001856 // FIXME: Do we need to work on the canonical types?
Mike Stump11289f42009-09-09 15:08:12 +00001857
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001858 // C++0x 5.9p2
1859 // Pointer conversions and qualification conversions are performed on
1860 // pointer operands to bring them to their composite pointer type. If
1861 // one operand is a null pointer constant, the composite pointer type is
1862 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00001863 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001864 if (T2->isMemberPointerType())
1865 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1866 else
1867 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001868 return T2;
1869 }
Douglas Gregor56751b52009-09-25 04:25:58 +00001870 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00001871 if (T1->isMemberPointerType())
1872 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1873 else
1874 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001875 return T1;
1876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001878 // Now both have to be pointers or member pointers.
1879 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1880 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001881 return QualType();
1882
1883 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1884 // the other has type "pointer to cv2 T" and the composite pointer type is
1885 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1886 // Otherwise, the composite pointer type is a pointer type similar to the
1887 // type of one of the operands, with a cv-qualification signature that is
1888 // the union of the cv-qualification signatures of the operand types.
1889 // In practice, the first part here is redundant; it's subsumed by the second.
1890 // What we do here is, we build the two possible composite types, and try the
1891 // conversions in both directions. If only one works, or if the two composite
1892 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00001893 // FIXME: extended qualifiers?
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001894 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001895 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001896 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001897 do {
1898 const PointerType *Ptr1, *Ptr2;
1899 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1900 (Ptr2 = Composite2->getAs<PointerType>())) {
1901 Composite1 = Ptr1->getPointeeType();
1902 Composite2 = Ptr2->getPointeeType();
1903 QualifierUnion.push_back(
1904 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1905 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1906 continue;
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001909 const MemberPointerType *MemPtr1, *MemPtr2;
1910 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1911 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1912 Composite1 = MemPtr1->getPointeeType();
1913 Composite2 = MemPtr2->getPointeeType();
1914 QualifierUnion.push_back(
1915 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1916 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1917 MemPtr2->getClass()));
1918 continue;
1919 }
Mike Stump11289f42009-09-09 15:08:12 +00001920
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001921 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001923 // Cannot unwrap any more types.
1924 break;
1925 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00001926
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001927 // Rewrap the composites as pointers or member pointers with the union CVRs.
1928 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1929 = MemberOfClass.begin();
Mike Stump11289f42009-09-09 15:08:12 +00001930 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001931 I = QualifierUnion.begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001932 E = QualifierUnion.end();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001933 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00001934 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001935 if (MOC->first && MOC->second) {
1936 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00001937 Composite1 = Context.getMemberPointerType(
1938 Context.getQualifiedType(Composite1, Quals),
1939 MOC->first);
1940 Composite2 = Context.getMemberPointerType(
1941 Context.getQualifiedType(Composite2, Quals),
1942 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001943 } else {
1944 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00001945 Composite1
1946 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1947 Composite2
1948 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00001949 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001950 }
1951
Mike Stump11289f42009-09-09 15:08:12 +00001952 ImplicitConversionSequence E1ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001953 TryImplicitConversion(E1, Composite1,
1954 /*SuppressUserConversions=*/false,
1955 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001956 /*ForceRValue=*/false,
1957 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001958 ImplicitConversionSequence E2ToC1 =
Anders Carlssonef4c7212009-08-27 17:24:15 +00001959 TryImplicitConversion(E2, Composite1,
1960 /*SuppressUserConversions=*/false,
1961 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001962 /*ForceRValue=*/false,
1963 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001964
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001965 ImplicitConversionSequence E1ToC2, E2ToC2;
1966 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1967 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1968 if (Context.getCanonicalType(Composite1) !=
1969 Context.getCanonicalType(Composite2)) {
Anders Carlssonef4c7212009-08-27 17:24:15 +00001970 E1ToC2 = TryImplicitConversion(E1, Composite2,
1971 /*SuppressUserConversions=*/false,
1972 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001973 /*ForceRValue=*/false,
1974 /*InOverloadResolution=*/false);
Anders Carlssonef4c7212009-08-27 17:24:15 +00001975 E2ToC2 = TryImplicitConversion(E2, Composite2,
1976 /*SuppressUserConversions=*/false,
1977 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001978 /*ForceRValue=*/false,
1979 /*InOverloadResolution=*/false);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00001980 }
1981
1982 bool ToC1Viable = E1ToC1.ConversionKind !=
1983 ImplicitConversionSequence::BadConversion
1984 && E2ToC1.ConversionKind !=
1985 ImplicitConversionSequence::BadConversion;
1986 bool ToC2Viable = E1ToC2.ConversionKind !=
1987 ImplicitConversionSequence::BadConversion
1988 && E2ToC2.ConversionKind !=
1989 ImplicitConversionSequence::BadConversion;
1990 if (ToC1Viable && !ToC2Viable) {
1991 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1992 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1993 return Composite1;
1994 }
1995 if (ToC2Viable && !ToC1Viable) {
1996 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1997 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1998 return Composite2;
1999 }
2000 return QualType();
2001}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002002
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002003Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002004 if (!Context.getLangOptions().CPlusPlus)
2005 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002006
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002007 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002008 if (!RT)
2009 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002011 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2012 if (RD->hasTrivialDestructor())
2013 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002014
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002015 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2016 QualType Ty = CE->getCallee()->getType();
2017 if (const PointerType *PT = Ty->getAs<PointerType>())
2018 Ty = PT->getPointeeType();
2019
John McCall9dd450b2009-09-21 23:43:11 +00002020 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002021 if (FTy->getResultType()->isReferenceType())
2022 return Owned(E);
2023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002025 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002026 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002027 if (CXXDestructorDecl *Destructor =
2028 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2029 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002030 // FIXME: Add the temporary to the temporaries vector.
2031 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2032}
2033
Mike Stump11289f42009-09-09 15:08:12 +00002034Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002035 bool ShouldDestroyTemps) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002036 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002037
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002038 if (ExprTemporaries.empty())
2039 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002040
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002041 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002042 &ExprTemporaries[0],
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002043 ExprTemporaries.size(),
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002044 ShouldDestroyTemps);
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002045 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00002046
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002047 return E;
2048}
2049
Mike Stump11289f42009-09-09 15:08:12 +00002050Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002051Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2052 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2053 // Since this might be a postfix expression, get rid of ParenListExprs.
2054 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002056 Expr *BaseExpr = (Expr*)Base.get();
2057 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002058
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002059 QualType BaseType = BaseExpr->getType();
2060 if (BaseType->isDependentType()) {
2061 // FIXME: member of the current instantiation
2062 ObjectType = BaseType.getAsOpaquePtr();
2063 return move(Base);
2064 }
Mike Stump11289f42009-09-09 15:08:12 +00002065
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002066 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002067 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002068 // returned, with the original second operand.
2069 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002070 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002071 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002072 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002073 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002074
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002075 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002076 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002077 BaseExpr = (Expr*)Base.get();
2078 if (BaseExpr == NULL)
2079 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002080 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002081 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002082 BaseType = BaseExpr->getType();
2083 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002084 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002085 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002086 for (unsigned i = 0; i < Locations.size(); i++)
2087 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002088 return ExprError();
2089 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002090 }
2091 }
Mike Stump11289f42009-09-09 15:08:12 +00002092
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002093 if (BaseType->isPointerType())
2094 BaseType = BaseType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002095
2096 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002097 // vector types or Objective-C interfaces. Just return early and let
2098 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002099 if (!BaseType->isRecordType()) {
2100 // C++ [basic.lookup.classref]p2:
2101 // [...] If the type of the object expression is of pointer to scalar
2102 // type, the unqualified-id is looked up in the context of the complete
2103 // postfix-expression.
2104 ObjectType = 0;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002105 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002106 }
Mike Stump11289f42009-09-09 15:08:12 +00002107
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002108 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002109 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002110 // unqualified-id, and the type of the object expres- sion is of a class
2111 // type C (or of pointer to a class type C), the unqualified-id is looked
2112 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002113 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002114 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002115}
2116
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002117CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2118 CXXMethodDecl *Method) {
2119 MemberExpr *ME =
2120 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2121 SourceLocation(), Method->getType());
2122 QualType ResultType;
2123 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2124 ResultType = Conv->getConversionType().getNonReferenceType();
2125 else
2126 ResultType = Method->getResultType().getNonReferenceType();
2127
2128 CXXMemberCallExpr *CE =
2129 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2130 ResultType,
2131 SourceLocation());
2132 return CE;
2133}
2134
Anders Carlssone9766d52009-09-09 21:33:21 +00002135Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2136 QualType Ty,
2137 CastExpr::CastKind Kind,
2138 CXXMethodDecl *Method,
2139 ExprArg Arg) {
2140 Expr *From = Arg.takeAs<Expr>();
2141
2142 switch (Kind) {
2143 default: assert(0 && "Unhandled cast kind!");
2144 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00002145 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2146
2147 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2148 MultiExprArg(*this, (void **)&From, 1),
2149 CastLoc, ConstructorArgs))
2150 return ExprError();
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002151
2152 OwningExprResult Result =
2153 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2154 move_arg(ConstructorArgs));
2155 if (Result.isInvalid())
2156 return ExprError();
2157
2158 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlssone9766d52009-09-09 21:33:21 +00002159 }
2160
2161 case CastExpr::CK_UserDefinedConversion: {
Anders Carlsson6b2737d2009-09-15 07:42:44 +00002162 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2163
2164 // Cast to base if needed.
2165 if (PerformObjectArgumentInitialization(From, Method))
2166 return ExprError();
2167
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002168 // Create an implicit call expr that calls it.
2169 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson8f741bf2009-10-18 21:20:14 +00002170 return MaybeBindToTemporary(CE);
Anders Carlssone9766d52009-09-09 21:33:21 +00002171 }
Anders Carlssone9766d52009-09-09 21:33:21 +00002172 }
2173}
2174
Anders Carlsson85a307d2009-05-17 18:41:29 +00002175Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2176 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002177 if (FullExpr)
Mike Stump11289f42009-09-09 15:08:12 +00002178 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssona42ab8f2009-06-16 03:37:31 +00002179 /*ShouldDestroyTemps=*/true);
Anders Carlsson85a307d2009-05-17 18:41:29 +00002180
Anders Carlsson7e3f0e42009-08-25 23:46:41 +00002181
Anders Carlsson85a307d2009-05-17 18:41:29 +00002182 return Owned(FullExpr);
2183}
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002184
2185/// \brief Determine whether a reference to the given declaration in the
2186/// current context is an implicit member access
2187/// (C++ [class.mfct.non-static]p2).
2188///
2189/// FIXME: Should Objective-C also use this approach?
2190///
2191/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2192/// name of the declaration referenced.
2193///
2194/// \param D the declaration being referenced from the current scope.
2195///
2196/// \param NameLoc the location of the name in the source.
2197///
2198/// \param ThisType if the reference to this declaration is an implicit member
2199/// access, will be set to the type of the "this" pointer to be used when
2200/// building that implicit member access.
2201///
2202/// \param MemberType if the reference to this declaration is an implicit
2203/// member access, will be set to the type of the member being referenced
2204/// (for use at the type of the resulting member access expression).
2205///
2206/// \returns true if this is an implicit member reference (in which case
2207/// \p ThisType and \p MemberType will be set), or false if it is not an
2208/// implicit member reference.
2209bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2210 SourceLocation NameLoc, QualType &ThisType,
2211 QualType &MemberType) {
2212 // If this isn't a C++ method, then it isn't an implicit member reference.
2213 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2214 if (!MD || MD->isStatic())
2215 return false;
2216
2217 // C++ [class.mfct.nonstatic]p2:
2218 // [...] if name lookup (3.4.1) resolves the name in the
2219 // id-expression to a nonstatic nontype member of class X or of
2220 // a base class of X, the id-expression is transformed into a
2221 // class member access expression (5.2.5) using (*this) (9.3.2)
2222 // as the postfix-expression to the left of the '.' operator.
2223 DeclContext *Ctx = 0;
2224 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2225 Ctx = FD->getDeclContext();
2226 MemberType = FD->getType();
2227
2228 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2229 MemberType = RefType->getPointeeType();
2230 else if (!FD->isMutable())
2231 MemberType
2232 = Context.getQualifiedType(MemberType,
2233 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2234 } else {
2235 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2236 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2237 FunctionTemplateDecl *FunTmpl = 0;
2238 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2239 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2240
Douglas Gregord3319842009-10-24 04:59:53 +00002241 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002242 if (Method && !Method->isStatic()) {
2243 Ctx = Method->getParent();
2244 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2245 MemberType = Method->getType();
2246 else
2247 MemberType = Context.OverloadTy;
2248 break;
2249 }
2250 }
2251 }
2252
2253 if (!Ctx || !Ctx->isRecord())
2254 return false;
2255
2256 // Determine whether the declaration(s) we found are actually in a base
2257 // class. If not, this isn't an implicit member reference.
2258 ThisType = MD->getThisType(Context);
Douglas Gregor5897e092009-11-01 17:08:18 +00002259
2260 // If the type of "this" is dependent, we can't tell if the member is in a
2261 // base class or not, so treat this as a dependent implicit member reference.
2262 if (ThisType->isDependentType())
2263 return true;
2264
Douglas Gregor6493d9c2009-10-22 07:08:30 +00002265 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2266 QualType ClassType
2267 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2268 return Context.hasSameType(CtxType, ClassType) ||
2269 IsDerivedFrom(ClassType, CtxType);
2270}
2271