blob: 4188905fddec182179d3fb938da8626ce4a59f19 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
Sebastian Redlc42e1182008-11-11 11:37:55 +000025/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000026Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000027Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
28 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000029 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000030 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000031
32 if (isType)
33 // FIXME: Preserve type source info.
34 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
35
Chris Lattner572af492008-11-20 05:51:55 +000036 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCallf36e02d2009-10-09 21:13:30 +000037 LookupResult R;
38 LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
39 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000040 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000041 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000042 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000043
44 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
45
Douglas Gregorac7610d2009-06-22 20:57:11 +000046 if (!isType) {
47 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-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 Gregorac7610d2009-06-22 20:57:11 +000050 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregorac7610d2009-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 Kremenek6217b802009-07-29 21:53:49 +000058 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000059 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
60 if (RecordD->isPolymorphic())
61 isUnevaluatedOperand = false;
62 }
63 }
Mike Stump1eb44332009-09-09 15:08:12 +000064
Douglas Gregorac7610d2009-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 Stump1eb44332009-09-09 15:08:12 +000070
Sebastian Redlf53597f2009-03-15 17:47:39 +000071 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
72 TypeInfoType.withConst(),
73 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000074}
75
Steve Naroff1b273c42007-09-16 14:56:35 +000076/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000077Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000078Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000079 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000080 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000081 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
82 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000083}
Chris Lattner50dd2892008-02-26 00:51:44 +000084
Sebastian Redl6e8ed162009-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 Lattner50dd2892008-02-26 00:51:44 +000091/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000092Action::OwningExprResult
93Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-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 Kremenek6217b802009-07-29 21:53:49 +0000111 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000112 Ty = Ptr->getPointeeType();
113 isPointer = 1;
114 }
115 if (!isPointer || !Ty->isVoidType()) {
116 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000117 PDiag(isPointer ? diag::err_throw_incomplete_ptr
118 : diag::err_throw_incomplete)
119 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000120 return true;
121 }
122
123 // FIXME: Construct a temporary here.
124 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000125}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000126
Sebastian Redlf53597f2009-03-15 17:47:39 +0000127Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-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 Redlf53597f2009-03-15 17:47:39 +0000132 if (!isa<FunctionDecl>(CurContext))
133 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000134
135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
136 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 return Owned(new (Context) CXXThisExpr(ThisLoc,
138 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000139
Sebastian Redlf53597f2009-03-15 17:47:39 +0000140 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000141}
Argyrios Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000147Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000148Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
149 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000150 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000151 SourceLocation *CommaLocs,
152 SourceLocation RParenLoc) {
153 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000154 // FIXME: Preserve type source info.
155 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000156 unsigned NumExprs = exprs.size();
157 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000158 SourceLocation TyBeginLoc = TypeRange.getBegin();
159 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
160
Sebastian Redlf53597f2009-03-15 17:47:39 +0000161 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000162 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000164
165 return Owned(CXXUnresolvedConstructExpr::Create(Context,
166 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000167 LParenLoc,
168 Exprs, NumExprs,
169 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000170 }
171
Anders Carlssonbb60a502009-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 Jahanianf071e9b2009-10-23 21:01:39 +0000180
Anders Carlssonbb60a502009-08-27 03:53:50 +0000181 if (RequireNonAbstractType(TyBeginLoc, Ty,
182 diag::err_allocation_of_abstract_type))
183 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
185
Douglas Gregor506ae412009-01-16 18:33:17 +0000186 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-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 Carlssoncdb61972009-08-07 22:21:05 +0000192 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000193 CXXMethodDecl *Method = 0;
194 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
195 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 return ExprError();
Anders Carlsson0aebc812009-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 Jahanian4fc7ab32009-08-28 15:11:24 +0000207 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000208
209 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
210 Ty, TyBeginLoc, Kind,
211 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000212 }
213
Ted Kremenek6217b802009-07-29 21:53:49 +0000214 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000215 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000216
Mike Stump1eb44332009-09-09 15:08:12 +0000217 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000218 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000219 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
220
Douglas Gregor506ae412009-01-16 18:33:17 +0000221 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000222 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 TypeRange.getBegin(),
224 SourceRange(TypeRange.getBegin(),
225 RParenLoc),
226 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000227 IK_Direct,
228 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000229
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 if (!Constructor)
231 return ExprError();
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233 OwningExprResult Result =
234 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000235 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000236 if (Result.isInvalid())
237 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssone7624a72009-08-27 05:08:22 +0000239 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-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 Kyrtzidis987a14b2008-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 Redlf53597f2009-03-15 17:47:39 +0000251 return ExprError(Diag(CommaLocs[0],
252 diag::err_builtin_func_cast_more_than_one_arg)
253 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000254
255 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000256 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000257 // The expression T(), where T is a simple-type-specifier for a non-array
258 // complete object type or the (possibly cv-qualified) void type, creates an
259 // rvalue of the specified type, which is value-initialized.
260 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000261 exprs.release();
262 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000263}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000264
265
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000266/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
267/// @code new (memory) int[size][4] @endcode
268/// or
269/// @code ::new Foo(23, "hello") @endcode
270/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000271Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000272Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000274 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000275 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000277 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000278 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 // If the specified type is an array, unwrap it and save the expression.
280 if (D.getNumTypeObjects() > 0 &&
281 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
282 DeclaratorChunk &Chunk = D.getTypeObject(0);
283 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000284 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
285 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000286 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000287 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
288 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000289
290 if (ParenTypeId) {
291 // Can't have dynamic array size when the type-id is in parentheses.
292 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
293 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
294 !NumElts->isIntegerConstantExpr(Context)) {
295 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
296 << NumElts->getSourceRange();
297 return ExprError();
298 }
299 }
300
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000301 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000302 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000303 }
304
Douglas Gregor043cad22009-09-11 00:18:58 +0000305 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000306 if (ArraySize) {
307 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000308 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
309 break;
310
311 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
312 if (Expr *NumElts = (Expr *)Array.NumElts) {
313 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
314 !NumElts->isIntegerConstantExpr(Context)) {
315 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
316 << NumElts->getSourceRange();
317 return ExprError();
318 }
319 }
320 }
321 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000322
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000323 //FIXME: Store DeclaratorInfo in CXXNew expression.
324 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000325 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000326 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000327 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000328
Mike Stump1eb44332009-09-09 15:08:12 +0000329 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000330 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000331 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000332 PlacementRParen,
333 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000334 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000335 D.getSourceRange().getBegin(),
336 D.getSourceRange(),
337 Owned(ArraySize),
338 ConstructorLParen,
339 move(ConstructorArgs),
340 ConstructorRParen);
341}
342
Mike Stump1eb44332009-09-09 15:08:12 +0000343Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000344Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
345 SourceLocation PlacementLParen,
346 MultiExprArg PlacementArgs,
347 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000348 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000349 QualType AllocType,
350 SourceLocation TypeLoc,
351 SourceRange TypeRange,
352 ExprArg ArraySizeE,
353 SourceLocation ConstructorLParen,
354 MultiExprArg ConstructorArgs,
355 SourceLocation ConstructorRParen) {
356 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000357 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000358
Douglas Gregor3433cf72009-05-21 00:00:09 +0000359 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000360
361 // That every array dimension except the first is constant was already
362 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000363
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
365 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000366 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000367 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000368 QualType SizeType = ArraySize->getType();
369 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000370 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
371 diag::err_array_size_not_integral)
372 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000373 // Let's see if this is a constant < 0. If so, we reject it out of hand.
374 // We don't care about special rules, so we tell the machinery it's not
375 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000376 if (!ArraySize->isValueDependent()) {
377 llvm::APSInt Value;
378 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
379 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000380 llvm::APInt::getNullValue(Value.getBitWidth()),
381 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
383 diag::err_typecheck_negative_array_size)
384 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000385 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000386 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000387
Eli Friedman73c39ab2009-10-20 08:27:19 +0000388 ImpCastExprToType(ArraySize, Context.getSizeType(),
389 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000390 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000391
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000392 FunctionDecl *OperatorNew = 0;
393 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000394 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
395 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000396
Sebastian Redl28507842009-02-26 14:39:58 +0000397 if (!AllocType->isDependentType() &&
398 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
399 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000400 SourceRange(PlacementLParen, PlacementRParen),
401 UseGlobal, AllocType, ArraySize, PlaceArgs,
402 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000403 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000404
405 bool Init = ConstructorLParen.isValid();
406 // --- Choosing a constructor ---
407 // C++ 5.3.4p15
408 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
409 // the object is not initialized. If the object, or any part of it, is
410 // const-qualified, it's an error.
411 // 2) If T is a POD and there's an empty initializer, the object is value-
412 // initialized.
413 // 3) If T is a POD and there's one initializer argument, the object is copy-
414 // constructed.
415 // 4) If T is a POD and there's more initializer arguments, it's an error.
416 // 5) If T is not a POD, the initializer arguments are used as constructor
417 // arguments.
418 //
419 // Or by the C++0x formulation:
420 // 1) If there's no initializer, the object is default-initialized according
421 // to C++0x rules.
422 // 2) Otherwise, the object is direct-initialized.
423 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000424 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000425 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000426 unsigned NumConsArgs = ConstructorArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000427
428 if (AllocType->isDependentType() ||
429 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000430 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000431 } else if ((RT = AllocType->getAs<RecordType>()) &&
432 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000433 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
434
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000435 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000436 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000437 TypeLoc,
438 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000439 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000440 NumConsArgs != 0 ? IK_Direct : IK_Default,
441 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000442 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000444
445 // Take the converted constructor arguments and use them for the new
446 // expression.
447 NumConsArgs = ConvertedConstructorArgs.size();
448 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000449 } else {
450 if (!Init) {
451 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000452 if (AllocType.isConstQualified())
453 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000454 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000455 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000456 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000457 } else if (NumConsArgs == 1) {
458 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000459 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000460 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000461 DeclarationName() /*AllocType.getAsString()*/,
462 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000463 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000464 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return ExprError(Diag(StartLoc,
466 diag::err_builtin_direct_init_more_than_one_arg)
467 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000468 }
469 }
470
471 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000472
Sebastian Redlf53597f2009-03-15 17:47:39 +0000473 PlacementArgs.release();
474 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000475 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000476 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000477 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000478 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000479 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000480}
481
482/// CheckAllocatedType - Checks that a type is suitable as the allocated type
483/// in a new-expression.
484/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000485bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000486 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000487 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
488 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000489 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000490 return Diag(Loc, diag::err_bad_new_type)
491 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000492 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000493 return Diag(Loc, diag::err_bad_new_type)
494 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000495 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000496 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000497 PDiag(diag::err_new_incomplete_type)
498 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000500 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000501 diag::err_allocation_of_abstract_type))
502 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000503
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000504 return false;
505}
506
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000507/// FindAllocationFunctions - Finds the overloads of operator new and delete
508/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000509bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
510 bool UseGlobal, QualType AllocType,
511 bool IsArray, Expr **PlaceArgs,
512 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000513 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000514 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000515 // --- Choosing an allocation function ---
516 // C++ 5.3.4p8 - 14 & 18
517 // 1) If UseGlobal is true, only look in the global scope. Else, also look
518 // in the scope of the allocated class.
519 // 2) If an array size is given, look for operator new[], else look for
520 // operator new.
521 // 3) The first argument is always size_t. Append the arguments from the
522 // placement form.
523 // FIXME: Also find the appropriate delete operator.
524
525 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
526 // We don't care about the actual value of this argument.
527 // FIXME: Should the Sema create the expression and embed it in the syntax
528 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000529 IntegerLiteral Size(llvm::APInt::getNullValue(
530 Context.Target.getPointerWidth(0)),
531 Context.getSizeType(),
532 SourceLocation());
533 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000534 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
535
536 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
537 IsArray ? OO_Array_New : OO_New);
538 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000539 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000540 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000541 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000542 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000543 AllocArgs.size(), Record, /*AllowMissing=*/true,
544 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000545 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000546 }
547 if (!OperatorNew) {
548 // Didn't find a member overload. Look for a global one.
549 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000550 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000551 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000552 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
553 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000554 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000555 }
556
Anders Carlssond9583892009-05-31 20:26:12 +0000557 // FindAllocationOverload can change the passed in arguments, so we need to
558 // copy them back.
559 if (NumPlaceArgs > 0)
560 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000562 return false;
563}
564
Sebastian Redl7f662392008-12-04 22:20:51 +0000565/// FindAllocationOverload - Find an fitting overload for the allocation
566/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000567bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
568 DeclarationName Name, Expr** Args,
569 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000570 bool AllowMissing, FunctionDecl *&Operator) {
John McCallf36e02d2009-10-09 21:13:30 +0000571 LookupResult R;
572 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
573 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000574 if (AllowMissing)
575 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000576 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000577 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000578 }
579
John McCallf36e02d2009-10-09 21:13:30 +0000580 // FIXME: handle ambiguity
581
Sebastian Redl7f662392008-12-04 22:20:51 +0000582 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000583 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
584 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000585 // Even member operator new/delete are implicitly treated as
586 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000587 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000588 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
589 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000590 continue;
591 }
592
593 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000594 }
595
596 // Do the resolution.
597 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000598 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 case OR_Success: {
600 // Got one!
601 FunctionDecl *FnDecl = Best->Function;
602 // The first argument is size_t, and the first parameter must be size_t,
603 // too. This is checked on declaration and can be assumed. (It can't be
604 // asserted on, though, since invalid decls are left in there.)
Douglas Gregor90916562009-09-29 18:16:17 +0000605 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000606 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000607 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000608 FnDecl->getParamDecl(i)->getType(),
609 "passing"))
610 return true;
611 }
612 Operator = FnDecl;
613 return false;
614 }
615
616 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000617 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000618 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000619 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
620 return true;
621
622 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000623 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000624 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000625 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
626 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000627
628 case OR_Deleted:
629 Diag(StartLoc, diag::err_ovl_deleted_call)
630 << Best->Function->isDeleted()
631 << Name << Range;
632 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
633 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 }
635 assert(false && "Unreachable, bad result from BestViableFunction");
636 return true;
637}
638
639
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000640/// DeclareGlobalNewDelete - Declare the global forms of operator new and
641/// delete. These are:
642/// @code
643/// void* operator new(std::size_t) throw(std::bad_alloc);
644/// void* operator new[](std::size_t) throw(std::bad_alloc);
645/// void operator delete(void *) throw();
646/// void operator delete[](void *) throw();
647/// @endcode
648/// Note that the placement and nothrow forms of new are *not* implicitly
649/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000650void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000651 if (GlobalNewDeleteDeclared)
652 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000653
654 // C++ [basic.std.dynamic]p2:
655 // [...] The following allocation and deallocation functions (18.4) are
656 // implicitly declared in global scope in each translation unit of a
657 // program
658 //
659 // void* operator new(std::size_t) throw(std::bad_alloc);
660 // void* operator new[](std::size_t) throw(std::bad_alloc);
661 // void operator delete(void*) throw();
662 // void operator delete[](void*) throw();
663 //
664 // These implicit declarations introduce only the function names operator
665 // new, operator new[], operator delete, operator delete[].
666 //
667 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
668 // "std" or "bad_alloc" as necessary to form the exception specification.
669 // However, we do not make these implicit declarations visible to name
670 // lookup.
671 if (!StdNamespace) {
672 // The "std" namespace has not yet been defined, so build one implicitly.
673 StdNamespace = NamespaceDecl::Create(Context,
674 Context.getTranslationUnitDecl(),
675 SourceLocation(),
676 &PP.getIdentifierTable().get("std"));
677 StdNamespace->setImplicit(true);
678 }
679
680 if (!StdBadAlloc) {
681 // The "std::bad_alloc" class has not yet been declared, so build it
682 // implicitly.
683 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
684 StdNamespace,
685 SourceLocation(),
686 &PP.getIdentifierTable().get("bad_alloc"),
687 SourceLocation(), 0);
688 StdBadAlloc->setImplicit(true);
689 }
690
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000691 GlobalNewDeleteDeclared = true;
692
693 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
694 QualType SizeT = Context.getSizeType();
695
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000696 DeclareGlobalAllocationFunction(
697 Context.DeclarationNames.getCXXOperatorName(OO_New),
698 VoidPtr, SizeT);
699 DeclareGlobalAllocationFunction(
700 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
701 VoidPtr, SizeT);
702 DeclareGlobalAllocationFunction(
703 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
704 Context.VoidTy, VoidPtr);
705 DeclareGlobalAllocationFunction(
706 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
707 Context.VoidTy, VoidPtr);
708}
709
710/// DeclareGlobalAllocationFunction - Declares a single implicit global
711/// allocation function if it doesn't already exist.
712void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000713 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000714 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
715
716 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000717 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000718 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000719 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000720 Alloc != AllocEnd; ++Alloc) {
721 // FIXME: Do we need to check for default arguments here?
722 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
723 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000724 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000725 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000726 }
727 }
728
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000729 QualType BadAllocType;
730 bool HasBadAllocExceptionSpec
731 = (Name.getCXXOverloadedOperator() == OO_New ||
732 Name.getCXXOverloadedOperator() == OO_Array_New);
733 if (HasBadAllocExceptionSpec) {
734 assert(StdBadAlloc && "Must have std::bad_alloc declared");
735 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
736 }
737
738 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
739 true, false,
740 HasBadAllocExceptionSpec? 1 : 0,
741 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000742 FunctionDecl *Alloc =
743 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000744 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000745 Alloc->setImplicit();
746 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000747 0, Argument, /*DInfo=*/0,
748 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000749 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000750
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000751 // FIXME: Also add this declaration to the IdentifierResolver, but
752 // make sure it is at the end of the chain to coincide with the
753 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000754 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000755}
756
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000757/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
758/// @code ::delete ptr; @endcode
759/// or
760/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000761Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000762Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000763 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000764 // C++ [expr.delete]p1:
765 // The operand shall have a pointer type, or a class type having a single
766 // conversion function to a pointer type. The result has type void.
767 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000768 // DR599 amends "pointer type" to "pointer to object type" in both cases.
769
Anders Carlssond67c4c32009-08-16 20:29:29 +0000770 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000773 if (!Ex->isTypeDependent()) {
774 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000775
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000776 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000777 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000778 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
779 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000780 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000781
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000782 for (OverloadedFunctionDecl::function_iterator
783 Func = Conversions->function_begin(),
784 FuncEnd = Conversions->function_end();
785 Func != FuncEnd; ++Func) {
786 // Skip over templated conversion functions; they aren't considered.
787 if (isa<FunctionTemplateDecl>(*Func))
788 continue;
789
790 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
791
792 QualType ConvType = Conv->getConversionType().getNonReferenceType();
793 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
794 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000795 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000796 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000797 if (ObjectPtrConversions.size() == 1) {
798 // We have a single conversion to a pointer-to-object type. Perform
799 // that conversion.
800 Operand.release();
801 if (!PerformImplicitConversion(Ex,
802 ObjectPtrConversions.front()->getConversionType(),
803 "converting")) {
804 Operand = Owned(Ex);
805 Type = Ex->getType();
806 }
807 }
808 else if (ObjectPtrConversions.size() > 1) {
809 Diag(StartLoc, diag::err_ambiguous_delete_operand)
810 << Type << Ex->getSourceRange();
811 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
812 CXXConversionDecl *Conv = ObjectPtrConversions[i];
813 Diag(Conv->getLocation(), diag::err_ovl_candidate);
814 }
815 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000816 }
Sebastian Redl28507842009-02-26 14:39:58 +0000817 }
818
Sebastian Redlf53597f2009-03-15 17:47:39 +0000819 if (!Type->isPointerType())
820 return ExprError(Diag(StartLoc, diag::err_delete_operand)
821 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000822
Ted Kremenek6217b802009-07-29 21:53:49 +0000823 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000824 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000825 return ExprError(Diag(StartLoc, diag::err_delete_operand)
826 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000827 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000828 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000829 PDiag(diag::warn_delete_incomplete)
830 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000831 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000832
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000833 // C++ [expr.delete]p2:
834 // [Note: a pointer to a const type can be the operand of a
835 // delete-expression; it is not necessary to cast away the constness
836 // (5.2.11) of the pointer expression before it is used as the operand
837 // of the delete-expression. ]
838 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
839 CastExpr::CK_NoOp);
840
841 // Update the operand.
842 Operand.take();
843 Operand = ExprArg(*this, Ex);
844
Anders Carlssond67c4c32009-08-16 20:29:29 +0000845 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
846 ArrayForm ? OO_Array_Delete : OO_Delete);
847
848 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000849 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000850 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
Douglas Gregor90916562009-09-29 18:16:17 +0000851
852 // Try to find operator delete/operator delete[] in class scope.
John McCallf36e02d2009-10-09 21:13:30 +0000853 LookupResult Found;
854 LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
Douglas Gregor90916562009-09-29 18:16:17 +0000855 // FIXME: Diagnose ambiguity properly
856 assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
857 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
858 F != FEnd; ++F) {
859 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
860 if (Delete->isUsualDeallocationFunction()) {
861 OperatorDelete = Delete;
862 break;
863 }
864 }
865
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000866 if (!Record->hasTrivialDestructor())
867 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000868 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000869 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000870 }
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Anders Carlssond67c4c32009-08-16 20:29:29 +0000872 if (!OperatorDelete) {
873 // Didn't find a member overload. Look for a global one.
874 DeclareGlobalNewDelete();
875 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000876 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000877 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000878 OperatorDelete))
879 return ExprError();
880 }
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Sebastian Redl28507842009-02-26 14:39:58 +0000882 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000883 }
884
Sebastian Redlf53597f2009-03-15 17:47:39 +0000885 Operand.release();
886 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000887 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000888}
889
890
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000891/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
892/// C++ if/switch/while/for statement.
893/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000894Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000895Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
896 Declarator &D,
897 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000898 ExprArg AssignExprVal) {
899 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000900
901 // C++ 6.4p2:
902 // The declarator shall not specify a function or an array.
903 // The type-specifier-seq shall not contain typedef and shall not declare a
904 // new class or enumeration.
905
906 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
907 "Parser allowed 'typedef' as storage class of condition decl.");
908
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000909 // FIXME: Store DeclaratorInfo in the expression.
910 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000911 TagDecl *OwnedTag = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000912 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000914 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
915 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
916 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000917 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
918 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000919 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000920 Diag(StartLoc, diag::err_invalid_use_of_array_type)
921 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000922 } else if (OwnedTag && OwnedTag->isDefinition()) {
923 // The type-specifier-seq shall not declare a new class or enumeration.
924 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000925 }
926
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000927 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000928 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000929 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000930 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000931
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000932 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000933 // We know that the decl had to be a VarDecl because that is the only type of
934 // decl that can be assigned and the grammar requires an '='.
935 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
936 VD->setDeclaredInCondition(true);
937 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000938}
939
940/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
941bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
942 // C++ 6.4p4:
943 // The value of a condition that is an initialized declaration in a statement
944 // other than a switch statement is the value of the declared variable
945 // implicitly converted to type bool. If that conversion is ill-formed, the
946 // program is ill-formed.
947 // The value of a condition that is an expression is the value of the
948 // expression, implicitly converted to bool.
949 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000950 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000951}
Douglas Gregor77a52232008-09-12 00:47:35 +0000952
953/// Helper function to determine whether this is the (deprecated) C++
954/// conversion from a string literal to a pointer to non-const char or
955/// non-const wchar_t (for narrow and wide string literals,
956/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000957bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000958Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
959 // Look inside the implicit cast, if it exists.
960 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
961 From = Cast->getSubExpr();
962
963 // A string literal (2.13.4) that is not a wide string literal can
964 // be converted to an rvalue of type "pointer to char"; a wide
965 // string literal can be converted to an rvalue of type "pointer
966 // to wchar_t" (C++ 4.2p2).
967 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000968 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000969 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000970 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000971 // This conversion is considered only when there is an
972 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +0000973 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +0000974 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
975 (!StrLit->isWide() &&
976 (ToPointeeType->getKind() == BuiltinType::Char_U ||
977 ToPointeeType->getKind() == BuiltinType::Char_S))))
978 return true;
979 }
980
981 return false;
982}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000983
984/// PerformImplicitConversion - Perform an implicit conversion of the
985/// expression From to the type ToType. Returns true if there was an
986/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000987/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000988/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000989/// explicit user-defined conversions are permitted. @p Elidable should be true
990/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
991/// resolution works differently in that case.
992bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000993Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000994 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +0000995 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +0000996 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +0000997 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
998 Elidable, ICS);
999}
1000
1001bool
1002Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1003 const char *Flavor, bool AllowExplicit,
1004 bool Elidable,
1005 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001006 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1007 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001008 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001009 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001010 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001011 /*ForceRValue=*/true,
1012 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001013 }
1014 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001015 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001016 /*SuppressUserConversions=*/false,
1017 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001018 /*ForceRValue=*/false,
1019 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001020 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001021 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1022}
1023
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001024/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1025/// for the derived to base conversion of the expression 'From'. All
1026/// necessary information is passed in ICS.
1027bool
1028Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1029 const ImplicitConversionSequence& ICS,
1030 const char *Flavor) {
1031 QualType BaseType =
1032 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1033 // Must do additional defined to base conversion.
1034 QualType DerivedType =
1035 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1036
1037 From = new (Context) ImplicitCastExpr(
1038 DerivedType.getNonReferenceType(),
1039 CastKind,
1040 From,
1041 DerivedType->isLValueReferenceType());
1042 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1043 CastExpr::CK_DerivedToBase, From,
1044 BaseType->isLValueReferenceType());
1045 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1046 OwningExprResult FromResult =
1047 BuildCXXConstructExpr(
1048 ICS.UserDefined.After.CopyConstructor->getLocation(),
1049 BaseType,
1050 ICS.UserDefined.After.CopyConstructor,
1051 MultiExprArg(*this, (void **)&From, 1));
1052 if (FromResult.isInvalid())
1053 return true;
1054 From = FromResult.takeAs<Expr>();
1055 return false;
1056}
1057
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001058/// PerformImplicitConversion - Perform an implicit conversion of the
1059/// expression From to the type ToType using the pre-computed implicit
1060/// conversion sequence ICS. Returns true if there was an error, false
1061/// otherwise. The expression From is replaced with the converted
1062/// expression. Flavor is the kind of conversion we're performing,
1063/// used in the error message.
1064bool
1065Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1066 const ImplicitConversionSequence &ICS,
1067 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001068 switch (ICS.ConversionKind) {
1069 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001070 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001071 return true;
1072 break;
1073
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001074 case ImplicitConversionSequence::UserDefinedConversion: {
1075
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001076 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1077 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001078 QualType BeforeToType;
1079 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001080 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001081
1082 // If the user-defined conversion is specified by a conversion function,
1083 // the initial standard conversion sequence converts the source type to
1084 // the implicit object parameter of the conversion function.
1085 BeforeToType = Context.getTagDeclType(Conv->getParent());
1086 } else if (const CXXConstructorDecl *Ctor =
1087 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001088 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001089 // Do no conversion if dealing with ... for the first conversion.
1090 if (!ICS.UserDefined.EllipsisConversion)
1091 // If the user-defined conversion is specified by a constructor, the
1092 // initial standard conversion sequence converts the source type to the
1093 // type required by the argument of the constructor
1094 BeforeToType = Ctor->getParamDecl(0)->getType();
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001095 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001096 else
1097 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001098 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001099 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001100 if (PerformImplicitConversion(From, BeforeToType,
1101 ICS.UserDefined.Before, "converting"))
1102 return true;
1103 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001104
Anders Carlsson0aebc812009-09-09 21:33:21 +00001105 OwningExprResult CastArg
1106 = BuildCXXCastArgument(From->getLocStart(),
1107 ToType.getNonReferenceType(),
1108 CastKind, cast<CXXMethodDecl>(FD),
1109 Owned(From));
1110
1111 if (CastArg.isInvalid())
1112 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001113
1114 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1115 ICS.UserDefined.After.CopyConstructor) {
1116 From = CastArg.takeAs<Expr>();
1117 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1118 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001119
1120 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1121 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1122 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001123
Anders Carlsson626c2d62009-09-15 05:49:31 +00001124 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001125 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001126 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001127 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001128 }
1129
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001130 case ImplicitConversionSequence::EllipsisConversion:
1131 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001132 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001133
1134 case ImplicitConversionSequence::BadConversion:
1135 return true;
1136 }
1137
1138 // Everything went well.
1139 return false;
1140}
1141
1142/// PerformImplicitConversion - Perform an implicit conversion of the
1143/// expression From to the type ToType by following the standard
1144/// conversion sequence SCS. Returns true if there was an error, false
1145/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001146/// expression. Flavor is the context in which we're performing this
1147/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001148bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001149Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001150 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001151 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001152 // Overall FIXME: we are recomputing too many types here and doing far too
1153 // much extra work. What this means is that we need to keep track of more
1154 // information that is computed when we try the implicit conversion initially,
1155 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001156 QualType FromType = From->getType();
1157
Douglas Gregor225c41e2008-11-03 19:09:14 +00001158 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001159 // FIXME: When can ToType be a reference type?
1160 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001161 if (SCS.Second == ICK_Derived_To_Base) {
1162 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1163 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1164 MultiExprArg(*this, (void **)&From, 1),
1165 /*FIXME:ConstructLoc*/SourceLocation(),
1166 ConstructorArgs))
1167 return true;
1168 OwningExprResult FromResult =
1169 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1170 ToType, SCS.CopyConstructor,
1171 move_arg(ConstructorArgs));
1172 if (FromResult.isInvalid())
1173 return true;
1174 From = FromResult.takeAs<Expr>();
1175 return false;
1176 }
Mike Stump1eb44332009-09-09 15:08:12 +00001177 OwningExprResult FromResult =
1178 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1179 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001180 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001182 if (FromResult.isInvalid())
1183 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001185 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001186 return false;
1187 }
1188
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001189 // Perform the first implicit conversion.
1190 switch (SCS.First) {
1191 case ICK_Identity:
1192 case ICK_Lvalue_To_Rvalue:
1193 // Nothing to do.
1194 break;
1195
1196 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001197 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001198 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001199 break;
1200
1201 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001202 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001203 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1204 if (!Fn)
1205 return true;
1206
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001207 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1208 return true;
1209
Anders Carlsson96ad5332009-10-21 17:16:23 +00001210 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001211 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001212
Sebastian Redl759986e2009-10-17 20:50:27 +00001213 // If there's already an address-of operator in the expression, we have
1214 // the right type already, and the code below would just introduce an
1215 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001216 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001217 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001218 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001219 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001220 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001221 break;
1222
1223 default:
1224 assert(false && "Improper first standard conversion");
1225 break;
1226 }
1227
1228 // Perform the second implicit conversion
1229 switch (SCS.Second) {
1230 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001231 // If both sides are functions (or pointers/references to them), there could
1232 // be incompatible exception declarations.
1233 if (CheckExceptionSpecCompatibility(From, ToType))
1234 return true;
1235 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001236 break;
1237
1238 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001239 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001240 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1241 break;
1242
1243 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001244 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001245 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1246 break;
1247
1248 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001249 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001250 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1251 break;
1252
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001253 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001254 if (ToType->isFloatingType())
1255 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1256 else
1257 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1258 break;
1259
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001260 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001261 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1262 break;
1263
Douglas Gregorf9201e02009-02-11 23:02:49 +00001264 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001265 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001266 break;
1267
Anders Carlsson61faec12009-09-12 04:46:44 +00001268 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001269 if (SCS.IncompatibleObjC) {
1270 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001271 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001272 diag::ext_typecheck_convert_incompatible_pointer)
1273 << From->getType() << ToType << Flavor
1274 << From->getSourceRange();
1275 }
1276
Anders Carlsson61faec12009-09-12 04:46:44 +00001277
1278 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1279 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001280 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001281 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001282 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001283 }
1284
1285 case ICK_Pointer_Member: {
1286 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1287 if (CheckMemberPointerConversion(From, ToType, Kind))
1288 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001289 if (CheckExceptionSpecCompatibility(From, ToType))
1290 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001291 ImpCastExprToType(From, ToType, Kind);
1292 break;
1293 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001294 case ICK_Boolean_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001295 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001296 break;
1297
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001298 case ICK_Derived_To_Base:
1299 if (CheckDerivedToBaseConversion(From->getType(),
1300 ToType.getNonReferenceType(),
1301 From->getLocStart(),
1302 From->getSourceRange()))
1303 return true;
1304 ImpCastExprToType(From, ToType.getNonReferenceType(),
1305 CastExpr::CK_DerivedToBase);
1306 break;
1307
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001308 default:
1309 assert(false && "Improper second standard conversion");
1310 break;
1311 }
1312
1313 switch (SCS.Third) {
1314 case ICK_Identity:
1315 // Nothing to do.
1316 break;
1317
1318 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001319 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1320 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001321 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001322 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001323 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001324 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001325
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001326 default:
1327 assert(false && "Improper second standard conversion");
1328 break;
1329 }
1330
1331 return false;
1332}
1333
Sebastian Redl64b45f72009-01-05 20:52:13 +00001334Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1335 SourceLocation KWLoc,
1336 SourceLocation LParen,
1337 TypeTy *Ty,
1338 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001339 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001341 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1342 // all traits except __is_class, __is_enum and __is_union require a the type
1343 // to be complete.
1344 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001345 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001346 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001347 return ExprError();
1348 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001349
1350 // There is no point in eagerly computing the value. The traits are designed
1351 // to be used from type trait templates, so Ty will be a template parameter
1352 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001353 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1354 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001355}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001356
1357QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001358 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001359 const char *OpSpelling = isIndirect ? "->*" : ".*";
1360 // C++ 5.5p2
1361 // The binary operator .* [p3: ->*] binds its second operand, which shall
1362 // be of type "pointer to member of T" (where T is a completely-defined
1363 // class type) [...]
1364 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001365 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001366 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001367 Diag(Loc, diag::err_bad_memptr_rhs)
1368 << OpSpelling << RType << rex->getSourceRange();
1369 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001370 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001371
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001372 QualType Class(MemPtr->getClass(), 0);
1373
1374 // C++ 5.5p2
1375 // [...] to its first operand, which shall be of class T or of a class of
1376 // which T is an unambiguous and accessible base class. [p3: a pointer to
1377 // such a class]
1378 QualType LType = lex->getType();
1379 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001380 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001381 LType = Ptr->getPointeeType().getNonReferenceType();
1382 else {
1383 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001384 << OpSpelling << 1 << LType
1385 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001386 return QualType();
1387 }
1388 }
1389
1390 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1391 Context.getCanonicalType(LType).getUnqualifiedType()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001392 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1393 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001394 // FIXME: Would it be useful to print full ambiguity paths, or is that
1395 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001396 if (!IsDerivedFrom(LType, Class, Paths) ||
1397 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001398 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001399 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001400 << (int)isIndirect << lex->getType() <<
1401 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001402 return QualType();
1403 }
1404 }
1405
1406 // C++ 5.5p2
1407 // The result is an object or a function of the type specified by the
1408 // second operand.
1409 // The cv qualifiers are the union of those in the pointer and the left side,
1410 // in accordance with 5.5p5 and 5.2.5.
1411 // FIXME: This returns a dereferenced member function pointer as a normal
1412 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001413 // calling them. There's also a GCC extension to get a function pointer to the
1414 // thing, which is another complication, because this type - unlike the type
1415 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001416 // argument.
1417 // We probably need a "MemberFunctionClosureType" or something like that.
1418 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001419 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001420 return Result;
1421}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001422
1423/// \brief Get the target type of a standard or user-defined conversion.
1424static QualType TargetType(const ImplicitConversionSequence &ICS) {
1425 assert((ICS.ConversionKind ==
1426 ImplicitConversionSequence::StandardConversion ||
1427 ICS.ConversionKind ==
1428 ImplicitConversionSequence::UserDefinedConversion) &&
1429 "function only valid for standard or user-defined conversions");
1430 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1431 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1432 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1433}
1434
1435/// \brief Try to convert a type to another according to C++0x 5.16p3.
1436///
1437/// This is part of the parameter validation for the ? operator. If either
1438/// value operand is a class type, the two operands are attempted to be
1439/// converted to each other. This function does the conversion in one direction.
1440/// It emits a diagnostic and returns true only if it finds an ambiguous
1441/// conversion.
1442static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1443 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001444 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001445 // C++0x 5.16p3
1446 // The process for determining whether an operand expression E1 of type T1
1447 // can be converted to match an operand expression E2 of type T2 is defined
1448 // as follows:
1449 // -- If E2 is an lvalue:
1450 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1451 // E1 can be converted to match E2 if E1 can be implicitly converted to
1452 // type "lvalue reference to T2", subject to the constraint that in the
1453 // conversion the reference must bind directly to E1.
1454 if (!Self.CheckReferenceInit(From,
1455 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001456 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001457 /*SuppressUserConversions=*/false,
1458 /*AllowExplicit=*/false,
1459 /*ForceRValue=*/false,
1460 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001461 {
1462 assert((ICS.ConversionKind ==
1463 ImplicitConversionSequence::StandardConversion ||
1464 ICS.ConversionKind ==
1465 ImplicitConversionSequence::UserDefinedConversion) &&
1466 "expected a definite conversion");
1467 bool DirectBinding =
1468 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1469 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1470 if (DirectBinding)
1471 return false;
1472 }
1473 }
1474 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1475 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1476 // -- if E1 and E2 have class type, and the underlying class types are
1477 // the same or one is a base class of the other:
1478 QualType FTy = From->getType();
1479 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001480 const RecordType *FRec = FTy->getAs<RecordType>();
1481 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001482 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1483 if (FRec && TRec && (FRec == TRec ||
1484 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1485 // E1 can be converted to match E2 if the class of T2 is the
1486 // same type as, or a base class of, the class of T1, and
1487 // [cv2 > cv1].
1488 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1489 // Could still fail if there's no copy constructor.
1490 // FIXME: Is this a hard error then, or just a conversion failure? The
1491 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001492 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001493 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001494 /*ForceRValue=*/false,
1495 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001496 }
1497 } else {
1498 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1499 // implicitly converted to the type that expression E2 would have
1500 // if E2 were converted to an rvalue.
1501 // First find the decayed type.
1502 if (TTy->isFunctionType())
1503 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001504 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001505 TTy = Self.Context.getArrayDecayedType(TTy);
1506
1507 // Now try the implicit conversion.
1508 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001509 ICS = Self.TryImplicitConversion(From, TTy,
1510 /*SuppressUserConversions=*/false,
1511 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001512 /*ForceRValue=*/false,
1513 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001514 }
1515 return false;
1516}
1517
1518/// \brief Try to find a common type for two according to C++0x 5.16p5.
1519///
1520/// This is part of the parameter validation for the ? operator. If either
1521/// value operand is a class type, overload resolution is used to find a
1522/// conversion to a common type.
1523static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1524 SourceLocation Loc) {
1525 Expr *Args[2] = { LHS, RHS };
1526 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001527 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001528
1529 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001530 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001531 case Sema::OR_Success:
1532 // We found a match. Perform the conversions on the arguments and move on.
1533 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1534 Best->Conversions[0], "converting") ||
1535 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1536 Best->Conversions[1], "converting"))
1537 break;
1538 return false;
1539
1540 case Sema::OR_No_Viable_Function:
1541 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1542 << LHS->getType() << RHS->getType()
1543 << LHS->getSourceRange() << RHS->getSourceRange();
1544 return true;
1545
1546 case Sema::OR_Ambiguous:
1547 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1548 << LHS->getType() << RHS->getType()
1549 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001550 // FIXME: Print the possible common types by printing the return types of
1551 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001552 break;
1553
1554 case Sema::OR_Deleted:
1555 assert(false && "Conditional operator has only built-in overloads");
1556 break;
1557 }
1558 return true;
1559}
1560
Sebastian Redl76458502009-04-17 16:30:52 +00001561/// \brief Perform an "extended" implicit conversion as returned by
1562/// TryClassUnification.
1563///
1564/// TryClassUnification generates ICSs that include reference bindings.
1565/// PerformImplicitConversion is not suitable for this; it chokes if the
1566/// second part of a standard conversion is ICK_DerivedToBase. This function
1567/// handles the reference binding specially.
1568static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001569 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001570 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1571 ICS.Standard.ReferenceBinding) {
1572 assert(ICS.Standard.DirectBinding &&
1573 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001574 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1575 // redoing all the work.
1576 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001577 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001578 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001579 /*SuppressUserConversions=*/false,
1580 /*AllowExplicit=*/false,
1581 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001582 }
1583 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1584 ICS.UserDefined.After.ReferenceBinding) {
1585 assert(ICS.UserDefined.After.DirectBinding &&
1586 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001587 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001588 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001589 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001590 /*SuppressUserConversions=*/false,
1591 /*AllowExplicit=*/false,
1592 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001593 }
1594 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1595 return true;
1596 return false;
1597}
1598
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001599/// \brief Check the operands of ?: under C++ semantics.
1600///
1601/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1602/// extension. In this case, LHS == Cond. (But they're not aliases.)
1603QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1604 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001605 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1606 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001607
1608 // C++0x 5.16p1
1609 // The first expression is contextually converted to bool.
1610 if (!Cond->isTypeDependent()) {
1611 if (CheckCXXBooleanCondition(Cond))
1612 return QualType();
1613 }
1614
1615 // Either of the arguments dependent?
1616 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1617 return Context.DependentTy;
1618
John McCallb13c87f2009-11-05 09:23:39 +00001619 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1620
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001621 // C++0x 5.16p2
1622 // If either the second or the third operand has type (cv) void, ...
1623 QualType LTy = LHS->getType();
1624 QualType RTy = RHS->getType();
1625 bool LVoid = LTy->isVoidType();
1626 bool RVoid = RTy->isVoidType();
1627 if (LVoid || RVoid) {
1628 // ... then the [l2r] conversions are performed on the second and third
1629 // operands ...
1630 DefaultFunctionArrayConversion(LHS);
1631 DefaultFunctionArrayConversion(RHS);
1632 LTy = LHS->getType();
1633 RTy = RHS->getType();
1634
1635 // ... and one of the following shall hold:
1636 // -- The second or the third operand (but not both) is a throw-
1637 // expression; the result is of the type of the other and is an rvalue.
1638 bool LThrow = isa<CXXThrowExpr>(LHS);
1639 bool RThrow = isa<CXXThrowExpr>(RHS);
1640 if (LThrow && !RThrow)
1641 return RTy;
1642 if (RThrow && !LThrow)
1643 return LTy;
1644
1645 // -- Both the second and third operands have type void; the result is of
1646 // type void and is an rvalue.
1647 if (LVoid && RVoid)
1648 return Context.VoidTy;
1649
1650 // Neither holds, error.
1651 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1652 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1653 << LHS->getSourceRange() << RHS->getSourceRange();
1654 return QualType();
1655 }
1656
1657 // Neither is void.
1658
1659 // C++0x 5.16p3
1660 // Otherwise, if the second and third operand have different types, and
1661 // either has (cv) class type, and attempt is made to convert each of those
1662 // operands to the other.
1663 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1664 (LTy->isRecordType() || RTy->isRecordType())) {
1665 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1666 // These return true if a single direction is already ambiguous.
1667 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1668 return QualType();
1669 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1670 return QualType();
1671
1672 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1673 ImplicitConversionSequence::BadConversion;
1674 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1675 ImplicitConversionSequence::BadConversion;
1676 // If both can be converted, [...] the program is ill-formed.
1677 if (HaveL2R && HaveR2L) {
1678 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1679 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1680 return QualType();
1681 }
1682
1683 // If exactly one conversion is possible, that conversion is applied to
1684 // the chosen operand and the converted operands are used in place of the
1685 // original operands for the remainder of this section.
1686 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001687 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001688 return QualType();
1689 LTy = LHS->getType();
1690 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001691 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001692 return QualType();
1693 RTy = RHS->getType();
1694 }
1695 }
1696
1697 // C++0x 5.16p4
1698 // If the second and third operands are lvalues and have the same type,
1699 // the result is of that type [...]
1700 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1701 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1702 RHS->isLvalue(Context) == Expr::LV_Valid)
1703 return LTy;
1704
1705 // C++0x 5.16p5
1706 // Otherwise, the result is an rvalue. If the second and third operands
1707 // do not have the same type, and either has (cv) class type, ...
1708 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1709 // ... overload resolution is used to determine the conversions (if any)
1710 // to be applied to the operands. If the overload resolution fails, the
1711 // program is ill-formed.
1712 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1713 return QualType();
1714 }
1715
1716 // C++0x 5.16p6
1717 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1718 // conversions are performed on the second and third operands.
1719 DefaultFunctionArrayConversion(LHS);
1720 DefaultFunctionArrayConversion(RHS);
1721 LTy = LHS->getType();
1722 RTy = RHS->getType();
1723
1724 // After those conversions, one of the following shall hold:
1725 // -- The second and third operands have the same type; the result
1726 // is of that type.
1727 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1728 return LTy;
1729
1730 // -- The second and third operands have arithmetic or enumeration type;
1731 // the usual arithmetic conversions are performed to bring them to a
1732 // common type, and the result is of that type.
1733 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1734 UsualArithmeticConversions(LHS, RHS);
1735 return LHS->getType();
1736 }
1737
1738 // -- The second and third operands have pointer type, or one has pointer
1739 // type and the other is a null pointer constant; pointer conversions
1740 // and qualification conversions are performed to bring them to their
1741 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001742 QualType Composite = FindCompositePointerType(LHS, RHS);
1743 if (!Composite.isNull())
1744 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001745
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001746 // Fourth bullet is same for pointers-to-member. However, the possible
1747 // conversions are far more limited: we have null-to-pointer, upcast of
1748 // containing class, and second-level cv-ness.
1749 // cv-ness is not a union, but must match one of the two operands. (Which,
1750 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001751 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1752 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001753 if (LMemPtr &&
1754 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001755 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001756 return LTy;
1757 }
Douglas Gregorce940492009-09-25 04:25:58 +00001758 if (RMemPtr &&
1759 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001760 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001761 return RTy;
1762 }
1763 if (LMemPtr && RMemPtr) {
1764 QualType LPointee = LMemPtr->getPointeeType();
1765 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001766
1767 QualifierCollector LPQuals, RPQuals;
1768 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1769 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1770
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001771 // First, we check that the unqualified pointee type is the same. If it's
1772 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001773 if (LPCan == RPCan) {
1774
1775 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001776 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001777
1778 Qualifiers MergedQuals = LPQuals + RPQuals;
1779
1780 bool CompatibleQuals = true;
1781 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1782 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1783 CompatibleQuals = false;
1784 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1785 // FIXME:
1786 // C99 6.5.15 as modified by TR 18037:
1787 // If the second and third operands are pointers into different
1788 // address spaces, the address spaces must overlap.
1789 CompatibleQuals = false;
1790 // FIXME: GC qualifiers?
1791
1792 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001793 // Third, we check if either of the container classes is derived from
1794 // the other.
1795 QualType LContainer(LMemPtr->getClass(), 0);
1796 QualType RContainer(RMemPtr->getClass(), 0);
1797 QualType MoreDerived;
1798 if (Context.getCanonicalType(LContainer) ==
1799 Context.getCanonicalType(RContainer))
1800 MoreDerived = LContainer;
1801 else if (IsDerivedFrom(LContainer, RContainer))
1802 MoreDerived = LContainer;
1803 else if (IsDerivedFrom(RContainer, LContainer))
1804 MoreDerived = RContainer;
1805
1806 if (!MoreDerived.isNull()) {
1807 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1808 // We don't use ImpCastExprToType here because this could still fail
1809 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001810 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1811 QualType Common
1812 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001813 if (PerformImplicitConversion(LHS, Common, "converting"))
1814 return QualType();
1815 if (PerformImplicitConversion(RHS, Common, "converting"))
1816 return QualType();
1817 return Common;
1818 }
1819 }
1820 }
1821 }
1822
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001823 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1824 << LHS->getType() << RHS->getType()
1825 << LHS->getSourceRange() << RHS->getSourceRange();
1826 return QualType();
1827}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001828
1829/// \brief Find a merged pointer type and convert the two expressions to it.
1830///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001831/// This finds the composite pointer type (or member pointer type) for @p E1
1832/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1833/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001834/// It does not emit diagnostics.
1835QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1836 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1837 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor20b3e992009-08-24 17:42:35 +00001839 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1840 !T2->isPointerType() && !T2->isMemberPointerType())
1841 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001842
Douglas Gregor20b3e992009-08-24 17:42:35 +00001843 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001845 // C++0x 5.9p2
1846 // Pointer conversions and qualification conversions are performed on
1847 // pointer operands to bring them to their composite pointer type. If
1848 // one operand is a null pointer constant, the composite pointer type is
1849 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001850 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001851 if (T2->isMemberPointerType())
1852 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1853 else
1854 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001855 return T2;
1856 }
Douglas Gregorce940492009-09-25 04:25:58 +00001857 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001858 if (T1->isMemberPointerType())
1859 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1860 else
1861 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001862 return T1;
1863 }
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor20b3e992009-08-24 17:42:35 +00001865 // Now both have to be pointers or member pointers.
1866 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1867 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001868 return QualType();
1869
1870 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1871 // the other has type "pointer to cv2 T" and the composite pointer type is
1872 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1873 // Otherwise, the composite pointer type is a pointer type similar to the
1874 // type of one of the operands, with a cv-qualification signature that is
1875 // the union of the cv-qualification signatures of the operand types.
1876 // In practice, the first part here is redundant; it's subsumed by the second.
1877 // What we do here is, we build the two possible composite types, and try the
1878 // conversions in both directions. If only one works, or if the two composite
1879 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001880 // FIXME: extended qualifiers?
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001881 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001882 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001883 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001884 do {
1885 const PointerType *Ptr1, *Ptr2;
1886 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1887 (Ptr2 = Composite2->getAs<PointerType>())) {
1888 Composite1 = Ptr1->getPointeeType();
1889 Composite2 = Ptr2->getPointeeType();
1890 QualifierUnion.push_back(
1891 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1892 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1893 continue;
1894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Douglas Gregor20b3e992009-08-24 17:42:35 +00001896 const MemberPointerType *MemPtr1, *MemPtr2;
1897 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1898 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1899 Composite1 = MemPtr1->getPointeeType();
1900 Composite2 = MemPtr2->getPointeeType();
1901 QualifierUnion.push_back(
1902 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1903 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1904 MemPtr2->getClass()));
1905 continue;
1906 }
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Douglas Gregor20b3e992009-08-24 17:42:35 +00001908 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Douglas Gregor20b3e992009-08-24 17:42:35 +00001910 // Cannot unwrap any more types.
1911 break;
1912 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Douglas Gregor20b3e992009-08-24 17:42:35 +00001914 // Rewrap the composites as pointers or member pointers with the union CVRs.
1915 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1916 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001917 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001918 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001919 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001920 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001921 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001922 if (MOC->first && MOC->second) {
1923 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001924 Composite1 = Context.getMemberPointerType(
1925 Context.getQualifiedType(Composite1, Quals),
1926 MOC->first);
1927 Composite2 = Context.getMemberPointerType(
1928 Context.getQualifiedType(Composite2, Quals),
1929 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001930 } else {
1931 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001932 Composite1
1933 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1934 Composite2
1935 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001936 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001937 }
1938
Mike Stump1eb44332009-09-09 15:08:12 +00001939 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001940 TryImplicitConversion(E1, Composite1,
1941 /*SuppressUserConversions=*/false,
1942 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001943 /*ForceRValue=*/false,
1944 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001945 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001946 TryImplicitConversion(E2, Composite1,
1947 /*SuppressUserConversions=*/false,
1948 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001949 /*ForceRValue=*/false,
1950 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001952 ImplicitConversionSequence E1ToC2, E2ToC2;
1953 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1954 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1955 if (Context.getCanonicalType(Composite1) !=
1956 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001957 E1ToC2 = TryImplicitConversion(E1, Composite2,
1958 /*SuppressUserConversions=*/false,
1959 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001960 /*ForceRValue=*/false,
1961 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001962 E2ToC2 = TryImplicitConversion(E2, Composite2,
1963 /*SuppressUserConversions=*/false,
1964 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001965 /*ForceRValue=*/false,
1966 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001967 }
1968
1969 bool ToC1Viable = E1ToC1.ConversionKind !=
1970 ImplicitConversionSequence::BadConversion
1971 && E2ToC1.ConversionKind !=
1972 ImplicitConversionSequence::BadConversion;
1973 bool ToC2Viable = E1ToC2.ConversionKind !=
1974 ImplicitConversionSequence::BadConversion
1975 && E2ToC2.ConversionKind !=
1976 ImplicitConversionSequence::BadConversion;
1977 if (ToC1Viable && !ToC2Viable) {
1978 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1979 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1980 return Composite1;
1981 }
1982 if (ToC2Viable && !ToC1Viable) {
1983 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1984 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1985 return Composite2;
1986 }
1987 return QualType();
1988}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001989
Anders Carlssondef11992009-05-30 20:36:53 +00001990Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001991 if (!Context.getLangOptions().CPlusPlus)
1992 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenek6217b802009-07-29 21:53:49 +00001994 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001995 if (!RT)
1996 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Anders Carlssondef11992009-05-30 20:36:53 +00001998 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1999 if (RD->hasTrivialDestructor())
2000 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Anders Carlsson283e4d52009-09-14 01:30:44 +00002002 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2003 QualType Ty = CE->getCallee()->getType();
2004 if (const PointerType *PT = Ty->getAs<PointerType>())
2005 Ty = PT->getPointeeType();
2006
John McCall183700f2009-09-21 23:43:11 +00002007 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002008 if (FTy->getResultType()->isReferenceType())
2009 return Owned(E);
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002012 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002013 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002014 if (CXXDestructorDecl *Destructor =
2015 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2016 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002017 // FIXME: Add the temporary to the temporaries vector.
2018 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2019}
2020
Mike Stump1eb44332009-09-09 15:08:12 +00002021Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002022 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002023 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002025 if (ExprTemporaries.empty())
2026 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002028 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002029 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002030 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002031 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002032 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002034 return E;
2035}
2036
Mike Stump1eb44332009-09-09 15:08:12 +00002037Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002038Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2039 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2040 // Since this might be a postfix expression, get rid of ParenListExprs.
2041 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002043 Expr *BaseExpr = (Expr*)Base.get();
2044 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002046 QualType BaseType = BaseExpr->getType();
2047 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002048 // If we have a pointer to a dependent type and are using the -> operator,
2049 // the object type is the type that the pointer points to. We might still
2050 // have enough information about that type to do something useful.
2051 if (OpKind == tok::arrow)
2052 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2053 BaseType = Ptr->getPointeeType();
2054
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002055 ObjectType = BaseType.getAsOpaquePtr();
2056 return move(Base);
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002059 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002060 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002061 // returned, with the original second operand.
2062 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002063 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002064 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002065 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002066 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002067
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002068 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002069 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002070 BaseExpr = (Expr*)Base.get();
2071 if (BaseExpr == NULL)
2072 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002073 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002074 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002075 BaseType = BaseExpr->getType();
2076 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002077 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002078 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002079 for (unsigned i = 0; i < Locations.size(); i++)
2080 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002081 return ExprError();
2082 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002083 }
2084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002086 if (BaseType->isPointerType())
2087 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002088
2089 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002090 // vector types or Objective-C interfaces. Just return early and let
2091 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002092 if (!BaseType->isRecordType()) {
2093 // C++ [basic.lookup.classref]p2:
2094 // [...] If the type of the object expression is of pointer to scalar
2095 // type, the unqualified-id is looked up in the context of the complete
2096 // postfix-expression.
2097 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002098 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregorc68afe22009-09-03 21:38:09 +00002101 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002102 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00002103 // unqualified-id, and the type of the object expres- sion is of a class
2104 // type C (or of pointer to a class type C), the unqualified-id is looked
2105 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002106 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002107 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002108}
2109
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002110CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2111 CXXMethodDecl *Method) {
2112 MemberExpr *ME =
2113 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2114 SourceLocation(), Method->getType());
2115 QualType ResultType;
2116 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2117 ResultType = Conv->getConversionType().getNonReferenceType();
2118 else
2119 ResultType = Method->getResultType().getNonReferenceType();
2120
2121 CXXMemberCallExpr *CE =
2122 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2123 ResultType,
2124 SourceLocation());
2125 return CE;
2126}
2127
Anders Carlsson0aebc812009-09-09 21:33:21 +00002128Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2129 QualType Ty,
2130 CastExpr::CastKind Kind,
2131 CXXMethodDecl *Method,
2132 ExprArg Arg) {
2133 Expr *From = Arg.takeAs<Expr>();
2134
2135 switch (Kind) {
2136 default: assert(0 && "Unhandled cast kind!");
2137 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002138 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2139
2140 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2141 MultiExprArg(*this, (void **)&From, 1),
2142 CastLoc, ConstructorArgs))
2143 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002144
2145 OwningExprResult Result =
2146 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2147 move_arg(ConstructorArgs));
2148 if (Result.isInvalid())
2149 return ExprError();
2150
2151 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002152 }
2153
2154 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002155 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2156
2157 // Cast to base if needed.
2158 if (PerformObjectArgumentInitialization(From, Method))
2159 return ExprError();
2160
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002161 // Create an implicit call expr that calls it.
2162 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002163 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002164 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002165 }
2166}
2167
Anders Carlsson165a0a02009-05-17 18:41:29 +00002168Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2169 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002170 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002171 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002172 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002173
Anders Carlssonec773872009-08-25 23:46:41 +00002174
Anders Carlsson165a0a02009-05-17 18:41:29 +00002175 return Owned(FullExpr);
2176}
Douglas Gregore961afb2009-10-22 07:08:30 +00002177
2178/// \brief Determine whether a reference to the given declaration in the
2179/// current context is an implicit member access
2180/// (C++ [class.mfct.non-static]p2).
2181///
2182/// FIXME: Should Objective-C also use this approach?
2183///
2184/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2185/// name of the declaration referenced.
2186///
2187/// \param D the declaration being referenced from the current scope.
2188///
2189/// \param NameLoc the location of the name in the source.
2190///
2191/// \param ThisType if the reference to this declaration is an implicit member
2192/// access, will be set to the type of the "this" pointer to be used when
2193/// building that implicit member access.
2194///
2195/// \param MemberType if the reference to this declaration is an implicit
2196/// member access, will be set to the type of the member being referenced
2197/// (for use at the type of the resulting member access expression).
2198///
2199/// \returns true if this is an implicit member reference (in which case
2200/// \p ThisType and \p MemberType will be set), or false if it is not an
2201/// implicit member reference.
2202bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2203 SourceLocation NameLoc, QualType &ThisType,
2204 QualType &MemberType) {
2205 // If this isn't a C++ method, then it isn't an implicit member reference.
2206 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2207 if (!MD || MD->isStatic())
2208 return false;
2209
2210 // C++ [class.mfct.nonstatic]p2:
2211 // [...] if name lookup (3.4.1) resolves the name in the
2212 // id-expression to a nonstatic nontype member of class X or of
2213 // a base class of X, the id-expression is transformed into a
2214 // class member access expression (5.2.5) using (*this) (9.3.2)
2215 // as the postfix-expression to the left of the '.' operator.
2216 DeclContext *Ctx = 0;
2217 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2218 Ctx = FD->getDeclContext();
2219 MemberType = FD->getType();
2220
2221 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2222 MemberType = RefType->getPointeeType();
2223 else if (!FD->isMutable())
2224 MemberType
2225 = Context.getQualifiedType(MemberType,
2226 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2227 } else {
2228 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2229 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2230 FunctionTemplateDecl *FunTmpl = 0;
2231 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2232 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2233
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002234 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002235 if (Method && !Method->isStatic()) {
2236 Ctx = Method->getParent();
2237 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2238 MemberType = Method->getType();
2239 else
2240 MemberType = Context.OverloadTy;
2241 break;
2242 }
2243 }
2244 }
2245
2246 if (!Ctx || !Ctx->isRecord())
2247 return false;
2248
2249 // Determine whether the declaration(s) we found are actually in a base
2250 // class. If not, this isn't an implicit member reference.
2251 ThisType = MD->getThisType(Context);
Douglas Gregor7a343142009-11-01 17:08:18 +00002252
2253 // If the type of "this" is dependent, we can't tell if the member is in a
2254 // base class or not, so treat this as a dependent implicit member reference.
2255 if (ThisType->isDependentType())
2256 return true;
2257
Douglas Gregore961afb2009-10-22 07:08:30 +00002258 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2259 QualType ClassType
2260 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2261 return Context.hasSameType(CtxType, ClassType) ||
2262 IsDerivedFrom(ClassType, CtxType);
2263}
2264