blob: 1ad931e5416aeb76a60bb599d952a3b79afe4100 [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"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Sebastian Redlc42e1182008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000033
Douglas Gregorf57f2072009-12-23 20:51:04 +000034 if (isType) {
35 // C++ [expr.typeid]p4:
36 // The top-level cv-qualifiers of the lvalue expression or the type-id
37 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000038 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +000039 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +000040 QualType T = GetTypeFromParser(TyOrExpr);
41 if (T.isNull())
42 return ExprError();
43
44 // C++ [expr.typeid]p4:
45 // If the type of the type-id is a class type or a reference to a class
46 // type, the class shall be completely-defined.
47 QualType CheckT = T;
48 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
49 CheckT = RefType->getPointeeType();
50
51 if (CheckT->getAs<RecordType>() &&
52 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
53 return ExprError();
54
55 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +000056 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000057
Chris Lattner572af492008-11-20 05:51:55 +000058 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000059 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
60 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +000061 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +000062 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000063 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000064
65 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
66
Douglas Gregorac7610d2009-06-22 20:57:11 +000067 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000068 bool isUnevaluatedOperand = true;
69 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +000070 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000072 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000073 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +000074 // C++ [expr.typeid]p3:
75 // When typeid is applied to an expression other than an lvalue of a
76 // polymorphic class type [...] [the] expression is an unevaluated
77 // operand. [...]
78 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +000079 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +000080 else {
81 // C++ [expr.typeid]p3:
82 // [...] If the type of the expression is a class type, the class
83 // shall be completely-defined.
Douglas Gregor765ccba2009-12-23 21:06:06 +000084 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
85 return ExprError();
Douglas Gregorf57f2072009-12-23 20:51:04 +000086 }
87 }
88
89 // C++ [expr.typeid]p4:
90 // [...] If the type of the type-id is a reference to a possibly
91 // cv-qualified type, the result of the typeid expression refers to a
92 // std::type_info object representing the cv-unqualified referenced
93 // type.
94 if (T.hasQualifiers()) {
95 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
96 E->isLvalue(Context));
97 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +000098 }
99 }
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Douglas Gregor2afce722009-11-26 00:44:06 +0000101 // If this is an unevaluated operand, clear out the set of
102 // declaration references we have been computing and eliminate any
103 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000104 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000105 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
109 TypeInfoType.withConst(),
110 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000111}
112
Steve Naroff1b273c42007-09-16 14:56:35 +0000113/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000114Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000115Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000116 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
119 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000120}
Chris Lattner50dd2892008-02-26 00:51:44 +0000121
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000122/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
123Action::OwningExprResult
124Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
125 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
126}
127
Chris Lattner50dd2892008-02-26 00:51:44 +0000128/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult
130Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000131 Expr *Ex = E.takeAs<Expr>();
132 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
133 return ExprError();
134 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
135}
136
137/// CheckCXXThrowOperand - Validate the operand of a throw.
138bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
139 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000140 // A throw-expression initializes a temporary object, called the exception
141 // object, the type of which is determined by removing any top-level
142 // cv-qualifiers from the static type of the operand of throw and adjusting
143 // the type from "array of T" or "function returning T" to "pointer to T"
144 // or "pointer to function returning T", [...]
145 if (E->getType().hasQualifiers())
146 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
147 E->isLvalue(Context) == Expr::LV_Valid);
148
Sebastian Redl972041f2009-04-27 20:27:31 +0000149 DefaultFunctionArrayConversion(E);
150
151 // If the type of the exception would be an incomplete type or a pointer
152 // to an incomplete type other than (cv) void the program is ill-formed.
153 QualType Ty = E->getType();
154 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000155 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000156 Ty = Ptr->getPointeeType();
157 isPointer = 1;
158 }
159 if (!isPointer || !Ty->isVoidType()) {
160 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000161 PDiag(isPointer ? diag::err_throw_incomplete_ptr
162 : diag::err_throw_incomplete)
163 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000164 return true;
165 }
166
167 // FIXME: Construct a temporary here.
168 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000169}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000172 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
173 /// is a non-lvalue expression whose value is the address of the object for
174 /// which the function is called.
175
Sebastian Redlf53597f2009-03-15 17:47:39 +0000176 if (!isa<FunctionDecl>(CurContext))
177 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000178
179 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
180 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000182 MD->getThisType(Context),
183 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000184
Sebastian Redlf53597f2009-03-15 17:47:39 +0000185 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000186}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000187
188/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
189/// Can be interpreted either as function-style casting ("int(x)")
190/// or class type construction ("ClassType(x,y,z)")
191/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000192Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000193Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
194 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000195 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000196 SourceLocation *CommaLocs,
197 SourceLocation RParenLoc) {
198 assert(TypeRep && "Missing type!");
John McCall9d125032010-01-15 18:39:57 +0000199 TypeSourceInfo *TInfo;
200 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
201 if (!TInfo)
202 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000203 unsigned NumExprs = exprs.size();
204 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000205 SourceLocation TyBeginLoc = TypeRange.getBegin();
206 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
207
Sebastian Redlf53597f2009-03-15 17:47:39 +0000208 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000209 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000210 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000211
212 return Owned(CXXUnresolvedConstructExpr::Create(Context,
213 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000214 LParenLoc,
215 Exprs, NumExprs,
216 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000217 }
218
Anders Carlssonbb60a502009-08-27 03:53:50 +0000219 if (Ty->isArrayType())
220 return ExprError(Diag(TyBeginLoc,
221 diag::err_value_init_for_array_type) << FullRange);
222 if (!Ty->isVoidType() &&
223 RequireCompleteType(TyBeginLoc, Ty,
224 PDiag(diag::err_invalid_incomplete_type_use)
225 << FullRange))
226 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000227
Anders Carlssonbb60a502009-08-27 03:53:50 +0000228 if (RequireNonAbstractType(TyBeginLoc, Ty,
229 diag::err_allocation_of_abstract_type))
230 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000231
232
Douglas Gregor506ae412009-01-16 18:33:17 +0000233 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000234 // If the expression list is a single expression, the type conversion
235 // expression is equivalent (in definedness, and if defined in meaning) to the
236 // corresponding cast expression.
237 //
238 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000239 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000240 CXXMethodDecl *Method = 0;
241 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
242 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000243 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000244
245 exprs.release();
246 if (Method) {
247 OwningExprResult CastArg
248 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
249 Kind, Method, Owned(Exprs[0]));
250 if (CastArg.isInvalid())
251 return ExprError();
252
253 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000254 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000255
256 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000257 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000258 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000259 }
260
Ted Kremenek6217b802009-07-29 21:53:49 +0000261 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000262 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000263
Mike Stump1eb44332009-09-09 15:08:12 +0000264 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000265 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000266 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
267
Douglas Gregor506ae412009-01-16 18:33:17 +0000268 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000269 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000270 TypeRange.getBegin(),
271 SourceRange(TypeRange.getBegin(),
272 RParenLoc),
273 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000274 InitializationKind::CreateDirect(TypeRange.getBegin(),
275 LParenLoc,
276 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000277 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000278
Sebastian Redlf53597f2009-03-15 17:47:39 +0000279 if (!Constructor)
280 return ExprError();
281
Mike Stump1eb44332009-09-09 15:08:12 +0000282 OwningExprResult Result =
283 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000284 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000285 if (Result.isInvalid())
286 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Anders Carlssone7624a72009-08-27 05:08:22 +0000288 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000289 }
290
291 // Fall through to value-initialize an object of class type that
292 // doesn't have a user-declared default constructor.
293 }
294
295 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000296 // If the expression list specifies more than a single value, the type shall
297 // be a class with a suitably declared constructor.
298 //
299 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000300 return ExprError(Diag(CommaLocs[0],
301 diag::err_builtin_func_cast_more_than_one_arg)
302 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000303
304 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000305 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000306 // The expression T(), where T is a simple-type-specifier for a non-array
307 // complete object type or the (possibly cv-qualified) void type, creates an
308 // rvalue of the specified type, which is value-initialized.
309 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000310 exprs.release();
311 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000312}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000313
314
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000315/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
316/// @code new (memory) int[size][4] @endcode
317/// or
318/// @code ::new Foo(23, "hello") @endcode
319/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000320Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000321Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000322 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000323 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000324 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000325 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000326 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000327 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000328 // If the specified type is an array, unwrap it and save the expression.
329 if (D.getNumTypeObjects() > 0 &&
330 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
331 DeclaratorChunk &Chunk = D.getTypeObject(0);
332 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000333 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
334 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000335 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000336 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
337 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000338
339 if (ParenTypeId) {
340 // Can't have dynamic array size when the type-id is in parentheses.
341 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
342 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
343 !NumElts->isIntegerConstantExpr(Context)) {
344 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
345 << NumElts->getSourceRange();
346 return ExprError();
347 }
348 }
349
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000350 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000351 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000352 }
353
Douglas Gregor043cad22009-09-11 00:18:58 +0000354 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000355 if (ArraySize) {
356 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000357 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
358 break;
359
360 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
361 if (Expr *NumElts = (Expr *)Array.NumElts) {
362 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
363 !NumElts->isIntegerConstantExpr(Context)) {
364 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
365 << NumElts->getSourceRange();
366 return ExprError();
367 }
368 }
369 }
370 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000371
John McCalla93c9342009-12-07 02:54:59 +0000372 //FIXME: Store TypeSourceInfo in CXXNew expression.
373 TypeSourceInfo *TInfo = 0;
374 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000375 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000376 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000377
Mike Stump1eb44332009-09-09 15:08:12 +0000378 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000379 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000380 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000381 PlacementRParen,
382 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000383 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000384 D.getSourceRange().getBegin(),
385 D.getSourceRange(),
386 Owned(ArraySize),
387 ConstructorLParen,
388 move(ConstructorArgs),
389 ConstructorRParen);
390}
391
Mike Stump1eb44332009-09-09 15:08:12 +0000392Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000393Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
394 SourceLocation PlacementLParen,
395 MultiExprArg PlacementArgs,
396 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000397 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000398 QualType AllocType,
399 SourceLocation TypeLoc,
400 SourceRange TypeRange,
401 ExprArg ArraySizeE,
402 SourceLocation ConstructorLParen,
403 MultiExprArg ConstructorArgs,
404 SourceLocation ConstructorRParen) {
405 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000406 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000407
Douglas Gregor3433cf72009-05-21 00:00:09 +0000408 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000409
410 // That every array dimension except the first is constant was already
411 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000412
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000413 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
414 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000415 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000416 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000417 QualType SizeType = ArraySize->getType();
418 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000419 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
420 diag::err_array_size_not_integral)
421 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000422 // Let's see if this is a constant < 0. If so, we reject it out of hand.
423 // We don't care about special rules, so we tell the machinery it's not
424 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000425 if (!ArraySize->isValueDependent()) {
426 llvm::APSInt Value;
427 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
428 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000429 llvm::APInt::getNullValue(Value.getBitWidth()),
430 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000431 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
432 diag::err_typecheck_negative_array_size)
433 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000434 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000435 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000436
Eli Friedman73c39ab2009-10-20 08:27:19 +0000437 ImpCastExprToType(ArraySize, Context.getSizeType(),
438 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000439 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000440
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000441 FunctionDecl *OperatorNew = 0;
442 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
444 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000445
Sebastian Redl28507842009-02-26 14:39:58 +0000446 if (!AllocType->isDependentType() &&
447 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
448 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000449 SourceRange(PlacementLParen, PlacementRParen),
450 UseGlobal, AllocType, ArraySize, PlaceArgs,
451 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000452 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000453 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000454 if (OperatorNew) {
455 // Add default arguments, if any.
456 const FunctionProtoType *Proto =
457 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000458 VariadicCallType CallType =
459 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000460 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
461 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000462 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000463 if (Invalid)
464 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000465
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000466 NumPlaceArgs = AllPlaceArgs.size();
467 if (NumPlaceArgs > 0)
468 PlaceArgs = &AllPlaceArgs[0];
469 }
470
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000471 bool Init = ConstructorLParen.isValid();
472 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000473 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000474 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
475 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000476 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
477
Douglas Gregor99a2e602009-12-16 01:38:02 +0000478 if (!AllocType->isDependentType() &&
479 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
480 // C++0x [expr.new]p15:
481 // A new-expression that creates an object of type T initializes that
482 // object as follows:
483 InitializationKind Kind
484 // - If the new-initializer is omitted, the object is default-
485 // initialized (8.5); if no initialization is performed,
486 // the object has indeterminate value
487 = !Init? InitializationKind::CreateDefault(TypeLoc)
488 // - Otherwise, the new-initializer is interpreted according to the
489 // initialization rules of 8.5 for direct-initialization.
490 : InitializationKind::CreateDirect(TypeLoc,
491 ConstructorLParen,
492 ConstructorRParen);
493
Douglas Gregor99a2e602009-12-16 01:38:02 +0000494 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000495 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000496 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000497 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
498 move(ConstructorArgs));
499 if (FullInit.isInvalid())
500 return ExprError();
501
502 // FullInit is our initializer; walk through it to determine if it's a
503 // constructor call, which CXXNewExpr handles directly.
504 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
505 if (CXXBindTemporaryExpr *Binder
506 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
507 FullInitExpr = Binder->getSubExpr();
508 if (CXXConstructExpr *Construct
509 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
510 Constructor = Construct->getConstructor();
511 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
512 AEnd = Construct->arg_end();
513 A != AEnd; ++A)
514 ConvertedConstructorArgs.push_back(A->Retain());
515 } else {
516 // Take the converted initializer.
517 ConvertedConstructorArgs.push_back(FullInit.release());
518 }
519 } else {
520 // No initialization required.
521 }
522
523 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000524 NumConsArgs = ConvertedConstructorArgs.size();
525 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000526 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000527
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000528 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000529
Sebastian Redlf53597f2009-03-15 17:47:39 +0000530 PlacementArgs.release();
531 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000532 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000533 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000535 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000536 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000537}
538
539/// CheckAllocatedType - Checks that a type is suitable as the allocated type
540/// in a new-expression.
541/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000542bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000543 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000544 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
545 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000546 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000547 return Diag(Loc, diag::err_bad_new_type)
548 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000549 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000550 return Diag(Loc, diag::err_bad_new_type)
551 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000552 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000553 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000554 PDiag(diag::err_new_incomplete_type)
555 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000556 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000557 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000558 diag::err_allocation_of_abstract_type))
559 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000560
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000561 return false;
562}
563
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000564/// FindAllocationFunctions - Finds the overloads of operator new and delete
565/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000566bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
567 bool UseGlobal, QualType AllocType,
568 bool IsArray, Expr **PlaceArgs,
569 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000571 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000572 // --- Choosing an allocation function ---
573 // C++ 5.3.4p8 - 14 & 18
574 // 1) If UseGlobal is true, only look in the global scope. Else, also look
575 // in the scope of the allocated class.
576 // 2) If an array size is given, look for operator new[], else look for
577 // operator new.
578 // 3) The first argument is always size_t. Append the arguments from the
579 // placement form.
580 // FIXME: Also find the appropriate delete operator.
581
582 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
583 // We don't care about the actual value of this argument.
584 // FIXME: Should the Sema create the expression and embed it in the syntax
585 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000586 IntegerLiteral Size(llvm::APInt::getNullValue(
587 Context.Target.getPointerWidth(0)),
588 Context.getSizeType(),
589 SourceLocation());
590 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000591 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
592
593 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
594 IsArray ? OO_Array_New : OO_New);
595 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000597 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000598 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000599 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000600 AllocArgs.size(), Record, /*AllowMissing=*/true,
601 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000602 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000603 }
604 if (!OperatorNew) {
605 // Didn't find a member overload. Look for a global one.
606 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000608 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000609 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
610 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000611 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000612 }
613
Anders Carlssond9583892009-05-31 20:26:12 +0000614 // FindAllocationOverload can change the passed in arguments, so we need to
615 // copy them back.
616 if (NumPlaceArgs > 0)
617 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000619 return false;
620}
621
Sebastian Redl7f662392008-12-04 22:20:51 +0000622/// FindAllocationOverload - Find an fitting overload for the allocation
623/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000624bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
625 DeclarationName Name, Expr** Args,
626 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000627 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000628 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
629 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000630 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000631 if (AllowMissing)
632 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000633 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000634 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000635 }
636
John McCallf36e02d2009-10-09 21:13:30 +0000637 // FIXME: handle ambiguity
638
Sebastian Redl7f662392008-12-04 22:20:51 +0000639 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000640 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
641 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000642 // Even member operator new/delete are implicitly treated as
643 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000644 if (FunctionDecl *Fn =
645 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000646 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
647 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000648 continue;
649 }
650
651 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000652 }
653
654 // Do the resolution.
655 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000656 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000657 case OR_Success: {
658 // Got one!
659 FunctionDecl *FnDecl = Best->Function;
660 // The first argument is size_t, and the first parameter must be size_t,
661 // too. This is checked on declaration and can be assumed. (It can't be
662 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000663 // Whatch out for variadic allocator function.
664 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
665 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000666 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000667 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000668 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000669 return true;
670 }
671 Operator = FnDecl;
672 return false;
673 }
674
675 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000676 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000677 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000678 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000679 return true;
680
681 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000682 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000683 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000684 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000685 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000686
687 case OR_Deleted:
688 Diag(StartLoc, diag::err_ovl_deleted_call)
689 << Best->Function->isDeleted()
690 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000691 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000692 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000693 }
694 assert(false && "Unreachable, bad result from BestViableFunction");
695 return true;
696}
697
698
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000699/// DeclareGlobalNewDelete - Declare the global forms of operator new and
700/// delete. These are:
701/// @code
702/// void* operator new(std::size_t) throw(std::bad_alloc);
703/// void* operator new[](std::size_t) throw(std::bad_alloc);
704/// void operator delete(void *) throw();
705/// void operator delete[](void *) throw();
706/// @endcode
707/// Note that the placement and nothrow forms of new are *not* implicitly
708/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000709void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000710 if (GlobalNewDeleteDeclared)
711 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000712
713 // C++ [basic.std.dynamic]p2:
714 // [...] The following allocation and deallocation functions (18.4) are
715 // implicitly declared in global scope in each translation unit of a
716 // program
717 //
718 // void* operator new(std::size_t) throw(std::bad_alloc);
719 // void* operator new[](std::size_t) throw(std::bad_alloc);
720 // void operator delete(void*) throw();
721 // void operator delete[](void*) throw();
722 //
723 // These implicit declarations introduce only the function names operator
724 // new, operator new[], operator delete, operator delete[].
725 //
726 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
727 // "std" or "bad_alloc" as necessary to form the exception specification.
728 // However, we do not make these implicit declarations visible to name
729 // lookup.
730 if (!StdNamespace) {
731 // The "std" namespace has not yet been defined, so build one implicitly.
732 StdNamespace = NamespaceDecl::Create(Context,
733 Context.getTranslationUnitDecl(),
734 SourceLocation(),
735 &PP.getIdentifierTable().get("std"));
736 StdNamespace->setImplicit(true);
737 }
738
739 if (!StdBadAlloc) {
740 // The "std::bad_alloc" class has not yet been declared, so build it
741 // implicitly.
742 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
743 StdNamespace,
744 SourceLocation(),
745 &PP.getIdentifierTable().get("bad_alloc"),
746 SourceLocation(), 0);
747 StdBadAlloc->setImplicit(true);
748 }
749
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000750 GlobalNewDeleteDeclared = true;
751
752 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
753 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000754 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000755
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000756 DeclareGlobalAllocationFunction(
757 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000758 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000759 DeclareGlobalAllocationFunction(
760 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000761 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000762 DeclareGlobalAllocationFunction(
763 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
764 Context.VoidTy, VoidPtr);
765 DeclareGlobalAllocationFunction(
766 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
767 Context.VoidTy, VoidPtr);
768}
769
770/// DeclareGlobalAllocationFunction - Declares a single implicit global
771/// allocation function if it doesn't already exist.
772void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000773 QualType Return, QualType Argument,
774 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000775 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
776
777 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000778 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000779 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000780 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000781 Alloc != AllocEnd; ++Alloc) {
782 // FIXME: Do we need to check for default arguments here?
783 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
784 if (Func->getNumParams() == 1 &&
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000785 Context.getCanonicalType(
786 Func->getParamDecl(0)->getType().getUnqualifiedType()) == Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000787 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000788 }
789 }
790
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000791 QualType BadAllocType;
792 bool HasBadAllocExceptionSpec
793 = (Name.getCXXOverloadedOperator() == OO_New ||
794 Name.getCXXOverloadedOperator() == OO_Array_New);
795 if (HasBadAllocExceptionSpec) {
796 assert(StdBadAlloc && "Must have std::bad_alloc declared");
797 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
798 }
799
800 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
801 true, false,
802 HasBadAllocExceptionSpec? 1 : 0,
803 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000804 FunctionDecl *Alloc =
805 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000806 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000807 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000808
809 if (AddMallocAttr)
810 Alloc->addAttr(::new (Context) MallocAttr());
811
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000812 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000813 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000814 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000815 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000816
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000817 // FIXME: Also add this declaration to the IdentifierResolver, but
818 // make sure it is at the end of the chain to coincide with the
819 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000820 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000821}
822
Anders Carlsson78f74552009-11-15 18:45:20 +0000823bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
824 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000825 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000826 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000827 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000828 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000829
John McCalla24dc2e2009-11-17 02:14:36 +0000830 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000831 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000832
833 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
834 F != FEnd; ++F) {
835 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
836 if (Delete->isUsualDeallocationFunction()) {
837 Operator = Delete;
838 return false;
839 }
840 }
841
842 // We did find operator delete/operator delete[] declarations, but
843 // none of them were suitable.
844 if (!Found.empty()) {
845 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
846 << Name << RD;
847
848 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
849 F != FEnd; ++F) {
850 Diag((*F)->getLocation(),
851 diag::note_delete_member_function_declared_here)
852 << Name;
853 }
854
855 return true;
856 }
857
858 // Look for a global declaration.
859 DeclareGlobalNewDelete();
860 DeclContext *TUDecl = Context.getTranslationUnitDecl();
861
862 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
863 Expr* DeallocArgs[1];
864 DeallocArgs[0] = &Null;
865 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
866 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
867 Operator))
868 return true;
869
870 assert(Operator && "Did not find a deallocation function!");
871 return false;
872}
873
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000874/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
875/// @code ::delete ptr; @endcode
876/// or
877/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000878Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000879Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000880 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000881 // C++ [expr.delete]p1:
882 // The operand shall have a pointer type, or a class type having a single
883 // conversion function to a pointer type. The result has type void.
884 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000885 // DR599 amends "pointer type" to "pointer to object type" in both cases.
886
Anders Carlssond67c4c32009-08-16 20:29:29 +0000887 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Sebastian Redlf53597f2009-03-15 17:47:39 +0000889 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000890 if (!Ex->isTypeDependent()) {
891 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000892
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000893 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000894 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000895 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000896 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000897
John McCallba135432009-11-21 08:51:07 +0000898 for (UnresolvedSet::iterator I = Conversions->begin(),
899 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000900 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000901 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000902 continue;
903
John McCallba135432009-11-21 08:51:07 +0000904 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000905
906 QualType ConvType = Conv->getConversionType().getNonReferenceType();
907 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
908 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000909 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000910 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000911 if (ObjectPtrConversions.size() == 1) {
912 // We have a single conversion to a pointer-to-object type. Perform
913 // that conversion.
914 Operand.release();
915 if (!PerformImplicitConversion(Ex,
916 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000917 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000918 Operand = Owned(Ex);
919 Type = Ex->getType();
920 }
921 }
922 else if (ObjectPtrConversions.size() > 1) {
923 Diag(StartLoc, diag::err_ambiguous_delete_operand)
924 << Type << Ex->getSourceRange();
925 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
926 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +0000927 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000928 }
929 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000930 }
Sebastian Redl28507842009-02-26 14:39:58 +0000931 }
932
Sebastian Redlf53597f2009-03-15 17:47:39 +0000933 if (!Type->isPointerType())
934 return ExprError(Diag(StartLoc, diag::err_delete_operand)
935 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000936
Ted Kremenek6217b802009-07-29 21:53:49 +0000937 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000938 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000939 return ExprError(Diag(StartLoc, diag::err_delete_operand)
940 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000941 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000942 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000943 PDiag(diag::warn_delete_incomplete)
944 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000945 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000946
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000947 // C++ [expr.delete]p2:
948 // [Note: a pointer to a const type can be the operand of a
949 // delete-expression; it is not necessary to cast away the constness
950 // (5.2.11) of the pointer expression before it is used as the operand
951 // of the delete-expression. ]
952 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
953 CastExpr::CK_NoOp);
954
955 // Update the operand.
956 Operand.take();
957 Operand = ExprArg(*this, Ex);
958
Anders Carlssond67c4c32009-08-16 20:29:29 +0000959 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
960 ArrayForm ? OO_Array_Delete : OO_Delete);
961
Anders Carlsson78f74552009-11-15 18:45:20 +0000962 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
963 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
964
965 if (!UseGlobal &&
966 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000967 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000968
Anders Carlsson78f74552009-11-15 18:45:20 +0000969 if (!RD->hasTrivialDestructor())
970 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000971 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000972 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000973 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000974
Anders Carlssond67c4c32009-08-16 20:29:29 +0000975 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000976 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000977 DeclareGlobalNewDelete();
978 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000979 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000980 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000981 OperatorDelete))
982 return ExprError();
983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Sebastian Redl28507842009-02-26 14:39:58 +0000985 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000986 }
987
Sebastian Redlf53597f2009-03-15 17:47:39 +0000988 Operand.release();
989 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000990 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000991}
992
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000993/// \brief Check the use of the given variable as a C++ condition in an if,
994/// while, do-while, or switch statement.
995Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
996 QualType T = ConditionVar->getType();
997
998 // C++ [stmt.select]p2:
999 // The declarator shall not specify a function or an array.
1000 if (T->isFunctionType())
1001 return ExprError(Diag(ConditionVar->getLocation(),
1002 diag::err_invalid_use_of_function_type)
1003 << ConditionVar->getSourceRange());
1004 else if (T->isArrayType())
1005 return ExprError(Diag(ConditionVar->getLocation(),
1006 diag::err_invalid_use_of_array_type)
1007 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001008
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001009 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1010 ConditionVar->getLocation(),
1011 ConditionVar->getType().getNonReferenceType()));
1012}
1013
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001014/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1015bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1016 // C++ 6.4p4:
1017 // The value of a condition that is an initialized declaration in a statement
1018 // other than a switch statement is the value of the declared variable
1019 // implicitly converted to type bool. If that conversion is ill-formed, the
1020 // program is ill-formed.
1021 // The value of a condition that is an expression is the value of the
1022 // expression, implicitly converted to bool.
1023 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001024 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001025}
Douglas Gregor77a52232008-09-12 00:47:35 +00001026
1027/// Helper function to determine whether this is the (deprecated) C++
1028/// conversion from a string literal to a pointer to non-const char or
1029/// non-const wchar_t (for narrow and wide string literals,
1030/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001031bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001032Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1033 // Look inside the implicit cast, if it exists.
1034 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1035 From = Cast->getSubExpr();
1036
1037 // A string literal (2.13.4) that is not a wide string literal can
1038 // be converted to an rvalue of type "pointer to char"; a wide
1039 // string literal can be converted to an rvalue of type "pointer
1040 // to wchar_t" (C++ 4.2p2).
1041 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001042 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001043 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001044 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001045 // This conversion is considered only when there is an
1046 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001047 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001048 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1049 (!StrLit->isWide() &&
1050 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1051 ToPointeeType->getKind() == BuiltinType::Char_S))))
1052 return true;
1053 }
1054
1055 return false;
1056}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001057
1058/// PerformImplicitConversion - Perform an implicit conversion of the
1059/// expression From to the type ToType. Returns true if there was an
1060/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001061/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001062/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001063/// explicit user-defined conversions are permitted. @p Elidable should be true
1064/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1065/// resolution works differently in that case.
1066bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001067Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001068 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001069 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001070 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001071 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001072 Elidable, ICS);
1073}
1074
1075bool
1076Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001077 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001078 bool Elidable,
1079 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001080 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001081 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001082 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001083 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001084 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001085 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001086 /*ForceRValue=*/true,
1087 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001088 }
John McCall1d318332010-01-12 00:44:57 +00001089 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001090 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001091 /*SuppressUserConversions=*/false,
1092 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001093 /*ForceRValue=*/false,
1094 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001095 }
Douglas Gregor68647482009-12-16 03:45:30 +00001096 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001097}
1098
1099/// PerformImplicitConversion - Perform an implicit conversion of the
1100/// expression From to the type ToType using the pre-computed implicit
1101/// conversion sequence ICS. Returns true if there was an error, false
1102/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001103/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001104/// used in the error message.
1105bool
1106Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1107 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001108 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001109 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001110 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001111 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001112 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001113 return true;
1114 break;
1115
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001116 case ImplicitConversionSequence::UserDefinedConversion: {
1117
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001118 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1119 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001120 QualType BeforeToType;
1121 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001122 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001123
1124 // If the user-defined conversion is specified by a conversion function,
1125 // the initial standard conversion sequence converts the source type to
1126 // the implicit object parameter of the conversion function.
1127 BeforeToType = Context.getTagDeclType(Conv->getParent());
1128 } else if (const CXXConstructorDecl *Ctor =
1129 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001130 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001131 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001132 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001133 // If the user-defined conversion is specified by a constructor, the
1134 // initial standard conversion sequence converts the source type to the
1135 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001136 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1137 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001138 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001139 else
1140 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001141 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001142 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001143 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001144 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001145 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001146 return true;
1147 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001148
Anders Carlsson0aebc812009-09-09 21:33:21 +00001149 OwningExprResult CastArg
1150 = BuildCXXCastArgument(From->getLocStart(),
1151 ToType.getNonReferenceType(),
1152 CastKind, cast<CXXMethodDecl>(FD),
1153 Owned(From));
1154
1155 if (CastArg.isInvalid())
1156 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001157
1158 From = CastArg.takeAs<Expr>();
1159
Eli Friedmand8889622009-11-27 04:41:50 +00001160 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001161 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001162 }
John McCall1d318332010-01-12 00:44:57 +00001163
1164 case ImplicitConversionSequence::AmbiguousConversion:
1165 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1166 PDiag(diag::err_typecheck_ambiguous_condition)
1167 << From->getSourceRange());
1168 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001169
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001170 case ImplicitConversionSequence::EllipsisConversion:
1171 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001172 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001173
1174 case ImplicitConversionSequence::BadConversion:
1175 return true;
1176 }
1177
1178 // Everything went well.
1179 return false;
1180}
1181
1182/// PerformImplicitConversion - Perform an implicit conversion of the
1183/// expression From to the type ToType by following the standard
1184/// conversion sequence SCS. Returns true if there was an error, false
1185/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001186/// expression. Flavor is the context in which we're performing this
1187/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001188bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001189Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001190 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001191 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001192 // Overall FIXME: we are recomputing too many types here and doing far too
1193 // much extra work. What this means is that we need to keep track of more
1194 // information that is computed when we try the implicit conversion initially,
1195 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001196 QualType FromType = From->getType();
1197
Douglas Gregor225c41e2008-11-03 19:09:14 +00001198 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001199 // FIXME: When can ToType be a reference type?
1200 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001201 if (SCS.Second == ICK_Derived_To_Base) {
1202 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1203 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1204 MultiExprArg(*this, (void **)&From, 1),
1205 /*FIXME:ConstructLoc*/SourceLocation(),
1206 ConstructorArgs))
1207 return true;
1208 OwningExprResult FromResult =
1209 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1210 ToType, SCS.CopyConstructor,
1211 move_arg(ConstructorArgs));
1212 if (FromResult.isInvalid())
1213 return true;
1214 From = FromResult.takeAs<Expr>();
1215 return false;
1216 }
Mike Stump1eb44332009-09-09 15:08:12 +00001217 OwningExprResult FromResult =
1218 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1219 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001220 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001222 if (FromResult.isInvalid())
1223 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001225 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001226 return false;
1227 }
1228
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001229 // Perform the first implicit conversion.
1230 switch (SCS.First) {
1231 case ICK_Identity:
1232 case ICK_Lvalue_To_Rvalue:
1233 // Nothing to do.
1234 break;
1235
1236 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001237 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001238 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001239 break;
1240
1241 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001242 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001243 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1244 if (!Fn)
1245 return true;
1246
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001247 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1248 return true;
1249
Anders Carlsson96ad5332009-10-21 17:16:23 +00001250 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001251 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001252
Sebastian Redl759986e2009-10-17 20:50:27 +00001253 // If there's already an address-of operator in the expression, we have
1254 // the right type already, and the code below would just introduce an
1255 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001256 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001257 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001258 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001259 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001260 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001261 break;
1262
1263 default:
1264 assert(false && "Improper first standard conversion");
1265 break;
1266 }
1267
1268 // Perform the second implicit conversion
1269 switch (SCS.Second) {
1270 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001271 // If both sides are functions (or pointers/references to them), there could
1272 // be incompatible exception declarations.
1273 if (CheckExceptionSpecCompatibility(From, ToType))
1274 return true;
1275 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001276 break;
1277
Douglas Gregor43c79c22009-12-09 00:47:37 +00001278 case ICK_NoReturn_Adjustment:
1279 // If both sides are functions (or pointers/references to them), there could
1280 // be incompatible exception declarations.
1281 if (CheckExceptionSpecCompatibility(From, ToType))
1282 return true;
1283
1284 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1285 CastExpr::CK_NoOp);
1286 break;
1287
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001289 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001290 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1291 break;
1292
1293 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001294 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001295 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1296 break;
1297
1298 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001299 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001300 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1301 break;
1302
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001303 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001304 if (ToType->isFloatingType())
1305 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1306 else
1307 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1308 break;
1309
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001310 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001311 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1312 break;
1313
Douglas Gregorf9201e02009-02-11 23:02:49 +00001314 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001315 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001316 break;
1317
Anders Carlsson61faec12009-09-12 04:46:44 +00001318 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001319 if (SCS.IncompatibleObjC) {
1320 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001321 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001322 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001323 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001324 << From->getSourceRange();
1325 }
1326
Anders Carlsson61faec12009-09-12 04:46:44 +00001327
1328 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001329 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001330 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001331 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001332 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001333 }
1334
1335 case ICK_Pointer_Member: {
1336 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001337 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001338 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001339 if (CheckExceptionSpecCompatibility(From, ToType))
1340 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001341 ImpCastExprToType(From, ToType, Kind);
1342 break;
1343 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001344 case ICK_Boolean_Conversion: {
1345 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1346 if (FromType->isMemberPointerType())
1347 Kind = CastExpr::CK_MemberPointerToBoolean;
1348
1349 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001350 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001351 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001352
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001353 case ICK_Derived_To_Base:
1354 if (CheckDerivedToBaseConversion(From->getType(),
1355 ToType.getNonReferenceType(),
1356 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001357 From->getSourceRange(),
1358 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001359 return true;
1360 ImpCastExprToType(From, ToType.getNonReferenceType(),
1361 CastExpr::CK_DerivedToBase);
1362 break;
1363
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001364 default:
1365 assert(false && "Improper second standard conversion");
1366 break;
1367 }
1368
1369 switch (SCS.Third) {
1370 case ICK_Identity:
1371 // Nothing to do.
1372 break;
1373
1374 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001375 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1376 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001377 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001378 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001379 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001380 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001381
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001382 default:
1383 assert(false && "Improper second standard conversion");
1384 break;
1385 }
1386
1387 return false;
1388}
1389
Sebastian Redl64b45f72009-01-05 20:52:13 +00001390Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1391 SourceLocation KWLoc,
1392 SourceLocation LParen,
1393 TypeTy *Ty,
1394 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001395 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001397 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1398 // all traits except __is_class, __is_enum and __is_union require a the type
1399 // to be complete.
1400 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001401 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001402 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001403 return ExprError();
1404 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001405
1406 // There is no point in eagerly computing the value. The traits are designed
1407 // to be used from type trait templates, so Ty will be a template parameter
1408 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001409 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1410 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001411}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001412
1413QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001414 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001415 const char *OpSpelling = isIndirect ? "->*" : ".*";
1416 // C++ 5.5p2
1417 // The binary operator .* [p3: ->*] binds its second operand, which shall
1418 // be of type "pointer to member of T" (where T is a completely-defined
1419 // class type) [...]
1420 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001421 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001422 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001423 Diag(Loc, diag::err_bad_memptr_rhs)
1424 << OpSpelling << RType << rex->getSourceRange();
1425 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001426 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001427
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001428 QualType Class(MemPtr->getClass(), 0);
1429
1430 // C++ 5.5p2
1431 // [...] to its first operand, which shall be of class T or of a class of
1432 // which T is an unambiguous and accessible base class. [p3: a pointer to
1433 // such a class]
1434 QualType LType = lex->getType();
1435 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001436 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001437 LType = Ptr->getPointeeType().getNonReferenceType();
1438 else {
1439 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001440 << OpSpelling << 1 << LType
1441 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001442 return QualType();
1443 }
1444 }
1445
Douglas Gregora4923eb2009-11-16 21:35:15 +00001446 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001447 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1448 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001449 // FIXME: Would it be useful to print full ambiguity paths, or is that
1450 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001451 if (!IsDerivedFrom(LType, Class, Paths) ||
1452 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001453 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001454 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001455 << (int)isIndirect << lex->getType() <<
1456 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001457 return QualType();
1458 }
1459 }
1460
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001461 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001462 // Diagnose use of pointer-to-member type which when used as
1463 // the functional cast in a pointer-to-member expression.
1464 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1465 return QualType();
1466 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001467 // C++ 5.5p2
1468 // The result is an object or a function of the type specified by the
1469 // second operand.
1470 // The cv qualifiers are the union of those in the pointer and the left side,
1471 // in accordance with 5.5p5 and 5.2.5.
1472 // FIXME: This returns a dereferenced member function pointer as a normal
1473 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001474 // calling them. There's also a GCC extension to get a function pointer to the
1475 // thing, which is another complication, because this type - unlike the type
1476 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001477 // argument.
1478 // We probably need a "MemberFunctionClosureType" or something like that.
1479 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001480 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001481 return Result;
1482}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001483
1484/// \brief Get the target type of a standard or user-defined conversion.
1485static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001486 switch (ICS.getKind()) {
1487 case ImplicitConversionSequence::StandardConversion:
1488 return ICS.Standard.getToType();
1489 case ImplicitConversionSequence::UserDefinedConversion:
1490 return ICS.UserDefined.After.getToType();
1491 case ImplicitConversionSequence::AmbiguousConversion:
1492 return ICS.Ambiguous.getToType();
1493 case ImplicitConversionSequence::EllipsisConversion:
1494 case ImplicitConversionSequence::BadConversion:
1495 llvm_unreachable("function not valid for ellipsis or bad conversions");
1496 }
1497 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001498}
1499
1500/// \brief Try to convert a type to another according to C++0x 5.16p3.
1501///
1502/// This is part of the parameter validation for the ? operator. If either
1503/// value operand is a class type, the two operands are attempted to be
1504/// converted to each other. This function does the conversion in one direction.
1505/// It emits a diagnostic and returns true only if it finds an ambiguous
1506/// conversion.
1507static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1508 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001509 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001510 // C++0x 5.16p3
1511 // The process for determining whether an operand expression E1 of type T1
1512 // can be converted to match an operand expression E2 of type T2 is defined
1513 // as follows:
1514 // -- If E2 is an lvalue:
1515 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1516 // E1 can be converted to match E2 if E1 can be implicitly converted to
1517 // type "lvalue reference to T2", subject to the constraint that in the
1518 // conversion the reference must bind directly to E1.
1519 if (!Self.CheckReferenceInit(From,
1520 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001521 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001522 /*SuppressUserConversions=*/false,
1523 /*AllowExplicit=*/false,
1524 /*ForceRValue=*/false,
1525 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001526 {
John McCall1d318332010-01-12 00:44:57 +00001527 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001528 "expected a definite conversion");
1529 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001530 ICS.isStandard() ? ICS.Standard.DirectBinding
1531 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001532 if (DirectBinding)
1533 return false;
1534 }
1535 }
John McCall1d318332010-01-12 00:44:57 +00001536 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001537 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1538 // -- if E1 and E2 have class type, and the underlying class types are
1539 // the same or one is a base class of the other:
1540 QualType FTy = From->getType();
1541 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001542 const RecordType *FRec = FTy->getAs<RecordType>();
1543 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001544 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1545 if (FRec && TRec && (FRec == TRec ||
1546 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1547 // E1 can be converted to match E2 if the class of T2 is the
1548 // same type as, or a base class of, the class of T1, and
1549 // [cv2 > cv1].
1550 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1551 // Could still fail if there's no copy constructor.
1552 // FIXME: Is this a hard error then, or just a conversion failure? The
1553 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001554 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001555 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001556 /*ForceRValue=*/false,
1557 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001558 }
1559 } else {
1560 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1561 // implicitly converted to the type that expression E2 would have
1562 // if E2 were converted to an rvalue.
1563 // First find the decayed type.
1564 if (TTy->isFunctionType())
1565 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001566 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001567 TTy = Self.Context.getArrayDecayedType(TTy);
1568
1569 // Now try the implicit conversion.
1570 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001571 ICS = Self.TryImplicitConversion(From, TTy,
1572 /*SuppressUserConversions=*/false,
1573 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001574 /*ForceRValue=*/false,
1575 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001576 }
1577 return false;
1578}
1579
1580/// \brief Try to find a common type for two according to C++0x 5.16p5.
1581///
1582/// This is part of the parameter validation for the ? operator. If either
1583/// value operand is a class type, overload resolution is used to find a
1584/// conversion to a common type.
1585static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1586 SourceLocation Loc) {
1587 Expr *Args[2] = { LHS, RHS };
1588 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001589 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001590
1591 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001592 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001593 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001594 // We found a match. Perform the conversions on the arguments and move on.
1595 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001596 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001597 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001598 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001599 break;
1600 return false;
1601
Douglas Gregor20093b42009-12-09 23:02:17 +00001602 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001603 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1604 << LHS->getType() << RHS->getType()
1605 << LHS->getSourceRange() << RHS->getSourceRange();
1606 return true;
1607
Douglas Gregor20093b42009-12-09 23:02:17 +00001608 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001609 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1610 << LHS->getType() << RHS->getType()
1611 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001612 // FIXME: Print the possible common types by printing the return types of
1613 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001614 break;
1615
Douglas Gregor20093b42009-12-09 23:02:17 +00001616 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001617 assert(false && "Conditional operator has only built-in overloads");
1618 break;
1619 }
1620 return true;
1621}
1622
Sebastian Redl76458502009-04-17 16:30:52 +00001623/// \brief Perform an "extended" implicit conversion as returned by
1624/// TryClassUnification.
1625///
1626/// TryClassUnification generates ICSs that include reference bindings.
1627/// PerformImplicitConversion is not suitable for this; it chokes if the
1628/// second part of a standard conversion is ICK_DerivedToBase. This function
1629/// handles the reference binding specially.
1630static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001631 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001632 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001633 assert(ICS.Standard.DirectBinding &&
1634 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001635 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1636 // redoing all the work.
1637 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001638 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001639 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001640 /*SuppressUserConversions=*/false,
1641 /*AllowExplicit=*/false,
1642 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001643 }
John McCall1d318332010-01-12 00:44:57 +00001644 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001645 assert(ICS.UserDefined.After.DirectBinding &&
1646 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001647 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001648 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001649 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001650 /*SuppressUserConversions=*/false,
1651 /*AllowExplicit=*/false,
1652 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001653 }
Douglas Gregor68647482009-12-16 03:45:30 +00001654 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001655 return true;
1656 return false;
1657}
1658
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001659/// \brief Check the operands of ?: under C++ semantics.
1660///
1661/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1662/// extension. In this case, LHS == Cond. (But they're not aliases.)
1663QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1664 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001665 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1666 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001667
1668 // C++0x 5.16p1
1669 // The first expression is contextually converted to bool.
1670 if (!Cond->isTypeDependent()) {
1671 if (CheckCXXBooleanCondition(Cond))
1672 return QualType();
1673 }
1674
1675 // Either of the arguments dependent?
1676 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1677 return Context.DependentTy;
1678
John McCallb13c87f2009-11-05 09:23:39 +00001679 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1680
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001681 // C++0x 5.16p2
1682 // If either the second or the third operand has type (cv) void, ...
1683 QualType LTy = LHS->getType();
1684 QualType RTy = RHS->getType();
1685 bool LVoid = LTy->isVoidType();
1686 bool RVoid = RTy->isVoidType();
1687 if (LVoid || RVoid) {
1688 // ... then the [l2r] conversions are performed on the second and third
1689 // operands ...
1690 DefaultFunctionArrayConversion(LHS);
1691 DefaultFunctionArrayConversion(RHS);
1692 LTy = LHS->getType();
1693 RTy = RHS->getType();
1694
1695 // ... and one of the following shall hold:
1696 // -- The second or the third operand (but not both) is a throw-
1697 // expression; the result is of the type of the other and is an rvalue.
1698 bool LThrow = isa<CXXThrowExpr>(LHS);
1699 bool RThrow = isa<CXXThrowExpr>(RHS);
1700 if (LThrow && !RThrow)
1701 return RTy;
1702 if (RThrow && !LThrow)
1703 return LTy;
1704
1705 // -- Both the second and third operands have type void; the result is of
1706 // type void and is an rvalue.
1707 if (LVoid && RVoid)
1708 return Context.VoidTy;
1709
1710 // Neither holds, error.
1711 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1712 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1713 << LHS->getSourceRange() << RHS->getSourceRange();
1714 return QualType();
1715 }
1716
1717 // Neither is void.
1718
1719 // C++0x 5.16p3
1720 // Otherwise, if the second and third operand have different types, and
1721 // either has (cv) class type, and attempt is made to convert each of those
1722 // operands to the other.
1723 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1724 (LTy->isRecordType() || RTy->isRecordType())) {
1725 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1726 // These return true if a single direction is already ambiguous.
1727 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1728 return QualType();
1729 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1730 return QualType();
1731
John McCall1d318332010-01-12 00:44:57 +00001732 bool HaveL2R = !ICSLeftToRight.isBad();
1733 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001734 // If both can be converted, [...] the program is ill-formed.
1735 if (HaveL2R && HaveR2L) {
1736 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1737 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1738 return QualType();
1739 }
1740
1741 // If exactly one conversion is possible, that conversion is applied to
1742 // the chosen operand and the converted operands are used in place of the
1743 // original operands for the remainder of this section.
1744 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001745 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001746 return QualType();
1747 LTy = LHS->getType();
1748 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001749 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001750 return QualType();
1751 RTy = RHS->getType();
1752 }
1753 }
1754
1755 // C++0x 5.16p4
1756 // If the second and third operands are lvalues and have the same type,
1757 // the result is of that type [...]
1758 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1759 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1760 RHS->isLvalue(Context) == Expr::LV_Valid)
1761 return LTy;
1762
1763 // C++0x 5.16p5
1764 // Otherwise, the result is an rvalue. If the second and third operands
1765 // do not have the same type, and either has (cv) class type, ...
1766 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1767 // ... overload resolution is used to determine the conversions (if any)
1768 // to be applied to the operands. If the overload resolution fails, the
1769 // program is ill-formed.
1770 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1771 return QualType();
1772 }
1773
1774 // C++0x 5.16p6
1775 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1776 // conversions are performed on the second and third operands.
1777 DefaultFunctionArrayConversion(LHS);
1778 DefaultFunctionArrayConversion(RHS);
1779 LTy = LHS->getType();
1780 RTy = RHS->getType();
1781
1782 // After those conversions, one of the following shall hold:
1783 // -- The second and third operands have the same type; the result
1784 // is of that type.
1785 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1786 return LTy;
1787
1788 // -- The second and third operands have arithmetic or enumeration type;
1789 // the usual arithmetic conversions are performed to bring them to a
1790 // common type, and the result is of that type.
1791 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1792 UsualArithmeticConversions(LHS, RHS);
1793 return LHS->getType();
1794 }
1795
1796 // -- The second and third operands have pointer type, or one has pointer
1797 // type and the other is a null pointer constant; pointer conversions
1798 // and qualification conversions are performed to bring them to their
1799 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00001800 // -- The second and third operands have pointer to member type, or one has
1801 // pointer to member type and the other is a null pointer constant;
1802 // pointer to member conversions and qualification conversions are
1803 // performed to bring them to a common type, whose cv-qualification
1804 // shall match the cv-qualification of either the second or the third
1805 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001806 QualType Composite = FindCompositePointerType(LHS, RHS);
1807 if (!Composite.isNull())
1808 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001809
1810 // Similarly, attempt to find composite type of twp objective-c pointers.
1811 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1812 if (!Composite.isNull())
1813 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001814
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001815 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1816 << LHS->getType() << RHS->getType()
1817 << LHS->getSourceRange() << RHS->getSourceRange();
1818 return QualType();
1819}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001820
1821/// \brief Find a merged pointer type and convert the two expressions to it.
1822///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001823/// This finds the composite pointer type (or member pointer type) for @p E1
1824/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1825/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001826/// It does not emit diagnostics.
1827QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1828 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1829 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001831 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1832 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001833 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001834
1835 // C++0x 5.9p2
1836 // Pointer conversions and qualification conversions are performed on
1837 // pointer operands to bring them to their composite pointer type. If
1838 // one operand is a null pointer constant, the composite pointer type is
1839 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001840 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001841 if (T2->isMemberPointerType())
1842 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1843 else
1844 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001845 return T2;
1846 }
Douglas Gregorce940492009-09-25 04:25:58 +00001847 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001848 if (T1->isMemberPointerType())
1849 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1850 else
1851 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001852 return T1;
1853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Douglas Gregor20b3e992009-08-24 17:42:35 +00001855 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001856 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1857 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001858 return QualType();
1859
1860 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1861 // the other has type "pointer to cv2 T" and the composite pointer type is
1862 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1863 // Otherwise, the composite pointer type is a pointer type similar to the
1864 // type of one of the operands, with a cv-qualification signature that is
1865 // the union of the cv-qualification signatures of the operand types.
1866 // In practice, the first part here is redundant; it's subsumed by the second.
1867 // What we do here is, we build the two possible composite types, and try the
1868 // conversions in both directions. If only one works, or if the two composite
1869 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001870 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001871 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1872 QualifierVector QualifierUnion;
1873 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1874 ContainingClassVector;
1875 ContainingClassVector MemberOfClass;
1876 QualType Composite1 = Context.getCanonicalType(T1),
1877 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001878 do {
1879 const PointerType *Ptr1, *Ptr2;
1880 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1881 (Ptr2 = Composite2->getAs<PointerType>())) {
1882 Composite1 = Ptr1->getPointeeType();
1883 Composite2 = Ptr2->getPointeeType();
1884 QualifierUnion.push_back(
1885 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1886 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1887 continue;
1888 }
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Douglas Gregor20b3e992009-08-24 17:42:35 +00001890 const MemberPointerType *MemPtr1, *MemPtr2;
1891 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1892 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1893 Composite1 = MemPtr1->getPointeeType();
1894 Composite2 = MemPtr2->getPointeeType();
1895 QualifierUnion.push_back(
1896 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1897 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1898 MemPtr2->getClass()));
1899 continue;
1900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregor20b3e992009-08-24 17:42:35 +00001902 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Douglas Gregor20b3e992009-08-24 17:42:35 +00001904 // Cannot unwrap any more types.
1905 break;
1906 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Douglas Gregor20b3e992009-08-24 17:42:35 +00001908 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001909 ContainingClassVector::reverse_iterator MOC
1910 = MemberOfClass.rbegin();
1911 for (QualifierVector::reverse_iterator
1912 I = QualifierUnion.rbegin(),
1913 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001914 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001915 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001916 if (MOC->first && MOC->second) {
1917 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001918 Composite1 = Context.getMemberPointerType(
1919 Context.getQualifiedType(Composite1, Quals),
1920 MOC->first);
1921 Composite2 = Context.getMemberPointerType(
1922 Context.getQualifiedType(Composite2, Quals),
1923 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001924 } else {
1925 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001926 Composite1
1927 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1928 Composite2
1929 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001930 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001931 }
1932
Mike Stump1eb44332009-09-09 15:08:12 +00001933 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001934 TryImplicitConversion(E1, Composite1,
1935 /*SuppressUserConversions=*/false,
1936 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001937 /*ForceRValue=*/false,
1938 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001939 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001940 TryImplicitConversion(E2, Composite1,
1941 /*SuppressUserConversions=*/false,
1942 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001943 /*ForceRValue=*/false,
1944 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001946 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00001947 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001948 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001949 if (Context.getCanonicalType(Composite1) !=
1950 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001951 E1ToC2 = TryImplicitConversion(E1, Composite2,
1952 /*SuppressUserConversions=*/false,
1953 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001954 /*ForceRValue=*/false,
1955 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001956 E2ToC2 = TryImplicitConversion(E2, Composite2,
1957 /*SuppressUserConversions=*/false,
1958 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001959 /*ForceRValue=*/false,
1960 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001961 }
1962
John McCall1d318332010-01-12 00:44:57 +00001963 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
1964 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001965 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001966 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1967 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001968 return Composite1;
1969 }
1970 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001971 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1972 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001973 return Composite2;
1974 }
1975 return QualType();
1976}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001977
Anders Carlssondef11992009-05-30 20:36:53 +00001978Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001979 if (!Context.getLangOptions().CPlusPlus)
1980 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregor51326552009-12-24 18:51:59 +00001982 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1983
Ted Kremenek6217b802009-07-29 21:53:49 +00001984 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001985 if (!RT)
1986 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Anders Carlssondef11992009-05-30 20:36:53 +00001988 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1989 if (RD->hasTrivialDestructor())
1990 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Anders Carlsson283e4d52009-09-14 01:30:44 +00001992 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1993 QualType Ty = CE->getCallee()->getType();
1994 if (const PointerType *PT = Ty->getAs<PointerType>())
1995 Ty = PT->getPointeeType();
1996
John McCall183700f2009-09-21 23:43:11 +00001997 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001998 if (FTy->getResultType()->isReferenceType())
1999 return Owned(E);
2000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002002 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002003 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002004 if (CXXDestructorDecl *Destructor =
2005 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2006 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002007 // FIXME: Add the temporary to the temporaries vector.
2008 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2009}
2010
Anders Carlsson0ece4912009-12-15 20:51:39 +00002011Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002012 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002014 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2015 assert(ExprTemporaries.size() >= FirstTemporary);
2016 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002017 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002019 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002020 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002021 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002022 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2023 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002025 return E;
2026}
2027
Douglas Gregor90f93822009-12-22 22:17:25 +00002028Sema::OwningExprResult
2029Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2030 if (SubExpr.isInvalid())
2031 return ExprError();
2032
2033 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2034}
2035
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002036FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2037 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2038 assert(ExprTemporaries.size() >= FirstTemporary);
2039
2040 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2041 CXXTemporary **Temporaries =
2042 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2043
2044 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2045
2046 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2047 ExprTemporaries.end());
2048
2049 return E;
2050}
2051
Mike Stump1eb44332009-09-09 15:08:12 +00002052Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002053Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2054 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2055 // Since this might be a postfix expression, get rid of ParenListExprs.
2056 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002058 Expr *BaseExpr = (Expr*)Base.get();
2059 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002061 QualType BaseType = BaseExpr->getType();
2062 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002063 // If we have a pointer to a dependent type and are using the -> operator,
2064 // the object type is the type that the pointer points to. We might still
2065 // have enough information about that type to do something useful.
2066 if (OpKind == tok::arrow)
2067 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2068 BaseType = Ptr->getPointeeType();
2069
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002070 ObjectType = BaseType.getAsOpaquePtr();
2071 return move(Base);
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002074 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002075 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002076 // returned, with the original second operand.
2077 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002078 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002079 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002080 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002081 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002082
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002083 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002084 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002085 BaseExpr = (Expr*)Base.get();
2086 if (BaseExpr == NULL)
2087 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002088 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002089 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002090 BaseType = BaseExpr->getType();
2091 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002092 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002093 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002094 for (unsigned i = 0; i < Locations.size(); i++)
2095 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002096 return ExprError();
2097 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002098 }
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Douglas Gregor31658df2009-11-20 19:58:21 +00002100 if (BaseType->isPointerType())
2101 BaseType = BaseType->getPointeeType();
2102 }
Mike Stump1eb44332009-09-09 15:08:12 +00002103
2104 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002105 // vector types or Objective-C interfaces. Just return early and let
2106 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002107 if (!BaseType->isRecordType()) {
2108 // C++ [basic.lookup.classref]p2:
2109 // [...] If the type of the object expression is of pointer to scalar
2110 // type, the unqualified-id is looked up in the context of the complete
2111 // postfix-expression.
2112 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002113 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002114 }
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Douglas Gregor03c57052009-11-17 05:17:33 +00002116 // The object type must be complete (or dependent).
2117 if (!BaseType->isDependentType() &&
2118 RequireCompleteType(OpLoc, BaseType,
2119 PDiag(diag::err_incomplete_member_access)))
2120 return ExprError();
2121
Douglas Gregorc68afe22009-09-03 21:38:09 +00002122 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002123 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002124 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002125 // type C (or of pointer to a class type C), the unqualified-id is looked
2126 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002127 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002128
Mike Stump1eb44332009-09-09 15:08:12 +00002129 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002130}
2131
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002132CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2133 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002134 if (PerformObjectArgumentInitialization(Exp, Method))
2135 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2136
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002137 MemberExpr *ME =
2138 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2139 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002140 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002141 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2142 CXXMemberCallExpr *CE =
2143 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2144 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002145 return CE;
2146}
2147
Anders Carlsson0aebc812009-09-09 21:33:21 +00002148Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2149 QualType Ty,
2150 CastExpr::CastKind Kind,
2151 CXXMethodDecl *Method,
2152 ExprArg Arg) {
2153 Expr *From = Arg.takeAs<Expr>();
2154
2155 switch (Kind) {
2156 default: assert(0 && "Unhandled cast kind!");
2157 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002158 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2159
2160 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2161 MultiExprArg(*this, (void **)&From, 1),
2162 CastLoc, ConstructorArgs))
2163 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002164
2165 OwningExprResult Result =
2166 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2167 move_arg(ConstructorArgs));
2168 if (Result.isInvalid())
2169 return ExprError();
2170
2171 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002172 }
2173
2174 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002175 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002176
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002177 // Create an implicit call expr that calls it.
2178 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002179 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002180 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002181 }
2182}
2183
Anders Carlsson165a0a02009-05-17 18:41:29 +00002184Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2185 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002186 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002187 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002188
Anders Carlsson165a0a02009-05-17 18:41:29 +00002189 return Owned(FullExpr);
2190}