blob: 0b3426b2f3cbfcade31230ed68cb07be85f31cfe [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"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Sebastian Redlc42e1182008-11-11 11:37:55 +000026/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000027Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000028Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
29 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000030 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000031 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000032
33 if (isType)
34 // FIXME: Preserve type source info.
35 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
36
Chris Lattner572af492008-11-20 05:51:55 +000037 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000038 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
39 LookupQualifiedName(R, StdNamespace);
John McCallf36e02d2009-10-09 21:13:30 +000040 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000041 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000042 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000043 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000044
45 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
46
Douglas Gregorac7610d2009-06-22 20:57:11 +000047 if (!isType) {
48 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000049 // When typeid is applied to an expression other than an lvalue of a
50 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000051 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000052
Douglas Gregorac7610d2009-06-22 20:57:11 +000053 // FIXME: if the type of the expression is a class type, the class
54 // shall be completely defined.
55 bool isUnevaluatedOperand = true;
56 Expr *E = static_cast<Expr *>(TyOrExpr);
57 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
58 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000059 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000060 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
61 if (RecordD->isPolymorphic())
62 isUnevaluatedOperand = false;
63 }
64 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregor2afce722009-11-26 00:44:06 +000066 // If this is an unevaluated operand, clear out the set of
67 // declaration references we have been computing and eliminate any
68 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +000069 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +000070 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Sebastian Redlf53597f2009-03-15 17:47:39 +000073 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
74 TypeInfoType.withConst(),
75 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076}
77
Steve Naroff1b273c42007-09-16 14:56:35 +000078/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000079Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000081 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000082 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000083 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
84 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
Chris Lattner50dd2892008-02-26 00:51:44 +000086
Sebastian Redl6e8ed162009-05-10 18:38:11 +000087/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
88Action::OwningExprResult
89Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
90 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
91}
92
Chris Lattner50dd2892008-02-26 00:51:44 +000093/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000094Action::OwningExprResult
95Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000096 Expr *Ex = E.takeAs<Expr>();
97 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
98 return ExprError();
99 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
100}
101
102/// CheckCXXThrowOperand - Validate the operand of a throw.
103bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
104 // C++ [except.throw]p3:
105 // [...] adjusting the type from "array of T" or "function returning T"
106 // to "pointer to T" or "pointer to function returning T", [...]
107 DefaultFunctionArrayConversion(E);
108
109 // If the type of the exception would be an incomplete type or a pointer
110 // to an incomplete type other than (cv) void the program is ill-formed.
111 QualType Ty = E->getType();
112 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000113 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000114 Ty = Ptr->getPointeeType();
115 isPointer = 1;
116 }
117 if (!isPointer || !Ty->isVoidType()) {
118 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000119 PDiag(isPointer ? diag::err_throw_incomplete_ptr
120 : diag::err_throw_incomplete)
121 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000122 return true;
123 }
124
125 // FIXME: Construct a temporary here.
126 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000127}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000128
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000130 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
131 /// is a non-lvalue expression whose value is the address of the object for
132 /// which the function is called.
133
Sebastian Redlf53597f2009-03-15 17:47:39 +0000134 if (!isa<FunctionDecl>(CurContext))
135 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000136
137 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
138 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000139 return Owned(new (Context) CXXThisExpr(ThisLoc,
140 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000141
Sebastian Redlf53597f2009-03-15 17:47:39 +0000142 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000143}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000144
145/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
146/// Can be interpreted either as function-style casting ("int(x)")
147/// or class type construction ("ClassType(x,y,z)")
148/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000149Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000150Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
151 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000153 SourceLocation *CommaLocs,
154 SourceLocation RParenLoc) {
155 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000156 // FIXME: Preserve type source info.
157 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
167 return Owned(CXXUnresolvedConstructExpr::Create(Context,
168 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000169 LParenLoc,
170 Exprs, NumExprs,
171 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000172 }
173
Anders Carlssonbb60a502009-08-27 03:53:50 +0000174 if (Ty->isArrayType())
175 return ExprError(Diag(TyBeginLoc,
176 diag::err_value_init_for_array_type) << FullRange);
177 if (!Ty->isVoidType() &&
178 RequireCompleteType(TyBeginLoc, Ty,
179 PDiag(diag::err_invalid_incomplete_type_use)
180 << FullRange))
181 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000182
Anders Carlssonbb60a502009-08-27 03:53:50 +0000183 if (RequireNonAbstractType(TyBeginLoc, Ty,
184 diag::err_allocation_of_abstract_type))
185 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
187
Douglas Gregor506ae412009-01-16 18:33:17 +0000188 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000189 // If the expression list is a single expression, the type conversion
190 // expression is equivalent (in definedness, and if defined in meaning) to the
191 // corresponding cast expression.
192 //
193 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000194 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000195 CXXMethodDecl *Method = 0;
196 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
197 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000199
200 exprs.release();
201 if (Method) {
202 OwningExprResult CastArg
203 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
204 Kind, Method, Owned(Exprs[0]));
205 if (CastArg.isInvalid())
206 return ExprError();
207
208 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000209 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000210
211 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
212 Ty, TyBeginLoc, Kind,
213 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000214 }
215
Ted Kremenek6217b802009-07-29 21:53:49 +0000216 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000217 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000218
Mike Stump1eb44332009-09-09 15:08:12 +0000219 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000220 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000221 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
222
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000224 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000225 TypeRange.getBegin(),
226 SourceRange(TypeRange.getBegin(),
227 RParenLoc),
228 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000229 IK_Direct,
230 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000231
Sebastian Redlf53597f2009-03-15 17:47:39 +0000232 if (!Constructor)
233 return ExprError();
234
Mike Stump1eb44332009-09-09 15:08:12 +0000235 OwningExprResult Result =
236 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000237 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000238 if (Result.isInvalid())
239 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Anders Carlssone7624a72009-08-27 05:08:22 +0000241 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000242 }
243
244 // Fall through to value-initialize an object of class type that
245 // doesn't have a user-declared default constructor.
246 }
247
248 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000249 // If the expression list specifies more than a single value, the type shall
250 // be a class with a suitably declared constructor.
251 //
252 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000253 return ExprError(Diag(CommaLocs[0],
254 diag::err_builtin_func_cast_more_than_one_arg)
255 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000256
257 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000258 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000259 // The expression T(), where T is a simple-type-specifier for a non-array
260 // complete object type or the (possibly cv-qualified) void type, creates an
261 // rvalue of the specified type, which is value-initialized.
262 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000263 exprs.release();
264 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000265}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000266
267
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000268/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
269/// @code new (memory) int[size][4] @endcode
270/// or
271/// @code ::new Foo(23, "hello") @endcode
272/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000274Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000275 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000276 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000277 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000278 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000279 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000280 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000281 // If the specified type is an array, unwrap it and save the expression.
282 if (D.getNumTypeObjects() > 0 &&
283 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
284 DeclaratorChunk &Chunk = D.getTypeObject(0);
285 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000286 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
287 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000288 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000289 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
290 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000291
292 if (ParenTypeId) {
293 // Can't have dynamic array size when the type-id is in parentheses.
294 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
295 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
296 !NumElts->isIntegerConstantExpr(Context)) {
297 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
298 << NumElts->getSourceRange();
299 return ExprError();
300 }
301 }
302
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000303 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000304 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000305 }
306
Douglas Gregor043cad22009-09-11 00:18:58 +0000307 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000308 if (ArraySize) {
309 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000310 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
311 break;
312
313 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
314 if (Expr *NumElts = (Expr *)Array.NumElts) {
315 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
316 !NumElts->isIntegerConstantExpr(Context)) {
317 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
318 << NumElts->getSourceRange();
319 return ExprError();
320 }
321 }
322 }
323 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000324
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000325 //FIXME: Store DeclaratorInfo in CXXNew expression.
326 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000327 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000328 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000329 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000330
Mike Stump1eb44332009-09-09 15:08:12 +0000331 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000332 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000333 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000334 PlacementRParen,
335 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000336 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000337 D.getSourceRange().getBegin(),
338 D.getSourceRange(),
339 Owned(ArraySize),
340 ConstructorLParen,
341 move(ConstructorArgs),
342 ConstructorRParen);
343}
344
Mike Stump1eb44332009-09-09 15:08:12 +0000345Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000346Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
347 SourceLocation PlacementLParen,
348 MultiExprArg PlacementArgs,
349 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000351 QualType AllocType,
352 SourceLocation TypeLoc,
353 SourceRange TypeRange,
354 ExprArg ArraySizeE,
355 SourceLocation ConstructorLParen,
356 MultiExprArg ConstructorArgs,
357 SourceLocation ConstructorRParen) {
358 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000359 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000360
Douglas Gregor3433cf72009-05-21 00:00:09 +0000361 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000362
363 // That every array dimension except the first is constant was already
364 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000365
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000366 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
367 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000368 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000369 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000370 QualType SizeType = ArraySize->getType();
371 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000372 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
373 diag::err_array_size_not_integral)
374 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000375 // Let's see if this is a constant < 0. If so, we reject it out of hand.
376 // We don't care about special rules, so we tell the machinery it's not
377 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000378 if (!ArraySize->isValueDependent()) {
379 llvm::APSInt Value;
380 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
381 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000382 llvm::APInt::getNullValue(Value.getBitWidth()),
383 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000384 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
385 diag::err_typecheck_negative_array_size)
386 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000387 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000388 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000389
Eli Friedman73c39ab2009-10-20 08:27:19 +0000390 ImpCastExprToType(ArraySize, Context.getSizeType(),
391 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000392 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000393
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000394 FunctionDecl *OperatorNew = 0;
395 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
397 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000398
Sebastian Redl28507842009-02-26 14:39:58 +0000399 if (!AllocType->isDependentType() &&
400 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
401 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000402 SourceRange(PlacementLParen, PlacementRParen),
403 UseGlobal, AllocType, ArraySize, PlaceArgs,
404 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000405 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000406 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000407 if (OperatorNew) {
408 // Add default arguments, if any.
409 const FunctionProtoType *Proto =
410 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000411 VariadicCallType CallType =
412 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000413 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
414 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000415 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000416 if (Invalid)
417 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000418
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000419 NumPlaceArgs = AllPlaceArgs.size();
420 if (NumPlaceArgs > 0)
421 PlaceArgs = &AllPlaceArgs[0];
422 }
423
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000424 bool Init = ConstructorLParen.isValid();
425 // --- Choosing a constructor ---
426 // C++ 5.3.4p15
427 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
428 // the object is not initialized. If the object, or any part of it, is
429 // const-qualified, it's an error.
430 // 2) If T is a POD and there's an empty initializer, the object is value-
431 // initialized.
432 // 3) If T is a POD and there's one initializer argument, the object is copy-
433 // constructed.
434 // 4) If T is a POD and there's more initializer arguments, it's an error.
435 // 5) If T is not a POD, the initializer arguments are used as constructor
436 // arguments.
437 //
438 // Or by the C++0x formulation:
439 // 1) If there's no initializer, the object is default-initialized according
440 // to C++0x rules.
441 // 2) Otherwise, the object is direct-initialized.
442 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000444 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000445 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000446 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
447
Douglas Gregor089407b2009-10-17 21:40:42 +0000448 if (AllocType->isDependentType() ||
449 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000450 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000451 } else if ((RT = AllocType->getAs<RecordType>()) &&
452 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000453 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000454 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000455 TypeLoc,
456 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000457 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000458 NumConsArgs != 0 ? IK_Direct : IK_Default,
459 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000462
463 // Take the converted constructor arguments and use them for the new
464 // expression.
465 NumConsArgs = ConvertedConstructorArgs.size();
466 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000467 } else {
468 if (!Init) {
469 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000470 if (AllocType.isConstQualified())
471 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000472 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000473 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000474 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000475 } else if (NumConsArgs == 1) {
476 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000477 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000478 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000479 DeclarationName() /*AllocType.getAsString()*/,
480 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000481 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000482 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000483 return ExprError(Diag(StartLoc,
484 diag::err_builtin_direct_init_more_than_one_arg)
485 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000486 }
487 }
488
489 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000490
Sebastian Redlf53597f2009-03-15 17:47:39 +0000491 PlacementArgs.release();
492 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000493 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000494 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000495 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000496 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000497 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000498}
499
500/// CheckAllocatedType - Checks that a type is suitable as the allocated type
501/// in a new-expression.
502/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000503bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000504 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000505 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
506 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000507 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000508 return Diag(Loc, diag::err_bad_new_type)
509 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000510 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511 return Diag(Loc, diag::err_bad_new_type)
512 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000513 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000514 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000515 PDiag(diag::err_new_incomplete_type)
516 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000517 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000518 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000519 diag::err_allocation_of_abstract_type))
520 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000521
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000522 return false;
523}
524
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000525/// FindAllocationFunctions - Finds the overloads of operator new and delete
526/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000527bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
528 bool UseGlobal, QualType AllocType,
529 bool IsArray, Expr **PlaceArgs,
530 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000531 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000533 // --- Choosing an allocation function ---
534 // C++ 5.3.4p8 - 14 & 18
535 // 1) If UseGlobal is true, only look in the global scope. Else, also look
536 // in the scope of the allocated class.
537 // 2) If an array size is given, look for operator new[], else look for
538 // operator new.
539 // 3) The first argument is always size_t. Append the arguments from the
540 // placement form.
541 // FIXME: Also find the appropriate delete operator.
542
543 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
544 // We don't care about the actual value of this argument.
545 // FIXME: Should the Sema create the expression and embed it in the syntax
546 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000547 IntegerLiteral Size(llvm::APInt::getNullValue(
548 Context.Target.getPointerWidth(0)),
549 Context.getSizeType(),
550 SourceLocation());
551 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000552 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
553
554 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
555 IsArray ? OO_Array_New : OO_New);
556 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000558 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000559 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000560 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000561 AllocArgs.size(), Record, /*AllowMissing=*/true,
562 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000563 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000564 }
565 if (!OperatorNew) {
566 // Didn't find a member overload. Look for a global one.
567 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000568 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000569 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000570 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
571 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000572 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000573 }
574
Anders Carlssond9583892009-05-31 20:26:12 +0000575 // FindAllocationOverload can change the passed in arguments, so we need to
576 // copy them back.
577 if (NumPlaceArgs > 0)
578 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000580 return false;
581}
582
Sebastian Redl7f662392008-12-04 22:20:51 +0000583/// FindAllocationOverload - Find an fitting overload for the allocation
584/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000585bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
586 DeclarationName Name, Expr** Args,
587 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000588 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000589 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
590 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000591 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000592 if (AllowMissing)
593 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000594 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000595 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000596 }
597
John McCallf36e02d2009-10-09 21:13:30 +0000598 // FIXME: handle ambiguity
599
Sebastian Redl7f662392008-12-04 22:20:51 +0000600 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000601 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
602 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000603 // Even member operator new/delete are implicitly treated as
604 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000605 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000606 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
607 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000608 continue;
609 }
610
611 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000612 }
613
614 // Do the resolution.
615 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000616 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000617 case OR_Success: {
618 // Got one!
619 FunctionDecl *FnDecl = Best->Function;
620 // The first argument is size_t, and the first parameter must be size_t,
621 // too. This is checked on declaration and can be assumed. (It can't be
622 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000623 // Whatch out for variadic allocator function.
624 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
625 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000626 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000627 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000628 FnDecl->getParamDecl(i)->getType(),
629 "passing"))
630 return true;
631 }
632 Operator = FnDecl;
633 return false;
634 }
635
636 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000637 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000638 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000639 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
640 return true;
641
642 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000643 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000644 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000645 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
646 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000647
648 case OR_Deleted:
649 Diag(StartLoc, diag::err_ovl_deleted_call)
650 << Best->Function->isDeleted()
651 << Name << Range;
652 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
653 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000654 }
655 assert(false && "Unreachable, bad result from BestViableFunction");
656 return true;
657}
658
659
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000660/// DeclareGlobalNewDelete - Declare the global forms of operator new and
661/// delete. These are:
662/// @code
663/// void* operator new(std::size_t) throw(std::bad_alloc);
664/// void* operator new[](std::size_t) throw(std::bad_alloc);
665/// void operator delete(void *) throw();
666/// void operator delete[](void *) throw();
667/// @endcode
668/// Note that the placement and nothrow forms of new are *not* implicitly
669/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000670void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000671 if (GlobalNewDeleteDeclared)
672 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000673
674 // C++ [basic.std.dynamic]p2:
675 // [...] The following allocation and deallocation functions (18.4) are
676 // implicitly declared in global scope in each translation unit of a
677 // program
678 //
679 // void* operator new(std::size_t) throw(std::bad_alloc);
680 // void* operator new[](std::size_t) throw(std::bad_alloc);
681 // void operator delete(void*) throw();
682 // void operator delete[](void*) throw();
683 //
684 // These implicit declarations introduce only the function names operator
685 // new, operator new[], operator delete, operator delete[].
686 //
687 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
688 // "std" or "bad_alloc" as necessary to form the exception specification.
689 // However, we do not make these implicit declarations visible to name
690 // lookup.
691 if (!StdNamespace) {
692 // The "std" namespace has not yet been defined, so build one implicitly.
693 StdNamespace = NamespaceDecl::Create(Context,
694 Context.getTranslationUnitDecl(),
695 SourceLocation(),
696 &PP.getIdentifierTable().get("std"));
697 StdNamespace->setImplicit(true);
698 }
699
700 if (!StdBadAlloc) {
701 // The "std::bad_alloc" class has not yet been declared, so build it
702 // implicitly.
703 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
704 StdNamespace,
705 SourceLocation(),
706 &PP.getIdentifierTable().get("bad_alloc"),
707 SourceLocation(), 0);
708 StdBadAlloc->setImplicit(true);
709 }
710
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000711 GlobalNewDeleteDeclared = true;
712
713 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
714 QualType SizeT = Context.getSizeType();
715
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000716 DeclareGlobalAllocationFunction(
717 Context.DeclarationNames.getCXXOperatorName(OO_New),
718 VoidPtr, SizeT);
719 DeclareGlobalAllocationFunction(
720 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
721 VoidPtr, SizeT);
722 DeclareGlobalAllocationFunction(
723 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
724 Context.VoidTy, VoidPtr);
725 DeclareGlobalAllocationFunction(
726 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
727 Context.VoidTy, VoidPtr);
728}
729
730/// DeclareGlobalAllocationFunction - Declares a single implicit global
731/// allocation function if it doesn't already exist.
732void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000733 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000734 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
735
736 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000737 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000738 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000739 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000740 Alloc != AllocEnd; ++Alloc) {
741 // FIXME: Do we need to check for default arguments here?
742 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
743 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000744 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000745 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000746 }
747 }
748
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000749 QualType BadAllocType;
750 bool HasBadAllocExceptionSpec
751 = (Name.getCXXOverloadedOperator() == OO_New ||
752 Name.getCXXOverloadedOperator() == OO_Array_New);
753 if (HasBadAllocExceptionSpec) {
754 assert(StdBadAlloc && "Must have std::bad_alloc declared");
755 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
756 }
757
758 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
759 true, false,
760 HasBadAllocExceptionSpec? 1 : 0,
761 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000762 FunctionDecl *Alloc =
763 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000764 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000765 Alloc->setImplicit();
766 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000767 0, Argument, /*DInfo=*/0,
768 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000769 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000770
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000771 // FIXME: Also add this declaration to the IdentifierResolver, but
772 // make sure it is at the end of the chain to coincide with the
773 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000774 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000775}
776
Anders Carlsson78f74552009-11-15 18:45:20 +0000777bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
778 DeclarationName Name,
779 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000780 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000781 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000782 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000783
John McCalla24dc2e2009-11-17 02:14:36 +0000784 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000785 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000786
787 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
788 F != FEnd; ++F) {
789 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
790 if (Delete->isUsualDeallocationFunction()) {
791 Operator = Delete;
792 return false;
793 }
794 }
795
796 // We did find operator delete/operator delete[] declarations, but
797 // none of them were suitable.
798 if (!Found.empty()) {
799 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
800 << Name << RD;
801
802 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
803 F != FEnd; ++F) {
804 Diag((*F)->getLocation(),
805 diag::note_delete_member_function_declared_here)
806 << Name;
807 }
808
809 return true;
810 }
811
812 // Look for a global declaration.
813 DeclareGlobalNewDelete();
814 DeclContext *TUDecl = Context.getTranslationUnitDecl();
815
816 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
817 Expr* DeallocArgs[1];
818 DeallocArgs[0] = &Null;
819 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
820 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
821 Operator))
822 return true;
823
824 assert(Operator && "Did not find a deallocation function!");
825 return false;
826}
827
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000828/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
829/// @code ::delete ptr; @endcode
830/// or
831/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000832Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000833Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000834 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000835 // C++ [expr.delete]p1:
836 // The operand shall have a pointer type, or a class type having a single
837 // conversion function to a pointer type. The result has type void.
838 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000839 // DR599 amends "pointer type" to "pointer to object type" in both cases.
840
Anders Carlssond67c4c32009-08-16 20:29:29 +0000841 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Sebastian Redlf53597f2009-03-15 17:47:39 +0000843 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000844 if (!Ex->isTypeDependent()) {
845 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000846
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000847 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000848 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000849 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000850 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000851
John McCallba135432009-11-21 08:51:07 +0000852 for (UnresolvedSet::iterator I = Conversions->begin(),
853 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000854 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000855 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000856 continue;
857
John McCallba135432009-11-21 08:51:07 +0000858 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000859
860 QualType ConvType = Conv->getConversionType().getNonReferenceType();
861 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
862 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000863 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000864 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000865 if (ObjectPtrConversions.size() == 1) {
866 // We have a single conversion to a pointer-to-object type. Perform
867 // that conversion.
868 Operand.release();
869 if (!PerformImplicitConversion(Ex,
870 ObjectPtrConversions.front()->getConversionType(),
871 "converting")) {
872 Operand = Owned(Ex);
873 Type = Ex->getType();
874 }
875 }
876 else if (ObjectPtrConversions.size() > 1) {
877 Diag(StartLoc, diag::err_ambiguous_delete_operand)
878 << Type << Ex->getSourceRange();
879 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
880 CXXConversionDecl *Conv = ObjectPtrConversions[i];
881 Diag(Conv->getLocation(), diag::err_ovl_candidate);
882 }
883 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000884 }
Sebastian Redl28507842009-02-26 14:39:58 +0000885 }
886
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 if (!Type->isPointerType())
888 return ExprError(Diag(StartLoc, diag::err_delete_operand)
889 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000890
Ted Kremenek6217b802009-07-29 21:53:49 +0000891 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000892 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000893 return ExprError(Diag(StartLoc, diag::err_delete_operand)
894 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000895 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000896 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000897 PDiag(diag::warn_delete_incomplete)
898 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000899 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000900
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000901 // C++ [expr.delete]p2:
902 // [Note: a pointer to a const type can be the operand of a
903 // delete-expression; it is not necessary to cast away the constness
904 // (5.2.11) of the pointer expression before it is used as the operand
905 // of the delete-expression. ]
906 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
907 CastExpr::CK_NoOp);
908
909 // Update the operand.
910 Operand.take();
911 Operand = ExprArg(*this, Ex);
912
Anders Carlssond67c4c32009-08-16 20:29:29 +0000913 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
914 ArrayForm ? OO_Array_Delete : OO_Delete);
915
Anders Carlsson78f74552009-11-15 18:45:20 +0000916 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
917 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
918
919 if (!UseGlobal &&
920 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000921 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000922
Anders Carlsson78f74552009-11-15 18:45:20 +0000923 if (!RD->hasTrivialDestructor())
924 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000925 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000926 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000927 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000928
Anders Carlssond67c4c32009-08-16 20:29:29 +0000929 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000930 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000931 DeclareGlobalNewDelete();
932 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000933 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000934 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000935 OperatorDelete))
936 return ExprError();
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Sebastian Redl28507842009-02-26 14:39:58 +0000939 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000940 }
941
Sebastian Redlf53597f2009-03-15 17:47:39 +0000942 Operand.release();
943 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000944 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000945}
946
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000947/// \brief Check the use of the given variable as a C++ condition in an if,
948/// while, do-while, or switch statement.
949Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
950 QualType T = ConditionVar->getType();
951
952 // C++ [stmt.select]p2:
953 // The declarator shall not specify a function or an array.
954 if (T->isFunctionType())
955 return ExprError(Diag(ConditionVar->getLocation(),
956 diag::err_invalid_use_of_function_type)
957 << ConditionVar->getSourceRange());
958 else if (T->isArrayType())
959 return ExprError(Diag(ConditionVar->getLocation(),
960 diag::err_invalid_use_of_array_type)
961 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +0000962
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000963 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
964 ConditionVar->getLocation(),
965 ConditionVar->getType().getNonReferenceType()));
966}
967
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000968/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
969bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
970 // C++ 6.4p4:
971 // The value of a condition that is an initialized declaration in a statement
972 // other than a switch statement is the value of the declared variable
973 // implicitly converted to type bool. If that conversion is ill-formed, the
974 // program is ill-formed.
975 // The value of a condition that is an expression is the value of the
976 // expression, implicitly converted to bool.
977 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000978 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000979}
Douglas Gregor77a52232008-09-12 00:47:35 +0000980
981/// Helper function to determine whether this is the (deprecated) C++
982/// conversion from a string literal to a pointer to non-const char or
983/// non-const wchar_t (for narrow and wide string literals,
984/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000985bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000986Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
987 // Look inside the implicit cast, if it exists.
988 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
989 From = Cast->getSubExpr();
990
991 // A string literal (2.13.4) that is not a wide string literal can
992 // be converted to an rvalue of type "pointer to char"; a wide
993 // string literal can be converted to an rvalue of type "pointer
994 // to wchar_t" (C++ 4.2p2).
995 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000996 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000997 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000998 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000999 // This conversion is considered only when there is an
1000 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001001 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001002 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1003 (!StrLit->isWide() &&
1004 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1005 ToPointeeType->getKind() == BuiltinType::Char_S))))
1006 return true;
1007 }
1008
1009 return false;
1010}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001011
1012/// PerformImplicitConversion - Perform an implicit conversion of the
1013/// expression From to the type ToType. Returns true if there was an
1014/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001015/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001016/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001017/// explicit user-defined conversions are permitted. @p Elidable should be true
1018/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1019/// resolution works differently in that case.
1020bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001021Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001022 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001023 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001024 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001025 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1026 Elidable, ICS);
1027}
1028
1029bool
1030Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1031 const char *Flavor, bool AllowExplicit,
1032 bool Elidable,
1033 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001034 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1035 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001036 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001037 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001038 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001039 /*ForceRValue=*/true,
1040 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001041 }
1042 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001043 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001044 /*SuppressUserConversions=*/false,
1045 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001046 /*ForceRValue=*/false,
1047 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001048 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001049 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1050}
1051
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001052/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1053/// for the derived to base conversion of the expression 'From'. All
1054/// necessary information is passed in ICS.
1055bool
1056Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1057 const ImplicitConversionSequence& ICS,
1058 const char *Flavor) {
1059 QualType BaseType =
1060 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1061 // Must do additional defined to base conversion.
1062 QualType DerivedType =
1063 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1064
1065 From = new (Context) ImplicitCastExpr(
1066 DerivedType.getNonReferenceType(),
1067 CastKind,
1068 From,
1069 DerivedType->isLValueReferenceType());
1070 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1071 CastExpr::CK_DerivedToBase, From,
1072 BaseType->isLValueReferenceType());
1073 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1074 OwningExprResult FromResult =
1075 BuildCXXConstructExpr(
1076 ICS.UserDefined.After.CopyConstructor->getLocation(),
1077 BaseType,
1078 ICS.UserDefined.After.CopyConstructor,
1079 MultiExprArg(*this, (void **)&From, 1));
1080 if (FromResult.isInvalid())
1081 return true;
1082 From = FromResult.takeAs<Expr>();
1083 return false;
1084}
1085
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001086/// PerformImplicitConversion - Perform an implicit conversion of the
1087/// expression From to the type ToType using the pre-computed implicit
1088/// conversion sequence ICS. Returns true if there was an error, false
1089/// otherwise. The expression From is replaced with the converted
1090/// expression. Flavor is the kind of conversion we're performing,
1091/// used in the error message.
1092bool
1093Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1094 const ImplicitConversionSequence &ICS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001095 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001096 switch (ICS.ConversionKind) {
1097 case ImplicitConversionSequence::StandardConversion:
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001098 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1099 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001100 return true;
1101 break;
1102
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001103 case ImplicitConversionSequence::UserDefinedConversion: {
1104
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001105 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1106 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001107 QualType BeforeToType;
1108 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001109 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001110
1111 // If the user-defined conversion is specified by a conversion function,
1112 // the initial standard conversion sequence converts the source type to
1113 // the implicit object parameter of the conversion function.
1114 BeforeToType = Context.getTagDeclType(Conv->getParent());
1115 } else if (const CXXConstructorDecl *Ctor =
1116 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001117 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001118 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001119 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001120 // If the user-defined conversion is specified by a constructor, the
1121 // initial standard conversion sequence converts the source type to the
1122 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001123 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1124 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001125 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001126 else
1127 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001128 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001129 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001130 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001131 ICS.UserDefined.Before, "converting",
1132 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001133 return true;
1134 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001135
Anders Carlsson0aebc812009-09-09 21:33:21 +00001136 OwningExprResult CastArg
1137 = BuildCXXCastArgument(From->getLocStart(),
1138 ToType.getNonReferenceType(),
1139 CastKind, cast<CXXMethodDecl>(FD),
1140 Owned(From));
1141
1142 if (CastArg.isInvalid())
1143 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001144
1145 From = CastArg.takeAs<Expr>();
1146
1147 // FIXME: This and the following if statement shouldn't be necessary, but
1148 // there's some nasty stuff involving MaybeBindToTemporary going on here.
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001149 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1150 ICS.UserDefined.After.CopyConstructor) {
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001151 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1152 }
Eli Friedmand8889622009-11-27 04:41:50 +00001153
1154 if (ICS.UserDefined.After.CopyConstructor) {
1155 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1156 CastKind, From,
1157 ToType->isLValueReferenceType());
1158 return false;
1159 }
1160
1161 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1162 "converting", IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001163 }
1164
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001165 case ImplicitConversionSequence::EllipsisConversion:
1166 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001167 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001168
1169 case ImplicitConversionSequence::BadConversion:
1170 return true;
1171 }
1172
1173 // Everything went well.
1174 return false;
1175}
1176
1177/// PerformImplicitConversion - Perform an implicit conversion of the
1178/// expression From to the type ToType by following the standard
1179/// conversion sequence SCS. Returns true if there was an error, false
1180/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001181/// expression. Flavor is the context in which we're performing this
1182/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001183bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001184Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001185 const StandardConversionSequence& SCS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001186 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001187 // Overall FIXME: we are recomputing too many types here and doing far too
1188 // much extra work. What this means is that we need to keep track of more
1189 // information that is computed when we try the implicit conversion initially,
1190 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001191 QualType FromType = From->getType();
1192
Douglas Gregor225c41e2008-11-03 19:09:14 +00001193 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001194 // FIXME: When can ToType be a reference type?
1195 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001196 if (SCS.Second == ICK_Derived_To_Base) {
1197 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1198 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1199 MultiExprArg(*this, (void **)&From, 1),
1200 /*FIXME:ConstructLoc*/SourceLocation(),
1201 ConstructorArgs))
1202 return true;
1203 OwningExprResult FromResult =
1204 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1205 ToType, SCS.CopyConstructor,
1206 move_arg(ConstructorArgs));
1207 if (FromResult.isInvalid())
1208 return true;
1209 From = FromResult.takeAs<Expr>();
1210 return false;
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212 OwningExprResult FromResult =
1213 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1214 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001215 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001217 if (FromResult.isInvalid())
1218 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001220 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001221 return false;
1222 }
1223
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001224 // Perform the first implicit conversion.
1225 switch (SCS.First) {
1226 case ICK_Identity:
1227 case ICK_Lvalue_To_Rvalue:
1228 // Nothing to do.
1229 break;
1230
1231 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001232 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001233 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001234 break;
1235
1236 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001237 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001238 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1239 if (!Fn)
1240 return true;
1241
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001242 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1243 return true;
1244
Anders Carlsson96ad5332009-10-21 17:16:23 +00001245 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001246 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001247
Sebastian Redl759986e2009-10-17 20:50:27 +00001248 // If there's already an address-of operator in the expression, we have
1249 // the right type already, and the code below would just introduce an
1250 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001251 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001252 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001253 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001254 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001255 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001256 break;
1257
1258 default:
1259 assert(false && "Improper first standard conversion");
1260 break;
1261 }
1262
1263 // Perform the second implicit conversion
1264 switch (SCS.Second) {
1265 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001266 // If both sides are functions (or pointers/references to them), there could
1267 // be incompatible exception declarations.
1268 if (CheckExceptionSpecCompatibility(From, ToType))
1269 return true;
1270 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001271 break;
1272
1273 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001274 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001275 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1276 break;
1277
1278 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001279 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001280 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1281 break;
1282
1283 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001284 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001285 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1286 break;
1287
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001289 if (ToType->isFloatingType())
1290 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1291 else
1292 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1293 break;
1294
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001295 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001296 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1297 break;
1298
Douglas Gregorf9201e02009-02-11 23:02:49 +00001299 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001300 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001301 break;
1302
Anders Carlsson61faec12009-09-12 04:46:44 +00001303 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001304 if (SCS.IncompatibleObjC) {
1305 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001306 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001307 diag::ext_typecheck_convert_incompatible_pointer)
1308 << From->getType() << ToType << Flavor
1309 << From->getSourceRange();
1310 }
1311
Anders Carlsson61faec12009-09-12 04:46:44 +00001312
1313 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001314 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001315 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001316 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001317 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001318 }
1319
1320 case ICK_Pointer_Member: {
1321 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001322 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001323 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001324 if (CheckExceptionSpecCompatibility(From, ToType))
1325 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001326 ImpCastExprToType(From, ToType, Kind);
1327 break;
1328 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001329 case ICK_Boolean_Conversion: {
1330 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1331 if (FromType->isMemberPointerType())
1332 Kind = CastExpr::CK_MemberPointerToBoolean;
1333
1334 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001335 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001336 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001337
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001338 case ICK_Derived_To_Base:
1339 if (CheckDerivedToBaseConversion(From->getType(),
1340 ToType.getNonReferenceType(),
1341 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001342 From->getSourceRange(),
1343 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001344 return true;
1345 ImpCastExprToType(From, ToType.getNonReferenceType(),
1346 CastExpr::CK_DerivedToBase);
1347 break;
1348
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001349 default:
1350 assert(false && "Improper second standard conversion");
1351 break;
1352 }
1353
1354 switch (SCS.Third) {
1355 case ICK_Identity:
1356 // Nothing to do.
1357 break;
1358
1359 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001360 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1361 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001362 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001363 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001364 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001365 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001366
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001367 default:
1368 assert(false && "Improper second standard conversion");
1369 break;
1370 }
1371
1372 return false;
1373}
1374
Sebastian Redl64b45f72009-01-05 20:52:13 +00001375Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1376 SourceLocation KWLoc,
1377 SourceLocation LParen,
1378 TypeTy *Ty,
1379 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001380 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001382 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1383 // all traits except __is_class, __is_enum and __is_union require a the type
1384 // to be complete.
1385 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001386 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001387 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001388 return ExprError();
1389 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001390
1391 // There is no point in eagerly computing the value. The traits are designed
1392 // to be used from type trait templates, so Ty will be a template parameter
1393 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001394 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1395 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001396}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001397
1398QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001399 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001400 const char *OpSpelling = isIndirect ? "->*" : ".*";
1401 // C++ 5.5p2
1402 // The binary operator .* [p3: ->*] binds its second operand, which shall
1403 // be of type "pointer to member of T" (where T is a completely-defined
1404 // class type) [...]
1405 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001406 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001407 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001408 Diag(Loc, diag::err_bad_memptr_rhs)
1409 << OpSpelling << RType << rex->getSourceRange();
1410 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001411 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001412
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001413 QualType Class(MemPtr->getClass(), 0);
1414
1415 // C++ 5.5p2
1416 // [...] to its first operand, which shall be of class T or of a class of
1417 // which T is an unambiguous and accessible base class. [p3: a pointer to
1418 // such a class]
1419 QualType LType = lex->getType();
1420 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001421 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001422 LType = Ptr->getPointeeType().getNonReferenceType();
1423 else {
1424 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001425 << OpSpelling << 1 << LType
1426 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001427 return QualType();
1428 }
1429 }
1430
Douglas Gregora4923eb2009-11-16 21:35:15 +00001431 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001432 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1433 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001434 // FIXME: Would it be useful to print full ambiguity paths, or is that
1435 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001436 if (!IsDerivedFrom(LType, Class, Paths) ||
1437 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001438 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001439 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001440 << (int)isIndirect << lex->getType() <<
1441 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001442 return QualType();
1443 }
1444 }
1445
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001446 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001447 // Diagnose use of pointer-to-member type which when used as
1448 // the functional cast in a pointer-to-member expression.
1449 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1450 return QualType();
1451 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001452 // C++ 5.5p2
1453 // The result is an object or a function of the type specified by the
1454 // second operand.
1455 // The cv qualifiers are the union of those in the pointer and the left side,
1456 // in accordance with 5.5p5 and 5.2.5.
1457 // FIXME: This returns a dereferenced member function pointer as a normal
1458 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001459 // calling them. There's also a GCC extension to get a function pointer to the
1460 // thing, which is another complication, because this type - unlike the type
1461 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001462 // argument.
1463 // We probably need a "MemberFunctionClosureType" or something like that.
1464 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001465 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001466 return Result;
1467}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001468
1469/// \brief Get the target type of a standard or user-defined conversion.
1470static QualType TargetType(const ImplicitConversionSequence &ICS) {
1471 assert((ICS.ConversionKind ==
1472 ImplicitConversionSequence::StandardConversion ||
1473 ICS.ConversionKind ==
1474 ImplicitConversionSequence::UserDefinedConversion) &&
1475 "function only valid for standard or user-defined conversions");
1476 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1477 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1478 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1479}
1480
1481/// \brief Try to convert a type to another according to C++0x 5.16p3.
1482///
1483/// This is part of the parameter validation for the ? operator. If either
1484/// value operand is a class type, the two operands are attempted to be
1485/// converted to each other. This function does the conversion in one direction.
1486/// It emits a diagnostic and returns true only if it finds an ambiguous
1487/// conversion.
1488static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1489 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001490 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001491 // C++0x 5.16p3
1492 // The process for determining whether an operand expression E1 of type T1
1493 // can be converted to match an operand expression E2 of type T2 is defined
1494 // as follows:
1495 // -- If E2 is an lvalue:
1496 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1497 // E1 can be converted to match E2 if E1 can be implicitly converted to
1498 // type "lvalue reference to T2", subject to the constraint that in the
1499 // conversion the reference must bind directly to E1.
1500 if (!Self.CheckReferenceInit(From,
1501 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001502 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001503 /*SuppressUserConversions=*/false,
1504 /*AllowExplicit=*/false,
1505 /*ForceRValue=*/false,
1506 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001507 {
1508 assert((ICS.ConversionKind ==
1509 ImplicitConversionSequence::StandardConversion ||
1510 ICS.ConversionKind ==
1511 ImplicitConversionSequence::UserDefinedConversion) &&
1512 "expected a definite conversion");
1513 bool DirectBinding =
1514 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1515 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1516 if (DirectBinding)
1517 return false;
1518 }
1519 }
1520 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1521 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1522 // -- if E1 and E2 have class type, and the underlying class types are
1523 // the same or one is a base class of the other:
1524 QualType FTy = From->getType();
1525 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001526 const RecordType *FRec = FTy->getAs<RecordType>();
1527 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001528 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1529 if (FRec && TRec && (FRec == TRec ||
1530 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1531 // E1 can be converted to match E2 if the class of T2 is the
1532 // same type as, or a base class of, the class of T1, and
1533 // [cv2 > cv1].
1534 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1535 // Could still fail if there's no copy constructor.
1536 // FIXME: Is this a hard error then, or just a conversion failure? The
1537 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001538 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001539 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001540 /*ForceRValue=*/false,
1541 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001542 }
1543 } else {
1544 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1545 // implicitly converted to the type that expression E2 would have
1546 // if E2 were converted to an rvalue.
1547 // First find the decayed type.
1548 if (TTy->isFunctionType())
1549 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001550 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001551 TTy = Self.Context.getArrayDecayedType(TTy);
1552
1553 // Now try the implicit conversion.
1554 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001555 ICS = Self.TryImplicitConversion(From, TTy,
1556 /*SuppressUserConversions=*/false,
1557 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001558 /*ForceRValue=*/false,
1559 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001560 }
1561 return false;
1562}
1563
1564/// \brief Try to find a common type for two according to C++0x 5.16p5.
1565///
1566/// This is part of the parameter validation for the ? operator. If either
1567/// value operand is a class type, overload resolution is used to find a
1568/// conversion to a common type.
1569static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1570 SourceLocation Loc) {
1571 Expr *Args[2] = { LHS, RHS };
1572 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001573 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001574
1575 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001576 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001577 case Sema::OR_Success:
1578 // We found a match. Perform the conversions on the arguments and move on.
1579 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1580 Best->Conversions[0], "converting") ||
1581 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1582 Best->Conversions[1], "converting"))
1583 break;
1584 return false;
1585
1586 case Sema::OR_No_Viable_Function:
1587 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1588 << LHS->getType() << RHS->getType()
1589 << LHS->getSourceRange() << RHS->getSourceRange();
1590 return true;
1591
1592 case Sema::OR_Ambiguous:
1593 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1594 << LHS->getType() << RHS->getType()
1595 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001596 // FIXME: Print the possible common types by printing the return types of
1597 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001598 break;
1599
1600 case Sema::OR_Deleted:
1601 assert(false && "Conditional operator has only built-in overloads");
1602 break;
1603 }
1604 return true;
1605}
1606
Sebastian Redl76458502009-04-17 16:30:52 +00001607/// \brief Perform an "extended" implicit conversion as returned by
1608/// TryClassUnification.
1609///
1610/// TryClassUnification generates ICSs that include reference bindings.
1611/// PerformImplicitConversion is not suitable for this; it chokes if the
1612/// second part of a standard conversion is ICK_DerivedToBase. This function
1613/// handles the reference binding specially.
1614static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001615 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001616 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1617 ICS.Standard.ReferenceBinding) {
1618 assert(ICS.Standard.DirectBinding &&
1619 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001620 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1621 // redoing all the work.
1622 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001623 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001624 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001625 /*SuppressUserConversions=*/false,
1626 /*AllowExplicit=*/false,
1627 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001628 }
1629 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1630 ICS.UserDefined.After.ReferenceBinding) {
1631 assert(ICS.UserDefined.After.DirectBinding &&
1632 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001633 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001634 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001635 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001636 /*SuppressUserConversions=*/false,
1637 /*AllowExplicit=*/false,
1638 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001639 }
1640 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1641 return true;
1642 return false;
1643}
1644
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001645/// \brief Check the operands of ?: under C++ semantics.
1646///
1647/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1648/// extension. In this case, LHS == Cond. (But they're not aliases.)
1649QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1650 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001651 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1652 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001653
1654 // C++0x 5.16p1
1655 // The first expression is contextually converted to bool.
1656 if (!Cond->isTypeDependent()) {
1657 if (CheckCXXBooleanCondition(Cond))
1658 return QualType();
1659 }
1660
1661 // Either of the arguments dependent?
1662 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1663 return Context.DependentTy;
1664
John McCallb13c87f2009-11-05 09:23:39 +00001665 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1666
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001667 // C++0x 5.16p2
1668 // If either the second or the third operand has type (cv) void, ...
1669 QualType LTy = LHS->getType();
1670 QualType RTy = RHS->getType();
1671 bool LVoid = LTy->isVoidType();
1672 bool RVoid = RTy->isVoidType();
1673 if (LVoid || RVoid) {
1674 // ... then the [l2r] conversions are performed on the second and third
1675 // operands ...
1676 DefaultFunctionArrayConversion(LHS);
1677 DefaultFunctionArrayConversion(RHS);
1678 LTy = LHS->getType();
1679 RTy = RHS->getType();
1680
1681 // ... and one of the following shall hold:
1682 // -- The second or the third operand (but not both) is a throw-
1683 // expression; the result is of the type of the other and is an rvalue.
1684 bool LThrow = isa<CXXThrowExpr>(LHS);
1685 bool RThrow = isa<CXXThrowExpr>(RHS);
1686 if (LThrow && !RThrow)
1687 return RTy;
1688 if (RThrow && !LThrow)
1689 return LTy;
1690
1691 // -- Both the second and third operands have type void; the result is of
1692 // type void and is an rvalue.
1693 if (LVoid && RVoid)
1694 return Context.VoidTy;
1695
1696 // Neither holds, error.
1697 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1698 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1699 << LHS->getSourceRange() << RHS->getSourceRange();
1700 return QualType();
1701 }
1702
1703 // Neither is void.
1704
1705 // C++0x 5.16p3
1706 // Otherwise, if the second and third operand have different types, and
1707 // either has (cv) class type, and attempt is made to convert each of those
1708 // operands to the other.
1709 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1710 (LTy->isRecordType() || RTy->isRecordType())) {
1711 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1712 // These return true if a single direction is already ambiguous.
1713 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1714 return QualType();
1715 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1716 return QualType();
1717
1718 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1719 ImplicitConversionSequence::BadConversion;
1720 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1721 ImplicitConversionSequence::BadConversion;
1722 // If both can be converted, [...] the program is ill-formed.
1723 if (HaveL2R && HaveR2L) {
1724 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1725 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1726 return QualType();
1727 }
1728
1729 // If exactly one conversion is possible, that conversion is applied to
1730 // the chosen operand and the converted operands are used in place of the
1731 // original operands for the remainder of this section.
1732 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001733 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001734 return QualType();
1735 LTy = LHS->getType();
1736 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001737 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001738 return QualType();
1739 RTy = RHS->getType();
1740 }
1741 }
1742
1743 // C++0x 5.16p4
1744 // If the second and third operands are lvalues and have the same type,
1745 // the result is of that type [...]
1746 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1747 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1748 RHS->isLvalue(Context) == Expr::LV_Valid)
1749 return LTy;
1750
1751 // C++0x 5.16p5
1752 // Otherwise, the result is an rvalue. If the second and third operands
1753 // do not have the same type, and either has (cv) class type, ...
1754 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1755 // ... overload resolution is used to determine the conversions (if any)
1756 // to be applied to the operands. If the overload resolution fails, the
1757 // program is ill-formed.
1758 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1759 return QualType();
1760 }
1761
1762 // C++0x 5.16p6
1763 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1764 // conversions are performed on the second and third operands.
1765 DefaultFunctionArrayConversion(LHS);
1766 DefaultFunctionArrayConversion(RHS);
1767 LTy = LHS->getType();
1768 RTy = RHS->getType();
1769
1770 // After those conversions, one of the following shall hold:
1771 // -- The second and third operands have the same type; the result
1772 // is of that type.
1773 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1774 return LTy;
1775
1776 // -- The second and third operands have arithmetic or enumeration type;
1777 // the usual arithmetic conversions are performed to bring them to a
1778 // common type, and the result is of that type.
1779 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1780 UsualArithmeticConversions(LHS, RHS);
1781 return LHS->getType();
1782 }
1783
1784 // -- The second and third operands have pointer type, or one has pointer
1785 // type and the other is a null pointer constant; pointer conversions
1786 // and qualification conversions are performed to bring them to their
1787 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001788 QualType Composite = FindCompositePointerType(LHS, RHS);
1789 if (!Composite.isNull())
1790 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001791
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001792 // Fourth bullet is same for pointers-to-member. However, the possible
1793 // conversions are far more limited: we have null-to-pointer, upcast of
1794 // containing class, and second-level cv-ness.
1795 // cv-ness is not a union, but must match one of the two operands. (Which,
1796 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001797 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1798 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001799 if (LMemPtr &&
1800 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001801 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001802 return LTy;
1803 }
Douglas Gregorce940492009-09-25 04:25:58 +00001804 if (RMemPtr &&
1805 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001806 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001807 return RTy;
1808 }
1809 if (LMemPtr && RMemPtr) {
1810 QualType LPointee = LMemPtr->getPointeeType();
1811 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001812
1813 QualifierCollector LPQuals, RPQuals;
1814 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1815 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1816
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001817 // First, we check that the unqualified pointee type is the same. If it's
1818 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001819 if (LPCan == RPCan) {
1820
1821 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001822 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001823
1824 Qualifiers MergedQuals = LPQuals + RPQuals;
1825
1826 bool CompatibleQuals = true;
1827 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1828 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1829 CompatibleQuals = false;
1830 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1831 // FIXME:
1832 // C99 6.5.15 as modified by TR 18037:
1833 // If the second and third operands are pointers into different
1834 // address spaces, the address spaces must overlap.
1835 CompatibleQuals = false;
1836 // FIXME: GC qualifiers?
1837
1838 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001839 // Third, we check if either of the container classes is derived from
1840 // the other.
1841 QualType LContainer(LMemPtr->getClass(), 0);
1842 QualType RContainer(RMemPtr->getClass(), 0);
1843 QualType MoreDerived;
1844 if (Context.getCanonicalType(LContainer) ==
1845 Context.getCanonicalType(RContainer))
1846 MoreDerived = LContainer;
1847 else if (IsDerivedFrom(LContainer, RContainer))
1848 MoreDerived = LContainer;
1849 else if (IsDerivedFrom(RContainer, LContainer))
1850 MoreDerived = RContainer;
1851
1852 if (!MoreDerived.isNull()) {
1853 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1854 // We don't use ImpCastExprToType here because this could still fail
1855 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001856 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1857 QualType Common
1858 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001859 if (PerformImplicitConversion(LHS, Common, "converting"))
1860 return QualType();
1861 if (PerformImplicitConversion(RHS, Common, "converting"))
1862 return QualType();
1863 return Common;
1864 }
1865 }
1866 }
1867 }
1868
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001869 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1870 << LHS->getType() << RHS->getType()
1871 << LHS->getSourceRange() << RHS->getSourceRange();
1872 return QualType();
1873}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001874
1875/// \brief Find a merged pointer type and convert the two expressions to it.
1876///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001877/// This finds the composite pointer type (or member pointer type) for @p E1
1878/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1879/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001880/// It does not emit diagnostics.
1881QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1882 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1883 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Douglas Gregor20b3e992009-08-24 17:42:35 +00001885 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1886 !T2->isPointerType() && !T2->isMemberPointerType())
1887 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001888
1889 // C++0x 5.9p2
1890 // Pointer conversions and qualification conversions are performed on
1891 // pointer operands to bring them to their composite pointer type. If
1892 // one operand is a null pointer constant, the composite pointer type is
1893 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001894 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001895 if (T2->isMemberPointerType())
1896 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1897 else
1898 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001899 return T2;
1900 }
Douglas Gregorce940492009-09-25 04:25:58 +00001901 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001902 if (T1->isMemberPointerType())
1903 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1904 else
1905 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001906 return T1;
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor20b3e992009-08-24 17:42:35 +00001909 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001910 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1911 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001912 return QualType();
1913
1914 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1915 // the other has type "pointer to cv2 T" and the composite pointer type is
1916 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1917 // Otherwise, the composite pointer type is a pointer type similar to the
1918 // type of one of the operands, with a cv-qualification signature that is
1919 // the union of the cv-qualification signatures of the operand types.
1920 // In practice, the first part here is redundant; it's subsumed by the second.
1921 // What we do here is, we build the two possible composite types, and try the
1922 // conversions in both directions. If only one works, or if the two composite
1923 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001924 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001925 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1926 QualifierVector QualifierUnion;
1927 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1928 ContainingClassVector;
1929 ContainingClassVector MemberOfClass;
1930 QualType Composite1 = Context.getCanonicalType(T1),
1931 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001932 do {
1933 const PointerType *Ptr1, *Ptr2;
1934 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1935 (Ptr2 = Composite2->getAs<PointerType>())) {
1936 Composite1 = Ptr1->getPointeeType();
1937 Composite2 = Ptr2->getPointeeType();
1938 QualifierUnion.push_back(
1939 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1940 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1941 continue;
1942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Douglas Gregor20b3e992009-08-24 17:42:35 +00001944 const MemberPointerType *MemPtr1, *MemPtr2;
1945 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1946 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1947 Composite1 = MemPtr1->getPointeeType();
1948 Composite2 = MemPtr2->getPointeeType();
1949 QualifierUnion.push_back(
1950 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1951 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1952 MemPtr2->getClass()));
1953 continue;
1954 }
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Douglas Gregor20b3e992009-08-24 17:42:35 +00001956 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Douglas Gregor20b3e992009-08-24 17:42:35 +00001958 // Cannot unwrap any more types.
1959 break;
1960 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Douglas Gregor20b3e992009-08-24 17:42:35 +00001962 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001963 ContainingClassVector::reverse_iterator MOC
1964 = MemberOfClass.rbegin();
1965 for (QualifierVector::reverse_iterator
1966 I = QualifierUnion.rbegin(),
1967 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001968 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001969 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001970 if (MOC->first && MOC->second) {
1971 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001972 Composite1 = Context.getMemberPointerType(
1973 Context.getQualifiedType(Composite1, Quals),
1974 MOC->first);
1975 Composite2 = Context.getMemberPointerType(
1976 Context.getQualifiedType(Composite2, Quals),
1977 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001978 } else {
1979 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001980 Composite1
1981 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1982 Composite2
1983 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001984 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001985 }
1986
Mike Stump1eb44332009-09-09 15:08:12 +00001987 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001988 TryImplicitConversion(E1, Composite1,
1989 /*SuppressUserConversions=*/false,
1990 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001991 /*ForceRValue=*/false,
1992 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001993 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001994 TryImplicitConversion(E2, Composite1,
1995 /*SuppressUserConversions=*/false,
1996 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001997 /*ForceRValue=*/false,
1998 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002000 ImplicitConversionSequence E1ToC2, E2ToC2;
2001 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2002 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2003 if (Context.getCanonicalType(Composite1) !=
2004 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002005 E1ToC2 = TryImplicitConversion(E1, Composite2,
2006 /*SuppressUserConversions=*/false,
2007 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002008 /*ForceRValue=*/false,
2009 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002010 E2ToC2 = TryImplicitConversion(E2, Composite2,
2011 /*SuppressUserConversions=*/false,
2012 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002013 /*ForceRValue=*/false,
2014 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002015 }
2016
2017 bool ToC1Viable = E1ToC1.ConversionKind !=
2018 ImplicitConversionSequence::BadConversion
2019 && E2ToC1.ConversionKind !=
2020 ImplicitConversionSequence::BadConversion;
2021 bool ToC2Viable = E1ToC2.ConversionKind !=
2022 ImplicitConversionSequence::BadConversion
2023 && E2ToC2.ConversionKind !=
2024 ImplicitConversionSequence::BadConversion;
2025 if (ToC1Viable && !ToC2Viable) {
2026 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2027 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2028 return Composite1;
2029 }
2030 if (ToC2Viable && !ToC1Viable) {
2031 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2032 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2033 return Composite2;
2034 }
2035 return QualType();
2036}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002037
Anders Carlssondef11992009-05-30 20:36:53 +00002038Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002039 if (!Context.getLangOptions().CPlusPlus)
2040 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Ted Kremenek6217b802009-07-29 21:53:49 +00002042 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002043 if (!RT)
2044 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Anders Carlssondef11992009-05-30 20:36:53 +00002046 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2047 if (RD->hasTrivialDestructor())
2048 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Anders Carlsson283e4d52009-09-14 01:30:44 +00002050 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2051 QualType Ty = CE->getCallee()->getType();
2052 if (const PointerType *PT = Ty->getAs<PointerType>())
2053 Ty = PT->getPointeeType();
2054
John McCall183700f2009-09-21 23:43:11 +00002055 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002056 if (FTy->getResultType()->isReferenceType())
2057 return Owned(E);
2058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002060 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002061 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002062 if (CXXDestructorDecl *Destructor =
2063 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2064 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002065 // FIXME: Add the temporary to the temporaries vector.
2066 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2067}
2068
Mike Stump1eb44332009-09-09 15:08:12 +00002069Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002070 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002071 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002073 if (ExprTemporaries.empty())
2074 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002076 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002077 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002078 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002079 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002080 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002082 return E;
2083}
2084
Mike Stump1eb44332009-09-09 15:08:12 +00002085Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002086Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2087 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2088 // Since this might be a postfix expression, get rid of ParenListExprs.
2089 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002091 Expr *BaseExpr = (Expr*)Base.get();
2092 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002094 QualType BaseType = BaseExpr->getType();
2095 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002096 // If we have a pointer to a dependent type and are using the -> operator,
2097 // the object type is the type that the pointer points to. We might still
2098 // have enough information about that type to do something useful.
2099 if (OpKind == tok::arrow)
2100 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2101 BaseType = Ptr->getPointeeType();
2102
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002103 ObjectType = BaseType.getAsOpaquePtr();
2104 return move(Base);
2105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002107 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002108 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002109 // returned, with the original second operand.
2110 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002111 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002112 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002113 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002114 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002115
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002116 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002117 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002118 BaseExpr = (Expr*)Base.get();
2119 if (BaseExpr == NULL)
2120 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002121 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002122 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002123 BaseType = BaseExpr->getType();
2124 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002125 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002126 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002127 for (unsigned i = 0; i < Locations.size(); i++)
2128 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002129 return ExprError();
2130 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002131 }
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Douglas Gregor31658df2009-11-20 19:58:21 +00002133 if (BaseType->isPointerType())
2134 BaseType = BaseType->getPointeeType();
2135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
2137 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002138 // vector types or Objective-C interfaces. Just return early and let
2139 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002140 if (!BaseType->isRecordType()) {
2141 // C++ [basic.lookup.classref]p2:
2142 // [...] If the type of the object expression is of pointer to scalar
2143 // type, the unqualified-id is looked up in the context of the complete
2144 // postfix-expression.
2145 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002146 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002147 }
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Douglas Gregor03c57052009-11-17 05:17:33 +00002149 // The object type must be complete (or dependent).
2150 if (!BaseType->isDependentType() &&
2151 RequireCompleteType(OpLoc, BaseType,
2152 PDiag(diag::err_incomplete_member_access)))
2153 return ExprError();
2154
Douglas Gregorc68afe22009-09-03 21:38:09 +00002155 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002156 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002157 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002158 // type C (or of pointer to a class type C), the unqualified-id is looked
2159 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002160 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002161
Mike Stump1eb44332009-09-09 15:08:12 +00002162 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002163}
2164
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002165CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2166 CXXMethodDecl *Method) {
2167 MemberExpr *ME =
2168 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2169 SourceLocation(), Method->getType());
2170 QualType ResultType;
2171 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2172 ResultType = Conv->getConversionType().getNonReferenceType();
2173 else
2174 ResultType = Method->getResultType().getNonReferenceType();
2175
Douglas Gregor7edfb692009-11-23 12:27:39 +00002176 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2177 CXXMemberCallExpr *CE =
2178 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2179 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002180 return CE;
2181}
2182
Anders Carlsson0aebc812009-09-09 21:33:21 +00002183Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2184 QualType Ty,
2185 CastExpr::CastKind Kind,
2186 CXXMethodDecl *Method,
2187 ExprArg Arg) {
2188 Expr *From = Arg.takeAs<Expr>();
2189
2190 switch (Kind) {
2191 default: assert(0 && "Unhandled cast kind!");
2192 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002193 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2194
2195 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2196 MultiExprArg(*this, (void **)&From, 1),
2197 CastLoc, ConstructorArgs))
2198 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002199
2200 OwningExprResult Result =
2201 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2202 move_arg(ConstructorArgs));
2203 if (Result.isInvalid())
2204 return ExprError();
2205
2206 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002207 }
2208
2209 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002210 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2211
2212 // Cast to base if needed.
2213 if (PerformObjectArgumentInitialization(From, Method))
2214 return ExprError();
2215
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002216 // Create an implicit call expr that calls it.
2217 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002218 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002219 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002220 }
2221}
2222
Anders Carlsson165a0a02009-05-17 18:41:29 +00002223Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2224 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002225 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002226 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002227 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002228
Anders Carlssonec773872009-08-25 23:46:41 +00002229
Anders Carlsson165a0a02009-05-17 18:41:29 +00002230 return Owned(FullExpr);
2231}
Douglas Gregore961afb2009-10-22 07:08:30 +00002232
2233/// \brief Determine whether a reference to the given declaration in the
2234/// current context is an implicit member access
2235/// (C++ [class.mfct.non-static]p2).
2236///
2237/// FIXME: Should Objective-C also use this approach?
2238///
2239/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2240/// name of the declaration referenced.
2241///
2242/// \param D the declaration being referenced from the current scope.
2243///
2244/// \param NameLoc the location of the name in the source.
2245///
2246/// \param ThisType if the reference to this declaration is an implicit member
2247/// access, will be set to the type of the "this" pointer to be used when
2248/// building that implicit member access.
2249///
2250/// \param MemberType if the reference to this declaration is an implicit
2251/// member access, will be set to the type of the member being referenced
2252/// (for use at the type of the resulting member access expression).
2253///
2254/// \returns true if this is an implicit member reference (in which case
2255/// \p ThisType and \p MemberType will be set), or false if it is not an
2256/// implicit member reference.
John McCallf7a1a742009-11-24 19:00:30 +00002257bool Sema::isImplicitMemberReference(const CXXScopeSpec &SS, NamedDecl *D,
Douglas Gregore961afb2009-10-22 07:08:30 +00002258 SourceLocation NameLoc, QualType &ThisType,
2259 QualType &MemberType) {
2260 // If this isn't a C++ method, then it isn't an implicit member reference.
2261 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2262 if (!MD || MD->isStatic())
2263 return false;
2264
2265 // C++ [class.mfct.nonstatic]p2:
2266 // [...] if name lookup (3.4.1) resolves the name in the
2267 // id-expression to a nonstatic nontype member of class X or of
2268 // a base class of X, the id-expression is transformed into a
2269 // class member access expression (5.2.5) using (*this) (9.3.2)
2270 // as the postfix-expression to the left of the '.' operator.
2271 DeclContext *Ctx = 0;
2272 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2273 Ctx = FD->getDeclContext();
2274 MemberType = FD->getType();
2275
2276 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2277 MemberType = RefType->getPointeeType();
2278 else if (!FD->isMutable())
2279 MemberType
2280 = Context.getQualifiedType(MemberType,
2281 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
John McCallba135432009-11-21 08:51:07 +00002282 } else if (isa<UnresolvedUsingValueDecl>(D)) {
2283 Ctx = D->getDeclContext();
2284 MemberType = Context.DependentTy;
Douglas Gregore961afb2009-10-22 07:08:30 +00002285 } else {
2286 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2287 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2288 FunctionTemplateDecl *FunTmpl = 0;
2289 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2290 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2291
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002292 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002293 if (Method && !Method->isStatic()) {
2294 Ctx = Method->getParent();
2295 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2296 MemberType = Method->getType();
2297 else
2298 MemberType = Context.OverloadTy;
2299 break;
2300 }
2301 }
2302 }
2303
2304 if (!Ctx || !Ctx->isRecord())
2305 return false;
2306
2307 // Determine whether the declaration(s) we found are actually in a base
2308 // class. If not, this isn't an implicit member reference.
2309 ThisType = MD->getThisType(Context);
Douglas Gregor7a343142009-11-01 17:08:18 +00002310
Douglas Gregore961afb2009-10-22 07:08:30 +00002311 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2312 QualType ClassType
2313 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2314 return Context.hasSameType(CtxType, ClassType) ||
2315 IsDerivedFrom(ClassType, CtxType);
2316}
2317