blob: 130b6e857b7e165fc82e56b08d5a3d06a754cadd [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,
182 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000183
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000185}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000186
187/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
188/// Can be interpreted either as function-style casting ("int(x)")
189/// or class type construction ("ClassType(x,y,z)")
190/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000192Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
193 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000194 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000195 SourceLocation *CommaLocs,
196 SourceLocation RParenLoc) {
197 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000198 // FIXME: Preserve type source info.
199 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000200 unsigned NumExprs = exprs.size();
201 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000202 SourceLocation TyBeginLoc = TypeRange.getBegin();
203 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
204
Sebastian Redlf53597f2009-03-15 17:47:39 +0000205 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000206 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000207 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000208
209 return Owned(CXXUnresolvedConstructExpr::Create(Context,
210 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000211 LParenLoc,
212 Exprs, NumExprs,
213 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000214 }
215
Anders Carlssonbb60a502009-08-27 03:53:50 +0000216 if (Ty->isArrayType())
217 return ExprError(Diag(TyBeginLoc,
218 diag::err_value_init_for_array_type) << FullRange);
219 if (!Ty->isVoidType() &&
220 RequireCompleteType(TyBeginLoc, Ty,
221 PDiag(diag::err_invalid_incomplete_type_use)
222 << FullRange))
223 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000224
Anders Carlssonbb60a502009-08-27 03:53:50 +0000225 if (RequireNonAbstractType(TyBeginLoc, Ty,
226 diag::err_allocation_of_abstract_type))
227 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000228
229
Douglas Gregor506ae412009-01-16 18:33:17 +0000230 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000231 // If the expression list is a single expression, the type conversion
232 // expression is equivalent (in definedness, and if defined in meaning) to the
233 // corresponding cast expression.
234 //
235 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000236 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000237 CXXMethodDecl *Method = 0;
238 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
239 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000240 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000241
242 exprs.release();
243 if (Method) {
244 OwningExprResult CastArg
245 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
246 Kind, Method, Owned(Exprs[0]));
247 if (CastArg.isInvalid())
248 return ExprError();
249
250 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000251 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000252
253 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
254 Ty, TyBeginLoc, Kind,
255 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000256 }
257
Ted Kremenek6217b802009-07-29 21:53:49 +0000258 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000259 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000260
Mike Stump1eb44332009-09-09 15:08:12 +0000261 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000262 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000263 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
264
Douglas Gregor506ae412009-01-16 18:33:17 +0000265 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000266 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000267 TypeRange.getBegin(),
268 SourceRange(TypeRange.getBegin(),
269 RParenLoc),
270 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000271 InitializationKind::CreateDirect(TypeRange.getBegin(),
272 LParenLoc,
273 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000274 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000275
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 if (!Constructor)
277 return ExprError();
278
Mike Stump1eb44332009-09-09 15:08:12 +0000279 OwningExprResult Result =
280 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000281 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000282 if (Result.isInvalid())
283 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Anders Carlssone7624a72009-08-27 05:08:22 +0000285 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000286 }
287
288 // Fall through to value-initialize an object of class type that
289 // doesn't have a user-declared default constructor.
290 }
291
292 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000293 // If the expression list specifies more than a single value, the type shall
294 // be a class with a suitably declared constructor.
295 //
296 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297 return ExprError(Diag(CommaLocs[0],
298 diag::err_builtin_func_cast_more_than_one_arg)
299 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000300
301 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000302 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000303 // The expression T(), where T is a simple-type-specifier for a non-array
304 // complete object type or the (possibly cv-qualified) void type, creates an
305 // rvalue of the specified type, which is value-initialized.
306 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000307 exprs.release();
308 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000309}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000310
311
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000312/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
313/// @code new (memory) int[size][4] @endcode
314/// or
315/// @code ::new Foo(23, "hello") @endcode
316/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000317Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000318Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000319 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000320 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000321 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000322 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000323 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000324 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 // If the specified type is an array, unwrap it and save the expression.
326 if (D.getNumTypeObjects() > 0 &&
327 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
328 DeclaratorChunk &Chunk = D.getTypeObject(0);
329 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000330 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
331 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000332 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000333 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
334 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000335
336 if (ParenTypeId) {
337 // Can't have dynamic array size when the type-id is in parentheses.
338 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
339 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
340 !NumElts->isIntegerConstantExpr(Context)) {
341 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
342 << NumElts->getSourceRange();
343 return ExprError();
344 }
345 }
346
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000347 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000348 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000349 }
350
Douglas Gregor043cad22009-09-11 00:18:58 +0000351 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000352 if (ArraySize) {
353 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000354 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
355 break;
356
357 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
358 if (Expr *NumElts = (Expr *)Array.NumElts) {
359 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
360 !NumElts->isIntegerConstantExpr(Context)) {
361 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
362 << NumElts->getSourceRange();
363 return ExprError();
364 }
365 }
366 }
367 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000368
John McCalla93c9342009-12-07 02:54:59 +0000369 //FIXME: Store TypeSourceInfo in CXXNew expression.
370 TypeSourceInfo *TInfo = 0;
371 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000372 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000373 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000374
Mike Stump1eb44332009-09-09 15:08:12 +0000375 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000376 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000377 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000378 PlacementRParen,
379 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000380 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000381 D.getSourceRange().getBegin(),
382 D.getSourceRange(),
383 Owned(ArraySize),
384 ConstructorLParen,
385 move(ConstructorArgs),
386 ConstructorRParen);
387}
388
Mike Stump1eb44332009-09-09 15:08:12 +0000389Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000390Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
391 SourceLocation PlacementLParen,
392 MultiExprArg PlacementArgs,
393 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000394 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000395 QualType AllocType,
396 SourceLocation TypeLoc,
397 SourceRange TypeRange,
398 ExprArg ArraySizeE,
399 SourceLocation ConstructorLParen,
400 MultiExprArg ConstructorArgs,
401 SourceLocation ConstructorRParen) {
402 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000403 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000404
Douglas Gregor3433cf72009-05-21 00:00:09 +0000405 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000406
407 // That every array dimension except the first is constant was already
408 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000409
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000410 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
411 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000412 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000413 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000414 QualType SizeType = ArraySize->getType();
415 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000416 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
417 diag::err_array_size_not_integral)
418 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000419 // Let's see if this is a constant < 0. If so, we reject it out of hand.
420 // We don't care about special rules, so we tell the machinery it's not
421 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000422 if (!ArraySize->isValueDependent()) {
423 llvm::APSInt Value;
424 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
425 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000426 llvm::APInt::getNullValue(Value.getBitWidth()),
427 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000428 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
429 diag::err_typecheck_negative_array_size)
430 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000431 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000432 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000433
Eli Friedman73c39ab2009-10-20 08:27:19 +0000434 ImpCastExprToType(ArraySize, Context.getSizeType(),
435 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000436 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000437
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000438 FunctionDecl *OperatorNew = 0;
439 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000440 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
441 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000442
Sebastian Redl28507842009-02-26 14:39:58 +0000443 if (!AllocType->isDependentType() &&
444 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
445 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000446 SourceRange(PlacementLParen, PlacementRParen),
447 UseGlobal, AllocType, ArraySize, PlaceArgs,
448 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000449 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000450 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000451 if (OperatorNew) {
452 // Add default arguments, if any.
453 const FunctionProtoType *Proto =
454 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000455 VariadicCallType CallType =
456 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000457 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
458 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000459 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000460 if (Invalid)
461 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000462
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000463 NumPlaceArgs = AllPlaceArgs.size();
464 if (NumPlaceArgs > 0)
465 PlaceArgs = &AllPlaceArgs[0];
466 }
467
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000468 bool Init = ConstructorLParen.isValid();
469 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000470 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
472 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000473 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
474
Douglas Gregor99a2e602009-12-16 01:38:02 +0000475 if (!AllocType->isDependentType() &&
476 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
477 // C++0x [expr.new]p15:
478 // A new-expression that creates an object of type T initializes that
479 // object as follows:
480 InitializationKind Kind
481 // - If the new-initializer is omitted, the object is default-
482 // initialized (8.5); if no initialization is performed,
483 // the object has indeterminate value
484 = !Init? InitializationKind::CreateDefault(TypeLoc)
485 // - Otherwise, the new-initializer is interpreted according to the
486 // initialization rules of 8.5 for direct-initialization.
487 : InitializationKind::CreateDirect(TypeLoc,
488 ConstructorLParen,
489 ConstructorRParen);
490
Douglas Gregor99a2e602009-12-16 01:38:02 +0000491 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000492 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000493 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000494 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
495 move(ConstructorArgs));
496 if (FullInit.isInvalid())
497 return ExprError();
498
499 // FullInit is our initializer; walk through it to determine if it's a
500 // constructor call, which CXXNewExpr handles directly.
501 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
502 if (CXXBindTemporaryExpr *Binder
503 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
504 FullInitExpr = Binder->getSubExpr();
505 if (CXXConstructExpr *Construct
506 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
507 Constructor = Construct->getConstructor();
508 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
509 AEnd = Construct->arg_end();
510 A != AEnd; ++A)
511 ConvertedConstructorArgs.push_back(A->Retain());
512 } else {
513 // Take the converted initializer.
514 ConvertedConstructorArgs.push_back(FullInit.release());
515 }
516 } else {
517 // No initialization required.
518 }
519
520 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000521 NumConsArgs = ConvertedConstructorArgs.size();
522 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000523 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000524
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000525 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000526
Sebastian Redlf53597f2009-03-15 17:47:39 +0000527 PlacementArgs.release();
528 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000529 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000530 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000531 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000532 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000533 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000534}
535
536/// CheckAllocatedType - Checks that a type is suitable as the allocated type
537/// in a new-expression.
538/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000539bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000540 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000541 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
542 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000543 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000544 return Diag(Loc, diag::err_bad_new_type)
545 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000546 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000547 return Diag(Loc, diag::err_bad_new_type)
548 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000549 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000550 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000551 PDiag(diag::err_new_incomplete_type)
552 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000553 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000554 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000555 diag::err_allocation_of_abstract_type))
556 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000557
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000558 return false;
559}
560
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000561/// FindAllocationFunctions - Finds the overloads of operator new and delete
562/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000563bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
564 bool UseGlobal, QualType AllocType,
565 bool IsArray, Expr **PlaceArgs,
566 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000567 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000568 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000569 // --- Choosing an allocation function ---
570 // C++ 5.3.4p8 - 14 & 18
571 // 1) If UseGlobal is true, only look in the global scope. Else, also look
572 // in the scope of the allocated class.
573 // 2) If an array size is given, look for operator new[], else look for
574 // operator new.
575 // 3) The first argument is always size_t. Append the arguments from the
576 // placement form.
577 // FIXME: Also find the appropriate delete operator.
578
579 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
580 // We don't care about the actual value of this argument.
581 // FIXME: Should the Sema create the expression and embed it in the syntax
582 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000583 IntegerLiteral Size(llvm::APInt::getNullValue(
584 Context.Target.getPointerWidth(0)),
585 Context.getSizeType(),
586 SourceLocation());
587 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000588 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
589
590 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
591 IsArray ? OO_Array_New : OO_New);
592 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000593 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000594 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000595 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000596 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 AllocArgs.size(), Record, /*AllowMissing=*/true,
598 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000599 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000600 }
601 if (!OperatorNew) {
602 // Didn't find a member overload. Look for a global one.
603 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000604 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000605 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000606 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
607 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000608 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000609 }
610
Anders Carlssond9583892009-05-31 20:26:12 +0000611 // FindAllocationOverload can change the passed in arguments, so we need to
612 // copy them back.
613 if (NumPlaceArgs > 0)
614 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000616 return false;
617}
618
Sebastian Redl7f662392008-12-04 22:20:51 +0000619/// FindAllocationOverload - Find an fitting overload for the allocation
620/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000621bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
622 DeclarationName Name, Expr** Args,
623 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000624 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000625 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
626 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000627 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000628 if (AllowMissing)
629 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000630 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000631 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000632 }
633
John McCallf36e02d2009-10-09 21:13:30 +0000634 // FIXME: handle ambiguity
635
Sebastian Redl7f662392008-12-04 22:20:51 +0000636 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000637 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
638 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000639 // Even member operator new/delete are implicitly treated as
640 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000641 if (FunctionDecl *Fn =
642 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000643 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
644 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000645 continue;
646 }
647
648 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000649 }
650
651 // Do the resolution.
652 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000653 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000654 case OR_Success: {
655 // Got one!
656 FunctionDecl *FnDecl = Best->Function;
657 // The first argument is size_t, and the first parameter must be size_t,
658 // too. This is checked on declaration and can be assumed. (It can't be
659 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000660 // Whatch out for variadic allocator function.
661 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
662 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000663 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000664 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000665 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000666 return true;
667 }
668 Operator = FnDecl;
669 return false;
670 }
671
672 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000673 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000674 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000675 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
676 return true;
677
678 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000679 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000680 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000681 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
682 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000683
684 case OR_Deleted:
685 Diag(StartLoc, diag::err_ovl_deleted_call)
686 << Best->Function->isDeleted()
687 << Name << Range;
688 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
689 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000690 }
691 assert(false && "Unreachable, bad result from BestViableFunction");
692 return true;
693}
694
695
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000696/// DeclareGlobalNewDelete - Declare the global forms of operator new and
697/// delete. These are:
698/// @code
699/// void* operator new(std::size_t) throw(std::bad_alloc);
700/// void* operator new[](std::size_t) throw(std::bad_alloc);
701/// void operator delete(void *) throw();
702/// void operator delete[](void *) throw();
703/// @endcode
704/// Note that the placement and nothrow forms of new are *not* implicitly
705/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000706void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000707 if (GlobalNewDeleteDeclared)
708 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000709
710 // C++ [basic.std.dynamic]p2:
711 // [...] The following allocation and deallocation functions (18.4) are
712 // implicitly declared in global scope in each translation unit of a
713 // program
714 //
715 // void* operator new(std::size_t) throw(std::bad_alloc);
716 // void* operator new[](std::size_t) throw(std::bad_alloc);
717 // void operator delete(void*) throw();
718 // void operator delete[](void*) throw();
719 //
720 // These implicit declarations introduce only the function names operator
721 // new, operator new[], operator delete, operator delete[].
722 //
723 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
724 // "std" or "bad_alloc" as necessary to form the exception specification.
725 // However, we do not make these implicit declarations visible to name
726 // lookup.
727 if (!StdNamespace) {
728 // The "std" namespace has not yet been defined, so build one implicitly.
729 StdNamespace = NamespaceDecl::Create(Context,
730 Context.getTranslationUnitDecl(),
731 SourceLocation(),
732 &PP.getIdentifierTable().get("std"));
733 StdNamespace->setImplicit(true);
734 }
735
736 if (!StdBadAlloc) {
737 // The "std::bad_alloc" class has not yet been declared, so build it
738 // implicitly.
739 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
740 StdNamespace,
741 SourceLocation(),
742 &PP.getIdentifierTable().get("bad_alloc"),
743 SourceLocation(), 0);
744 StdBadAlloc->setImplicit(true);
745 }
746
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000747 GlobalNewDeleteDeclared = true;
748
749 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
750 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000751 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000752
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000753 DeclareGlobalAllocationFunction(
754 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000755 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000756 DeclareGlobalAllocationFunction(
757 Context.DeclarationNames.getCXXOperatorName(OO_Array_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_Delete),
761 Context.VoidTy, VoidPtr);
762 DeclareGlobalAllocationFunction(
763 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
764 Context.VoidTy, VoidPtr);
765}
766
767/// DeclareGlobalAllocationFunction - Declares a single implicit global
768/// allocation function if it doesn't already exist.
769void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000770 QualType Return, QualType Argument,
771 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000772 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
773
774 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000775 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000776 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000777 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000778 Alloc != AllocEnd; ++Alloc) {
779 // FIXME: Do we need to check for default arguments here?
780 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
781 if (Func->getNumParams() == 1 &&
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000782 Context.getCanonicalType(
783 Func->getParamDecl(0)->getType().getUnqualifiedType()) == Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000784 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000785 }
786 }
787
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000788 QualType BadAllocType;
789 bool HasBadAllocExceptionSpec
790 = (Name.getCXXOverloadedOperator() == OO_New ||
791 Name.getCXXOverloadedOperator() == OO_Array_New);
792 if (HasBadAllocExceptionSpec) {
793 assert(StdBadAlloc && "Must have std::bad_alloc declared");
794 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
795 }
796
797 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
798 true, false,
799 HasBadAllocExceptionSpec? 1 : 0,
800 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000801 FunctionDecl *Alloc =
802 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000803 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000804 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000805
806 if (AddMallocAttr)
807 Alloc->addAttr(::new (Context) MallocAttr());
808
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000809 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000810 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000811 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000812 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000813
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000814 // FIXME: Also add this declaration to the IdentifierResolver, but
815 // make sure it is at the end of the chain to coincide with the
816 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000817 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000818}
819
Anders Carlsson78f74552009-11-15 18:45:20 +0000820bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
821 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000822 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000823 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000824 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000825 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000826
John McCalla24dc2e2009-11-17 02:14:36 +0000827 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000828 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000829
830 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
831 F != FEnd; ++F) {
832 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
833 if (Delete->isUsualDeallocationFunction()) {
834 Operator = Delete;
835 return false;
836 }
837 }
838
839 // We did find operator delete/operator delete[] declarations, but
840 // none of them were suitable.
841 if (!Found.empty()) {
842 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
843 << Name << RD;
844
845 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
846 F != FEnd; ++F) {
847 Diag((*F)->getLocation(),
848 diag::note_delete_member_function_declared_here)
849 << Name;
850 }
851
852 return true;
853 }
854
855 // Look for a global declaration.
856 DeclareGlobalNewDelete();
857 DeclContext *TUDecl = Context.getTranslationUnitDecl();
858
859 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
860 Expr* DeallocArgs[1];
861 DeallocArgs[0] = &Null;
862 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
863 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
864 Operator))
865 return true;
866
867 assert(Operator && "Did not find a deallocation function!");
868 return false;
869}
870
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000871/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
872/// @code ::delete ptr; @endcode
873/// or
874/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000875Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000876Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000877 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000878 // C++ [expr.delete]p1:
879 // The operand shall have a pointer type, or a class type having a single
880 // conversion function to a pointer type. The result has type void.
881 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000882 // DR599 amends "pointer type" to "pointer to object type" in both cases.
883
Anders Carlssond67c4c32009-08-16 20:29:29 +0000884 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Sebastian Redlf53597f2009-03-15 17:47:39 +0000886 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000887 if (!Ex->isTypeDependent()) {
888 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000889
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000890 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000891 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000892 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000893 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000894
John McCallba135432009-11-21 08:51:07 +0000895 for (UnresolvedSet::iterator I = Conversions->begin(),
896 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000897 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000898 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000899 continue;
900
John McCallba135432009-11-21 08:51:07 +0000901 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000902
903 QualType ConvType = Conv->getConversionType().getNonReferenceType();
904 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
905 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000906 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000907 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000908 if (ObjectPtrConversions.size() == 1) {
909 // We have a single conversion to a pointer-to-object type. Perform
910 // that conversion.
911 Operand.release();
912 if (!PerformImplicitConversion(Ex,
913 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000914 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000915 Operand = Owned(Ex);
916 Type = Ex->getType();
917 }
918 }
919 else if (ObjectPtrConversions.size() > 1) {
920 Diag(StartLoc, diag::err_ambiguous_delete_operand)
921 << Type << Ex->getSourceRange();
922 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
923 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +0000924 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000925 }
926 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000927 }
Sebastian Redl28507842009-02-26 14:39:58 +0000928 }
929
Sebastian Redlf53597f2009-03-15 17:47:39 +0000930 if (!Type->isPointerType())
931 return ExprError(Diag(StartLoc, diag::err_delete_operand)
932 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000933
Ted Kremenek6217b802009-07-29 21:53:49 +0000934 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000935 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000936 return ExprError(Diag(StartLoc, diag::err_delete_operand)
937 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000938 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000939 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000940 PDiag(diag::warn_delete_incomplete)
941 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000942 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000943
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000944 // C++ [expr.delete]p2:
945 // [Note: a pointer to a const type can be the operand of a
946 // delete-expression; it is not necessary to cast away the constness
947 // (5.2.11) of the pointer expression before it is used as the operand
948 // of the delete-expression. ]
949 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
950 CastExpr::CK_NoOp);
951
952 // Update the operand.
953 Operand.take();
954 Operand = ExprArg(*this, Ex);
955
Anders Carlssond67c4c32009-08-16 20:29:29 +0000956 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
957 ArrayForm ? OO_Array_Delete : OO_Delete);
958
Anders Carlsson78f74552009-11-15 18:45:20 +0000959 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
960 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
961
962 if (!UseGlobal &&
963 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000964 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000965
Anders Carlsson78f74552009-11-15 18:45:20 +0000966 if (!RD->hasTrivialDestructor())
967 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000968 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000969 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000970 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000971
Anders Carlssond67c4c32009-08-16 20:29:29 +0000972 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000973 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000974 DeclareGlobalNewDelete();
975 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000976 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000977 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000978 OperatorDelete))
979 return ExprError();
980 }
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Sebastian Redl28507842009-02-26 14:39:58 +0000982 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000983 }
984
Sebastian Redlf53597f2009-03-15 17:47:39 +0000985 Operand.release();
986 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000987 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000988}
989
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000990/// \brief Check the use of the given variable as a C++ condition in an if,
991/// while, do-while, or switch statement.
992Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
993 QualType T = ConditionVar->getType();
994
995 // C++ [stmt.select]p2:
996 // The declarator shall not specify a function or an array.
997 if (T->isFunctionType())
998 return ExprError(Diag(ConditionVar->getLocation(),
999 diag::err_invalid_use_of_function_type)
1000 << ConditionVar->getSourceRange());
1001 else if (T->isArrayType())
1002 return ExprError(Diag(ConditionVar->getLocation(),
1003 diag::err_invalid_use_of_array_type)
1004 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001005
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001006 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1007 ConditionVar->getLocation(),
1008 ConditionVar->getType().getNonReferenceType()));
1009}
1010
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001011/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1012bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1013 // C++ 6.4p4:
1014 // The value of a condition that is an initialized declaration in a statement
1015 // other than a switch statement is the value of the declared variable
1016 // implicitly converted to type bool. If that conversion is ill-formed, the
1017 // program is ill-formed.
1018 // The value of a condition that is an expression is the value of the
1019 // expression, implicitly converted to bool.
1020 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001021 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001022}
Douglas Gregor77a52232008-09-12 00:47:35 +00001023
1024/// Helper function to determine whether this is the (deprecated) C++
1025/// conversion from a string literal to a pointer to non-const char or
1026/// non-const wchar_t (for narrow and wide string literals,
1027/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001028bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001029Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1030 // Look inside the implicit cast, if it exists.
1031 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1032 From = Cast->getSubExpr();
1033
1034 // A string literal (2.13.4) that is not a wide string literal can
1035 // be converted to an rvalue of type "pointer to char"; a wide
1036 // string literal can be converted to an rvalue of type "pointer
1037 // to wchar_t" (C++ 4.2p2).
1038 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001039 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001040 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001041 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001042 // This conversion is considered only when there is an
1043 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001044 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001045 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1046 (!StrLit->isWide() &&
1047 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1048 ToPointeeType->getKind() == BuiltinType::Char_S))))
1049 return true;
1050 }
1051
1052 return false;
1053}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001054
1055/// PerformImplicitConversion - Perform an implicit conversion of the
1056/// expression From to the type ToType. Returns true if there was an
1057/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001058/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001059/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001060/// explicit user-defined conversions are permitted. @p Elidable should be true
1061/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1062/// resolution works differently in that case.
1063bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001064Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001065 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001066 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001067 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001068 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001069 Elidable, ICS);
1070}
1071
1072bool
1073Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001074 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001075 bool Elidable,
1076 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001077 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1078 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001079 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001080 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001081 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001082 /*ForceRValue=*/true,
1083 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001084 }
1085 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001086 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001087 /*SuppressUserConversions=*/false,
1088 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001089 /*ForceRValue=*/false,
1090 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001091 }
Douglas Gregor68647482009-12-16 03:45:30 +00001092 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001093}
1094
1095/// PerformImplicitConversion - Perform an implicit conversion of the
1096/// expression From to the type ToType using the pre-computed implicit
1097/// conversion sequence ICS. Returns true if there was an error, false
1098/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001099/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001100/// used in the error message.
1101bool
1102Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1103 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001104 AssignmentAction Action, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001105 switch (ICS.ConversionKind) {
1106 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001107 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001108 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001109 return true;
1110 break;
1111
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001112 case ImplicitConversionSequence::UserDefinedConversion: {
1113
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001114 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1115 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001116 QualType BeforeToType;
1117 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001118 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001119
1120 // If the user-defined conversion is specified by a conversion function,
1121 // the initial standard conversion sequence converts the source type to
1122 // the implicit object parameter of the conversion function.
1123 BeforeToType = Context.getTagDeclType(Conv->getParent());
1124 } else if (const CXXConstructorDecl *Ctor =
1125 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001126 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001127 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001128 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001129 // If the user-defined conversion is specified by a constructor, the
1130 // initial standard conversion sequence converts the source type to the
1131 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001132 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1133 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001134 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001135 else
1136 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001137 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001138 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001139 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001140 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001141 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001142 return true;
1143 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001144
Anders Carlsson0aebc812009-09-09 21:33:21 +00001145 OwningExprResult CastArg
1146 = BuildCXXCastArgument(From->getLocStart(),
1147 ToType.getNonReferenceType(),
1148 CastKind, cast<CXXMethodDecl>(FD),
1149 Owned(From));
1150
1151 if (CastArg.isInvalid())
1152 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001153
1154 From = CastArg.takeAs<Expr>();
1155
Eli Friedmand8889622009-11-27 04:41:50 +00001156 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001157 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001158 }
1159
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001160 case ImplicitConversionSequence::EllipsisConversion:
1161 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001162 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001163
1164 case ImplicitConversionSequence::BadConversion:
1165 return true;
1166 }
1167
1168 // Everything went well.
1169 return false;
1170}
1171
1172/// PerformImplicitConversion - Perform an implicit conversion of the
1173/// expression From to the type ToType by following the standard
1174/// conversion sequence SCS. Returns true if there was an error, false
1175/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001176/// expression. Flavor is the context in which we're performing this
1177/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001178bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001179Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001180 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001181 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001182 // Overall FIXME: we are recomputing too many types here and doing far too
1183 // much extra work. What this means is that we need to keep track of more
1184 // information that is computed when we try the implicit conversion initially,
1185 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001186 QualType FromType = From->getType();
1187
Douglas Gregor225c41e2008-11-03 19:09:14 +00001188 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001189 // FIXME: When can ToType be a reference type?
1190 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001191 if (SCS.Second == ICK_Derived_To_Base) {
1192 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1193 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1194 MultiExprArg(*this, (void **)&From, 1),
1195 /*FIXME:ConstructLoc*/SourceLocation(),
1196 ConstructorArgs))
1197 return true;
1198 OwningExprResult FromResult =
1199 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1200 ToType, SCS.CopyConstructor,
1201 move_arg(ConstructorArgs));
1202 if (FromResult.isInvalid())
1203 return true;
1204 From = FromResult.takeAs<Expr>();
1205 return false;
1206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207 OwningExprResult FromResult =
1208 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1209 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001210 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001212 if (FromResult.isInvalid())
1213 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001215 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001216 return false;
1217 }
1218
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001219 // Perform the first implicit conversion.
1220 switch (SCS.First) {
1221 case ICK_Identity:
1222 case ICK_Lvalue_To_Rvalue:
1223 // Nothing to do.
1224 break;
1225
1226 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001227 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001228 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001229 break;
1230
1231 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001232 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001233 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1234 if (!Fn)
1235 return true;
1236
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001237 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1238 return true;
1239
Anders Carlsson96ad5332009-10-21 17:16:23 +00001240 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001241 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001242
Sebastian Redl759986e2009-10-17 20:50:27 +00001243 // If there's already an address-of operator in the expression, we have
1244 // the right type already, and the code below would just introduce an
1245 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001246 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001247 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001248 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001249 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001250 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001251 break;
1252
1253 default:
1254 assert(false && "Improper first standard conversion");
1255 break;
1256 }
1257
1258 // Perform the second implicit conversion
1259 switch (SCS.Second) {
1260 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001261 // If both sides are functions (or pointers/references to them), there could
1262 // be incompatible exception declarations.
1263 if (CheckExceptionSpecCompatibility(From, ToType))
1264 return true;
1265 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001266 break;
1267
Douglas Gregor43c79c22009-12-09 00:47:37 +00001268 case ICK_NoReturn_Adjustment:
1269 // If both sides are functions (or pointers/references to them), there could
1270 // be incompatible exception declarations.
1271 if (CheckExceptionSpecCompatibility(From, ToType))
1272 return true;
1273
1274 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1275 CastExpr::CK_NoOp);
1276 break;
1277
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001279 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001280 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1281 break;
1282
1283 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001284 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001285 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1286 break;
1287
1288 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001289 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001290 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1291 break;
1292
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001293 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001294 if (ToType->isFloatingType())
1295 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1296 else
1297 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1298 break;
1299
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001300 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001301 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1302 break;
1303
Douglas Gregorf9201e02009-02-11 23:02:49 +00001304 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001305 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 break;
1307
Anders Carlsson61faec12009-09-12 04:46:44 +00001308 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001309 if (SCS.IncompatibleObjC) {
1310 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001311 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001312 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001313 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001314 << From->getSourceRange();
1315 }
1316
Anders Carlsson61faec12009-09-12 04:46:44 +00001317
1318 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001319 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001320 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001321 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001322 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001323 }
1324
1325 case ICK_Pointer_Member: {
1326 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001327 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001328 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001329 if (CheckExceptionSpecCompatibility(From, ToType))
1330 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001331 ImpCastExprToType(From, ToType, Kind);
1332 break;
1333 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001334 case ICK_Boolean_Conversion: {
1335 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1336 if (FromType->isMemberPointerType())
1337 Kind = CastExpr::CK_MemberPointerToBoolean;
1338
1339 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001340 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001341 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001342
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001343 case ICK_Derived_To_Base:
1344 if (CheckDerivedToBaseConversion(From->getType(),
1345 ToType.getNonReferenceType(),
1346 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001347 From->getSourceRange(),
1348 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001349 return true;
1350 ImpCastExprToType(From, ToType.getNonReferenceType(),
1351 CastExpr::CK_DerivedToBase);
1352 break;
1353
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001354 default:
1355 assert(false && "Improper second standard conversion");
1356 break;
1357 }
1358
1359 switch (SCS.Third) {
1360 case ICK_Identity:
1361 // Nothing to do.
1362 break;
1363
1364 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001365 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1366 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001367 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001368 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001369 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001370 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001371
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001372 default:
1373 assert(false && "Improper second standard conversion");
1374 break;
1375 }
1376
1377 return false;
1378}
1379
Sebastian Redl64b45f72009-01-05 20:52:13 +00001380Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1381 SourceLocation KWLoc,
1382 SourceLocation LParen,
1383 TypeTy *Ty,
1384 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001385 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001387 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1388 // all traits except __is_class, __is_enum and __is_union require a the type
1389 // to be complete.
1390 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001391 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001392 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001393 return ExprError();
1394 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001395
1396 // There is no point in eagerly computing the value. The traits are designed
1397 // to be used from type trait templates, so Ty will be a template parameter
1398 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001399 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1400 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001401}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001402
1403QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001404 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001405 const char *OpSpelling = isIndirect ? "->*" : ".*";
1406 // C++ 5.5p2
1407 // The binary operator .* [p3: ->*] binds its second operand, which shall
1408 // be of type "pointer to member of T" (where T is a completely-defined
1409 // class type) [...]
1410 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001411 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001412 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001413 Diag(Loc, diag::err_bad_memptr_rhs)
1414 << OpSpelling << RType << rex->getSourceRange();
1415 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001416 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001417
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001418 QualType Class(MemPtr->getClass(), 0);
1419
1420 // C++ 5.5p2
1421 // [...] to its first operand, which shall be of class T or of a class of
1422 // which T is an unambiguous and accessible base class. [p3: a pointer to
1423 // such a class]
1424 QualType LType = lex->getType();
1425 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001426 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001427 LType = Ptr->getPointeeType().getNonReferenceType();
1428 else {
1429 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001430 << OpSpelling << 1 << LType
1431 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001432 return QualType();
1433 }
1434 }
1435
Douglas Gregora4923eb2009-11-16 21:35:15 +00001436 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001437 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1438 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001439 // FIXME: Would it be useful to print full ambiguity paths, or is that
1440 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001441 if (!IsDerivedFrom(LType, Class, Paths) ||
1442 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001443 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001444 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001445 << (int)isIndirect << lex->getType() <<
1446 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001447 return QualType();
1448 }
1449 }
1450
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001451 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001452 // Diagnose use of pointer-to-member type which when used as
1453 // the functional cast in a pointer-to-member expression.
1454 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1455 return QualType();
1456 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001457 // C++ 5.5p2
1458 // The result is an object or a function of the type specified by the
1459 // second operand.
1460 // The cv qualifiers are the union of those in the pointer and the left side,
1461 // in accordance with 5.5p5 and 5.2.5.
1462 // FIXME: This returns a dereferenced member function pointer as a normal
1463 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001464 // calling them. There's also a GCC extension to get a function pointer to the
1465 // thing, which is another complication, because this type - unlike the type
1466 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001467 // argument.
1468 // We probably need a "MemberFunctionClosureType" or something like that.
1469 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001470 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001471 return Result;
1472}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001473
1474/// \brief Get the target type of a standard or user-defined conversion.
1475static QualType TargetType(const ImplicitConversionSequence &ICS) {
1476 assert((ICS.ConversionKind ==
1477 ImplicitConversionSequence::StandardConversion ||
1478 ICS.ConversionKind ==
1479 ImplicitConversionSequence::UserDefinedConversion) &&
1480 "function only valid for standard or user-defined conversions");
1481 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1482 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1483 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1484}
1485
1486/// \brief Try to convert a type to another according to C++0x 5.16p3.
1487///
1488/// This is part of the parameter validation for the ? operator. If either
1489/// value operand is a class type, the two operands are attempted to be
1490/// converted to each other. This function does the conversion in one direction.
1491/// It emits a diagnostic and returns true only if it finds an ambiguous
1492/// conversion.
1493static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1494 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001495 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001496 // C++0x 5.16p3
1497 // The process for determining whether an operand expression E1 of type T1
1498 // can be converted to match an operand expression E2 of type T2 is defined
1499 // as follows:
1500 // -- If E2 is an lvalue:
1501 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1502 // E1 can be converted to match E2 if E1 can be implicitly converted to
1503 // type "lvalue reference to T2", subject to the constraint that in the
1504 // conversion the reference must bind directly to E1.
1505 if (!Self.CheckReferenceInit(From,
1506 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001507 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001508 /*SuppressUserConversions=*/false,
1509 /*AllowExplicit=*/false,
1510 /*ForceRValue=*/false,
1511 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001512 {
1513 assert((ICS.ConversionKind ==
1514 ImplicitConversionSequence::StandardConversion ||
1515 ICS.ConversionKind ==
1516 ImplicitConversionSequence::UserDefinedConversion) &&
1517 "expected a definite conversion");
1518 bool DirectBinding =
1519 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1520 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1521 if (DirectBinding)
1522 return false;
1523 }
1524 }
1525 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1526 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1527 // -- if E1 and E2 have class type, and the underlying class types are
1528 // the same or one is a base class of the other:
1529 QualType FTy = From->getType();
1530 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001531 const RecordType *FRec = FTy->getAs<RecordType>();
1532 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001533 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1534 if (FRec && TRec && (FRec == TRec ||
1535 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1536 // E1 can be converted to match E2 if the class of T2 is the
1537 // same type as, or a base class of, the class of T1, and
1538 // [cv2 > cv1].
1539 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1540 // Could still fail if there's no copy constructor.
1541 // FIXME: Is this a hard error then, or just a conversion failure? The
1542 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001543 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001544 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001545 /*ForceRValue=*/false,
1546 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001547 }
1548 } else {
1549 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1550 // implicitly converted to the type that expression E2 would have
1551 // if E2 were converted to an rvalue.
1552 // First find the decayed type.
1553 if (TTy->isFunctionType())
1554 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001555 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001556 TTy = Self.Context.getArrayDecayedType(TTy);
1557
1558 // Now try the implicit conversion.
1559 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001560 ICS = Self.TryImplicitConversion(From, TTy,
1561 /*SuppressUserConversions=*/false,
1562 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001563 /*ForceRValue=*/false,
1564 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001565 }
1566 return false;
1567}
1568
1569/// \brief Try to find a common type for two according to C++0x 5.16p5.
1570///
1571/// This is part of the parameter validation for the ? operator. If either
1572/// value operand is a class type, overload resolution is used to find a
1573/// conversion to a common type.
1574static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1575 SourceLocation Loc) {
1576 Expr *Args[2] = { LHS, RHS };
1577 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001578 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001579
1580 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001581 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001582 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001583 // We found a match. Perform the conversions on the arguments and move on.
1584 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001585 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001586 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001587 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001588 break;
1589 return false;
1590
Douglas Gregor20093b42009-12-09 23:02:17 +00001591 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001592 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1593 << LHS->getType() << RHS->getType()
1594 << LHS->getSourceRange() << RHS->getSourceRange();
1595 return true;
1596
Douglas Gregor20093b42009-12-09 23:02:17 +00001597 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001598 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1599 << LHS->getType() << RHS->getType()
1600 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001601 // FIXME: Print the possible common types by printing the return types of
1602 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001603 break;
1604
Douglas Gregor20093b42009-12-09 23:02:17 +00001605 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001606 assert(false && "Conditional operator has only built-in overloads");
1607 break;
1608 }
1609 return true;
1610}
1611
Sebastian Redl76458502009-04-17 16:30:52 +00001612/// \brief Perform an "extended" implicit conversion as returned by
1613/// TryClassUnification.
1614///
1615/// TryClassUnification generates ICSs that include reference bindings.
1616/// PerformImplicitConversion is not suitable for this; it chokes if the
1617/// second part of a standard conversion is ICK_DerivedToBase. This function
1618/// handles the reference binding specially.
1619static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001620 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001621 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1622 ICS.Standard.ReferenceBinding) {
1623 assert(ICS.Standard.DirectBinding &&
1624 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001625 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1626 // redoing all the work.
1627 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001628 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001629 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001630 /*SuppressUserConversions=*/false,
1631 /*AllowExplicit=*/false,
1632 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001633 }
1634 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1635 ICS.UserDefined.After.ReferenceBinding) {
1636 assert(ICS.UserDefined.After.DirectBinding &&
1637 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001638 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001639 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001640 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001641 /*SuppressUserConversions=*/false,
1642 /*AllowExplicit=*/false,
1643 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001644 }
Douglas Gregor68647482009-12-16 03:45:30 +00001645 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001646 return true;
1647 return false;
1648}
1649
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001650/// \brief Check the operands of ?: under C++ semantics.
1651///
1652/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1653/// extension. In this case, LHS == Cond. (But they're not aliases.)
1654QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1655 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001656 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1657 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001658
1659 // C++0x 5.16p1
1660 // The first expression is contextually converted to bool.
1661 if (!Cond->isTypeDependent()) {
1662 if (CheckCXXBooleanCondition(Cond))
1663 return QualType();
1664 }
1665
1666 // Either of the arguments dependent?
1667 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1668 return Context.DependentTy;
1669
John McCallb13c87f2009-11-05 09:23:39 +00001670 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1671
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001672 // C++0x 5.16p2
1673 // If either the second or the third operand has type (cv) void, ...
1674 QualType LTy = LHS->getType();
1675 QualType RTy = RHS->getType();
1676 bool LVoid = LTy->isVoidType();
1677 bool RVoid = RTy->isVoidType();
1678 if (LVoid || RVoid) {
1679 // ... then the [l2r] conversions are performed on the second and third
1680 // operands ...
1681 DefaultFunctionArrayConversion(LHS);
1682 DefaultFunctionArrayConversion(RHS);
1683 LTy = LHS->getType();
1684 RTy = RHS->getType();
1685
1686 // ... and one of the following shall hold:
1687 // -- The second or the third operand (but not both) is a throw-
1688 // expression; the result is of the type of the other and is an rvalue.
1689 bool LThrow = isa<CXXThrowExpr>(LHS);
1690 bool RThrow = isa<CXXThrowExpr>(RHS);
1691 if (LThrow && !RThrow)
1692 return RTy;
1693 if (RThrow && !LThrow)
1694 return LTy;
1695
1696 // -- Both the second and third operands have type void; the result is of
1697 // type void and is an rvalue.
1698 if (LVoid && RVoid)
1699 return Context.VoidTy;
1700
1701 // Neither holds, error.
1702 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1703 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1704 << LHS->getSourceRange() << RHS->getSourceRange();
1705 return QualType();
1706 }
1707
1708 // Neither is void.
1709
1710 // C++0x 5.16p3
1711 // Otherwise, if the second and third operand have different types, and
1712 // either has (cv) class type, and attempt is made to convert each of those
1713 // operands to the other.
1714 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1715 (LTy->isRecordType() || RTy->isRecordType())) {
1716 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1717 // These return true if a single direction is already ambiguous.
1718 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1719 return QualType();
1720 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1721 return QualType();
1722
1723 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1724 ImplicitConversionSequence::BadConversion;
1725 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1726 ImplicitConversionSequence::BadConversion;
1727 // If both can be converted, [...] the program is ill-formed.
1728 if (HaveL2R && HaveR2L) {
1729 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1730 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1731 return QualType();
1732 }
1733
1734 // If exactly one conversion is possible, that conversion is applied to
1735 // the chosen operand and the converted operands are used in place of the
1736 // original operands for the remainder of this section.
1737 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001738 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001739 return QualType();
1740 LTy = LHS->getType();
1741 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001742 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001743 return QualType();
1744 RTy = RHS->getType();
1745 }
1746 }
1747
1748 // C++0x 5.16p4
1749 // If the second and third operands are lvalues and have the same type,
1750 // the result is of that type [...]
1751 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1752 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1753 RHS->isLvalue(Context) == Expr::LV_Valid)
1754 return LTy;
1755
1756 // C++0x 5.16p5
1757 // Otherwise, the result is an rvalue. If the second and third operands
1758 // do not have the same type, and either has (cv) class type, ...
1759 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1760 // ... overload resolution is used to determine the conversions (if any)
1761 // to be applied to the operands. If the overload resolution fails, the
1762 // program is ill-formed.
1763 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1764 return QualType();
1765 }
1766
1767 // C++0x 5.16p6
1768 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1769 // conversions are performed on the second and third operands.
1770 DefaultFunctionArrayConversion(LHS);
1771 DefaultFunctionArrayConversion(RHS);
1772 LTy = LHS->getType();
1773 RTy = RHS->getType();
1774
1775 // After those conversions, one of the following shall hold:
1776 // -- The second and third operands have the same type; the result
1777 // is of that type.
1778 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1779 return LTy;
1780
1781 // -- The second and third operands have arithmetic or enumeration type;
1782 // the usual arithmetic conversions are performed to bring them to a
1783 // common type, and the result is of that type.
1784 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1785 UsualArithmeticConversions(LHS, RHS);
1786 return LHS->getType();
1787 }
1788
1789 // -- The second and third operands have pointer type, or one has pointer
1790 // type and the other is a null pointer constant; pointer conversions
1791 // and qualification conversions are performed to bring them to their
1792 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00001793 // -- The second and third operands have pointer to member type, or one has
1794 // pointer to member type and the other is a null pointer constant;
1795 // pointer to member conversions and qualification conversions are
1796 // performed to bring them to a common type, whose cv-qualification
1797 // shall match the cv-qualification of either the second or the third
1798 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001799 QualType Composite = FindCompositePointerType(LHS, RHS);
1800 if (!Composite.isNull())
1801 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001802
1803 // Similarly, attempt to find composite type of twp objective-c pointers.
1804 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1805 if (!Composite.isNull())
1806 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001807
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001808 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1809 << LHS->getType() << RHS->getType()
1810 << LHS->getSourceRange() << RHS->getSourceRange();
1811 return QualType();
1812}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001813
1814/// \brief Find a merged pointer type and convert the two expressions to it.
1815///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001816/// This finds the composite pointer type (or member pointer type) for @p E1
1817/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1818/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001819/// It does not emit diagnostics.
1820QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1821 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1822 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001824 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1825 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001826 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001827
1828 // C++0x 5.9p2
1829 // Pointer conversions and qualification conversions are performed on
1830 // pointer operands to bring them to their composite pointer type. If
1831 // one operand is a null pointer constant, the composite pointer type is
1832 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001833 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001834 if (T2->isMemberPointerType())
1835 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1836 else
1837 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001838 return T2;
1839 }
Douglas Gregorce940492009-09-25 04:25:58 +00001840 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001841 if (T1->isMemberPointerType())
1842 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1843 else
1844 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001845 return T1;
1846 }
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Douglas Gregor20b3e992009-08-24 17:42:35 +00001848 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001849 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1850 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001851 return QualType();
1852
1853 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1854 // the other has type "pointer to cv2 T" and the composite pointer type is
1855 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1856 // Otherwise, the composite pointer type is a pointer type similar to the
1857 // type of one of the operands, with a cv-qualification signature that is
1858 // the union of the cv-qualification signatures of the operand types.
1859 // In practice, the first part here is redundant; it's subsumed by the second.
1860 // What we do here is, we build the two possible composite types, and try the
1861 // conversions in both directions. If only one works, or if the two composite
1862 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001863 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001864 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1865 QualifierVector QualifierUnion;
1866 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1867 ContainingClassVector;
1868 ContainingClassVector MemberOfClass;
1869 QualType Composite1 = Context.getCanonicalType(T1),
1870 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001871 do {
1872 const PointerType *Ptr1, *Ptr2;
1873 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1874 (Ptr2 = Composite2->getAs<PointerType>())) {
1875 Composite1 = Ptr1->getPointeeType();
1876 Composite2 = Ptr2->getPointeeType();
1877 QualifierUnion.push_back(
1878 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1879 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1880 continue;
1881 }
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Douglas Gregor20b3e992009-08-24 17:42:35 +00001883 const MemberPointerType *MemPtr1, *MemPtr2;
1884 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1885 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1886 Composite1 = MemPtr1->getPointeeType();
1887 Composite2 = MemPtr2->getPointeeType();
1888 QualifierUnion.push_back(
1889 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1890 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1891 MemPtr2->getClass()));
1892 continue;
1893 }
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor20b3e992009-08-24 17:42:35 +00001895 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Douglas Gregor20b3e992009-08-24 17:42:35 +00001897 // Cannot unwrap any more types.
1898 break;
1899 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Douglas Gregor20b3e992009-08-24 17:42:35 +00001901 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001902 ContainingClassVector::reverse_iterator MOC
1903 = MemberOfClass.rbegin();
1904 for (QualifierVector::reverse_iterator
1905 I = QualifierUnion.rbegin(),
1906 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001907 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001908 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001909 if (MOC->first && MOC->second) {
1910 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001911 Composite1 = Context.getMemberPointerType(
1912 Context.getQualifiedType(Composite1, Quals),
1913 MOC->first);
1914 Composite2 = Context.getMemberPointerType(
1915 Context.getQualifiedType(Composite2, Quals),
1916 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001917 } else {
1918 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001919 Composite1
1920 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1921 Composite2
1922 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001923 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001924 }
1925
Mike Stump1eb44332009-09-09 15:08:12 +00001926 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001927 TryImplicitConversion(E1, Composite1,
1928 /*SuppressUserConversions=*/false,
1929 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001930 /*ForceRValue=*/false,
1931 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001932 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001933 TryImplicitConversion(E2, Composite1,
1934 /*SuppressUserConversions=*/false,
1935 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001936 /*ForceRValue=*/false,
1937 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001939 ImplicitConversionSequence E1ToC2, E2ToC2;
1940 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1941 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1942 if (Context.getCanonicalType(Composite1) !=
1943 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001944 E1ToC2 = TryImplicitConversion(E1, Composite2,
1945 /*SuppressUserConversions=*/false,
1946 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001947 /*ForceRValue=*/false,
1948 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001949 E2ToC2 = TryImplicitConversion(E2, Composite2,
1950 /*SuppressUserConversions=*/false,
1951 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001952 /*ForceRValue=*/false,
1953 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001954 }
1955
1956 bool ToC1Viable = E1ToC1.ConversionKind !=
1957 ImplicitConversionSequence::BadConversion
1958 && E2ToC1.ConversionKind !=
1959 ImplicitConversionSequence::BadConversion;
1960 bool ToC2Viable = E1ToC2.ConversionKind !=
1961 ImplicitConversionSequence::BadConversion
1962 && E2ToC2.ConversionKind !=
1963 ImplicitConversionSequence::BadConversion;
1964 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001965 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1966 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001967 return Composite1;
1968 }
1969 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001970 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1971 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001972 return Composite2;
1973 }
1974 return QualType();
1975}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001976
Anders Carlssondef11992009-05-30 20:36:53 +00001977Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001978 if (!Context.getLangOptions().CPlusPlus)
1979 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Douglas Gregor51326552009-12-24 18:51:59 +00001981 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1982
Ted Kremenek6217b802009-07-29 21:53:49 +00001983 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001984 if (!RT)
1985 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Anders Carlssondef11992009-05-30 20:36:53 +00001987 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1988 if (RD->hasTrivialDestructor())
1989 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Anders Carlsson283e4d52009-09-14 01:30:44 +00001991 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1992 QualType Ty = CE->getCallee()->getType();
1993 if (const PointerType *PT = Ty->getAs<PointerType>())
1994 Ty = PT->getPointeeType();
1995
John McCall183700f2009-09-21 23:43:11 +00001996 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001997 if (FTy->getResultType()->isReferenceType())
1998 return Owned(E);
1999 }
Mike Stump1eb44332009-09-09 15:08:12 +00002000 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002001 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002002 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002003 if (CXXDestructorDecl *Destructor =
2004 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2005 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002006 // FIXME: Add the temporary to the temporaries vector.
2007 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2008}
2009
Anders Carlsson0ece4912009-12-15 20:51:39 +00002010Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002011 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002013 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2014 assert(ExprTemporaries.size() >= FirstTemporary);
2015 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002016 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002018 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002019 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002020 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002021 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2022 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002024 return E;
2025}
2026
Douglas Gregor90f93822009-12-22 22:17:25 +00002027Sema::OwningExprResult
2028Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2029 if (SubExpr.isInvalid())
2030 return ExprError();
2031
2032 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2033}
2034
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002035FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2036 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2037 assert(ExprTemporaries.size() >= FirstTemporary);
2038
2039 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2040 CXXTemporary **Temporaries =
2041 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2042
2043 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2044
2045 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2046 ExprTemporaries.end());
2047
2048 return E;
2049}
2050
Mike Stump1eb44332009-09-09 15:08:12 +00002051Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002052Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2053 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2054 // Since this might be a postfix expression, get rid of ParenListExprs.
2055 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002057 Expr *BaseExpr = (Expr*)Base.get();
2058 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002060 QualType BaseType = BaseExpr->getType();
2061 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002062 // If we have a pointer to a dependent type and are using the -> operator,
2063 // the object type is the type that the pointer points to. We might still
2064 // have enough information about that type to do something useful.
2065 if (OpKind == tok::arrow)
2066 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2067 BaseType = Ptr->getPointeeType();
2068
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002069 ObjectType = BaseType.getAsOpaquePtr();
2070 return move(Base);
2071 }
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002073 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002074 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002075 // returned, with the original second operand.
2076 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002077 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002078 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002079 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002080 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002081
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002082 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002083 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002084 BaseExpr = (Expr*)Base.get();
2085 if (BaseExpr == NULL)
2086 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002087 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002088 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002089 BaseType = BaseExpr->getType();
2090 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002091 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002092 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002093 for (unsigned i = 0; i < Locations.size(); i++)
2094 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002095 return ExprError();
2096 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Douglas Gregor31658df2009-11-20 19:58:21 +00002099 if (BaseType->isPointerType())
2100 BaseType = BaseType->getPointeeType();
2101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
2103 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002104 // vector types or Objective-C interfaces. Just return early and let
2105 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002106 if (!BaseType->isRecordType()) {
2107 // C++ [basic.lookup.classref]p2:
2108 // [...] If the type of the object expression is of pointer to scalar
2109 // type, the unqualified-id is looked up in the context of the complete
2110 // postfix-expression.
2111 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002112 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Douglas Gregor03c57052009-11-17 05:17:33 +00002115 // The object type must be complete (or dependent).
2116 if (!BaseType->isDependentType() &&
2117 RequireCompleteType(OpLoc, BaseType,
2118 PDiag(diag::err_incomplete_member_access)))
2119 return ExprError();
2120
Douglas Gregorc68afe22009-09-03 21:38:09 +00002121 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002122 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002123 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002124 // type C (or of pointer to a class type C), the unqualified-id is looked
2125 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002126 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002127
Mike Stump1eb44332009-09-09 15:08:12 +00002128 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002129}
2130
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002131CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2132 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002133 if (PerformObjectArgumentInitialization(Exp, Method))
2134 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2135
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002136 MemberExpr *ME =
2137 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2138 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002139 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002140 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2141 CXXMemberCallExpr *CE =
2142 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2143 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002144 return CE;
2145}
2146
Anders Carlsson0aebc812009-09-09 21:33:21 +00002147Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2148 QualType Ty,
2149 CastExpr::CastKind Kind,
2150 CXXMethodDecl *Method,
2151 ExprArg Arg) {
2152 Expr *From = Arg.takeAs<Expr>();
2153
2154 switch (Kind) {
2155 default: assert(0 && "Unhandled cast kind!");
2156 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002157 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2158
2159 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2160 MultiExprArg(*this, (void **)&From, 1),
2161 CastLoc, ConstructorArgs))
2162 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002163
2164 OwningExprResult Result =
2165 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2166 move_arg(ConstructorArgs));
2167 if (Result.isInvalid())
2168 return ExprError();
2169
2170 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002171 }
2172
2173 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002174 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002175
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002176 // Create an implicit call expr that calls it.
2177 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002178 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002179 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002180 }
2181}
2182
Anders Carlsson165a0a02009-05-17 18:41:29 +00002183Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2184 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002185 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002186 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002187
Anders Carlsson165a0a02009-05-17 18:41:29 +00002188 return Owned(FullExpr);
2189}