blob: d6947986a45507a6fe32f0aa612af1feaac4409b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Sebastian Redlc42e1182008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000033
Douglas Gregorf57f2072009-12-23 20:51:04 +000034 if (isType) {
35 // C++ [expr.typeid]p4:
36 // The top-level cv-qualifiers of the lvalue expression or the type-id
37 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000038 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +000039 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +000040 QualType T = GetTypeFromParser(TyOrExpr);
41 if (T.isNull())
42 return ExprError();
43
44 // C++ [expr.typeid]p4:
45 // If the type of the type-id is a class type or a reference to a class
46 // type, the class shall be completely-defined.
47 QualType CheckT = T;
48 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
49 CheckT = RefType->getPointeeType();
50
51 if (CheckT->getAs<RecordType>() &&
52 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
53 return ExprError();
54
55 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +000056 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000057
Chris Lattner572af492008-11-20 05:51:55 +000058 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000059 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
60 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +000061 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +000062 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000063 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000064
65 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
66
Douglas Gregorac7610d2009-06-22 20:57:11 +000067 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000068 bool isUnevaluatedOperand = true;
69 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +000070 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000072 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000073 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +000074 // C++ [expr.typeid]p3:
75 // When typeid is applied to an expression other than an lvalue of a
76 // polymorphic class type [...] [the] expression is an unevaluated
77 // operand. [...]
78 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +000079 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +000080 else {
81 // C++ [expr.typeid]p3:
82 // [...] If the type of the expression is a class type, the class
83 // shall be completely-defined.
Douglas Gregor765ccba2009-12-23 21:06:06 +000084 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
85 return ExprError();
Douglas Gregorf57f2072009-12-23 20:51:04 +000086 }
87 }
88
89 // C++ [expr.typeid]p4:
90 // [...] If the type of the type-id is a reference to a possibly
91 // cv-qualified type, the result of the typeid expression refers to a
92 // std::type_info object representing the cv-unqualified referenced
93 // type.
94 if (T.hasQualifiers()) {
95 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
96 E->isLvalue(Context));
97 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +000098 }
99 }
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Douglas Gregor2afce722009-11-26 00:44:06 +0000101 // If this is an unevaluated operand, clear out the set of
102 // declaration references we have been computing and eliminate any
103 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000104 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000105 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
109 TypeInfoType.withConst(),
110 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000111}
112
Steve Naroff1b273c42007-09-16 14:56:35 +0000113/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000114Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000115Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000116 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
119 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000120}
Chris Lattner50dd2892008-02-26 00:51:44 +0000121
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000122/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
123Action::OwningExprResult
124Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
125 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
126}
127
Chris Lattner50dd2892008-02-26 00:51:44 +0000128/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult
130Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000131 Expr *Ex = E.takeAs<Expr>();
132 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
133 return ExprError();
134 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
135}
136
137/// CheckCXXThrowOperand - Validate the operand of a throw.
138bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
139 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000140 // A throw-expression initializes a temporary object, called the exception
141 // object, the type of which is determined by removing any top-level
142 // cv-qualifiers from the static type of the operand of throw and adjusting
143 // the type from "array of T" or "function returning T" to "pointer to T"
144 // or "pointer to function returning T", [...]
145 if (E->getType().hasQualifiers())
146 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
147 E->isLvalue(Context) == Expr::LV_Valid);
148
Sebastian Redl972041f2009-04-27 20:27:31 +0000149 DefaultFunctionArrayConversion(E);
150
151 // If the type of the exception would be an incomplete type or a pointer
152 // to an incomplete type other than (cv) void the program is ill-formed.
153 QualType Ty = E->getType();
154 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000155 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000156 Ty = Ptr->getPointeeType();
157 isPointer = 1;
158 }
159 if (!isPointer || !Ty->isVoidType()) {
160 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000161 PDiag(isPointer ? diag::err_throw_incomplete_ptr
162 : diag::err_throw_incomplete)
163 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000164 return true;
165 }
166
167 // FIXME: Construct a temporary here.
168 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000169}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000172 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
173 /// is a non-lvalue expression whose value is the address of the object for
174 /// which the function is called.
175
Sebastian Redlf53597f2009-03-15 17:47:39 +0000176 if (!isa<FunctionDecl>(CurContext))
177 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000178
179 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
180 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000182 MD->getThisType(Context),
183 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000184
Sebastian Redlf53597f2009-03-15 17:47:39 +0000185 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000186}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000187
188/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
189/// Can be interpreted either as function-style casting ("int(x)")
190/// or class type construction ("ClassType(x,y,z)")
191/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000192Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000193Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
194 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000195 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000196 SourceLocation *CommaLocs,
197 SourceLocation RParenLoc) {
198 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000199 // FIXME: Preserve type source info.
200 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000201 unsigned NumExprs = exprs.size();
202 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000203 SourceLocation TyBeginLoc = TypeRange.getBegin();
204 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
205
Sebastian Redlf53597f2009-03-15 17:47:39 +0000206 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000207 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000208 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000209
210 return Owned(CXXUnresolvedConstructExpr::Create(Context,
211 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000212 LParenLoc,
213 Exprs, NumExprs,
214 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000215 }
216
Anders Carlssonbb60a502009-08-27 03:53:50 +0000217 if (Ty->isArrayType())
218 return ExprError(Diag(TyBeginLoc,
219 diag::err_value_init_for_array_type) << FullRange);
220 if (!Ty->isVoidType() &&
221 RequireCompleteType(TyBeginLoc, Ty,
222 PDiag(diag::err_invalid_incomplete_type_use)
223 << FullRange))
224 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000225
Anders Carlssonbb60a502009-08-27 03:53:50 +0000226 if (RequireNonAbstractType(TyBeginLoc, Ty,
227 diag::err_allocation_of_abstract_type))
228 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000229
230
Douglas Gregor506ae412009-01-16 18:33:17 +0000231 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000232 // If the expression list is a single expression, the type conversion
233 // expression is equivalent (in definedness, and if defined in meaning) to the
234 // corresponding cast expression.
235 //
236 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000237 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000238 CXXMethodDecl *Method = 0;
239 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
240 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000241 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000242
243 exprs.release();
244 if (Method) {
245 OwningExprResult CastArg
246 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
247 Kind, Method, Owned(Exprs[0]));
248 if (CastArg.isInvalid())
249 return ExprError();
250
251 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000252 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000253
254 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
255 Ty, TyBeginLoc, Kind,
256 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000257 }
258
Ted Kremenek6217b802009-07-29 21:53:49 +0000259 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000260 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000261
Mike Stump1eb44332009-09-09 15:08:12 +0000262 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000263 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000264 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
265
Douglas Gregor506ae412009-01-16 18:33:17 +0000266 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000267 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000268 TypeRange.getBegin(),
269 SourceRange(TypeRange.getBegin(),
270 RParenLoc),
271 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000272 InitializationKind::CreateDirect(TypeRange.getBegin(),
273 LParenLoc,
274 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000275 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000276
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 if (!Constructor)
278 return ExprError();
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280 OwningExprResult Result =
281 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000282 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000283 if (Result.isInvalid())
284 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Anders Carlssone7624a72009-08-27 05:08:22 +0000286 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000287 }
288
289 // Fall through to value-initialize an object of class type that
290 // doesn't have a user-declared default constructor.
291 }
292
293 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000294 // If the expression list specifies more than a single value, the type shall
295 // be a class with a suitably declared constructor.
296 //
297 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000298 return ExprError(Diag(CommaLocs[0],
299 diag::err_builtin_func_cast_more_than_one_arg)
300 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000301
302 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000303 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000304 // The expression T(), where T is a simple-type-specifier for a non-array
305 // complete object type or the (possibly cv-qualified) void type, creates an
306 // rvalue of the specified type, which is value-initialized.
307 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000308 exprs.release();
309 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000310}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000311
312
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
314/// @code new (memory) int[size][4] @endcode
315/// or
316/// @code ::new Foo(23, "hello") @endcode
317/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000318Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000319Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000320 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000321 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000322 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000324 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000326 // If the specified type is an array, unwrap it and save the expression.
327 if (D.getNumTypeObjects() > 0 &&
328 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
329 DeclaratorChunk &Chunk = D.getTypeObject(0);
330 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000331 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
332 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000333 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000334 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
335 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000336
337 if (ParenTypeId) {
338 // Can't have dynamic array size when the type-id is in parentheses.
339 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
340 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
341 !NumElts->isIntegerConstantExpr(Context)) {
342 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
343 << NumElts->getSourceRange();
344 return ExprError();
345 }
346 }
347
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000348 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000349 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000350 }
351
Douglas Gregor043cad22009-09-11 00:18:58 +0000352 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000353 if (ArraySize) {
354 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000355 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
356 break;
357
358 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
359 if (Expr *NumElts = (Expr *)Array.NumElts) {
360 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
361 !NumElts->isIntegerConstantExpr(Context)) {
362 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
363 << NumElts->getSourceRange();
364 return ExprError();
365 }
366 }
367 }
368 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000369
John McCalla93c9342009-12-07 02:54:59 +0000370 //FIXME: Store TypeSourceInfo in CXXNew expression.
371 TypeSourceInfo *TInfo = 0;
372 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000373 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000374 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000375
Mike Stump1eb44332009-09-09 15:08:12 +0000376 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000377 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000378 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000379 PlacementRParen,
380 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000381 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000382 D.getSourceRange().getBegin(),
383 D.getSourceRange(),
384 Owned(ArraySize),
385 ConstructorLParen,
386 move(ConstructorArgs),
387 ConstructorRParen);
388}
389
Mike Stump1eb44332009-09-09 15:08:12 +0000390Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000391Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
392 SourceLocation PlacementLParen,
393 MultiExprArg PlacementArgs,
394 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000395 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000396 QualType AllocType,
397 SourceLocation TypeLoc,
398 SourceRange TypeRange,
399 ExprArg ArraySizeE,
400 SourceLocation ConstructorLParen,
401 MultiExprArg ConstructorArgs,
402 SourceLocation ConstructorRParen) {
403 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000404 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000405
Douglas Gregor3433cf72009-05-21 00:00:09 +0000406 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000407
408 // That every array dimension except the first is constant was already
409 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000410
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000411 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
412 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000413 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000414 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000415 QualType SizeType = ArraySize->getType();
416 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000417 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
418 diag::err_array_size_not_integral)
419 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000420 // Let's see if this is a constant < 0. If so, we reject it out of hand.
421 // We don't care about special rules, so we tell the machinery it's not
422 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000423 if (!ArraySize->isValueDependent()) {
424 llvm::APSInt Value;
425 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
426 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000427 llvm::APInt::getNullValue(Value.getBitWidth()),
428 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
430 diag::err_typecheck_negative_array_size)
431 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000432 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000433 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000434
Eli Friedman73c39ab2009-10-20 08:27:19 +0000435 ImpCastExprToType(ArraySize, Context.getSizeType(),
436 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000437 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000438
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000439 FunctionDecl *OperatorNew = 0;
440 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000441 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
442 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000443
Sebastian Redl28507842009-02-26 14:39:58 +0000444 if (!AllocType->isDependentType() &&
445 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
446 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000447 SourceRange(PlacementLParen, PlacementRParen),
448 UseGlobal, AllocType, ArraySize, PlaceArgs,
449 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000450 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000451 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000452 if (OperatorNew) {
453 // Add default arguments, if any.
454 const FunctionProtoType *Proto =
455 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000456 VariadicCallType CallType =
457 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000458 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
459 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000460 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000461 if (Invalid)
462 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000463
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000464 NumPlaceArgs = AllPlaceArgs.size();
465 if (NumPlaceArgs > 0)
466 PlaceArgs = &AllPlaceArgs[0];
467 }
468
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000469 bool Init = ConstructorLParen.isValid();
470 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000471 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
473 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000474 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
475
Douglas Gregor99a2e602009-12-16 01:38:02 +0000476 if (!AllocType->isDependentType() &&
477 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
478 // C++0x [expr.new]p15:
479 // A new-expression that creates an object of type T initializes that
480 // object as follows:
481 InitializationKind Kind
482 // - If the new-initializer is omitted, the object is default-
483 // initialized (8.5); if no initialization is performed,
484 // the object has indeterminate value
485 = !Init? InitializationKind::CreateDefault(TypeLoc)
486 // - Otherwise, the new-initializer is interpreted according to the
487 // initialization rules of 8.5 for direct-initialization.
488 : InitializationKind::CreateDirect(TypeLoc,
489 ConstructorLParen,
490 ConstructorRParen);
491
Douglas Gregor99a2e602009-12-16 01:38:02 +0000492 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000493 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000494 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000495 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
496 move(ConstructorArgs));
497 if (FullInit.isInvalid())
498 return ExprError();
499
500 // FullInit is our initializer; walk through it to determine if it's a
501 // constructor call, which CXXNewExpr handles directly.
502 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
503 if (CXXBindTemporaryExpr *Binder
504 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
505 FullInitExpr = Binder->getSubExpr();
506 if (CXXConstructExpr *Construct
507 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
508 Constructor = Construct->getConstructor();
509 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
510 AEnd = Construct->arg_end();
511 A != AEnd; ++A)
512 ConvertedConstructorArgs.push_back(A->Retain());
513 } else {
514 // Take the converted initializer.
515 ConvertedConstructorArgs.push_back(FullInit.release());
516 }
517 } else {
518 // No initialization required.
519 }
520
521 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000522 NumConsArgs = ConvertedConstructorArgs.size();
523 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000524 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000525
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000526 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000527
Sebastian Redlf53597f2009-03-15 17:47:39 +0000528 PlacementArgs.release();
529 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000530 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000531 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000532 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000533 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000534 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000535}
536
537/// CheckAllocatedType - Checks that a type is suitable as the allocated type
538/// in a new-expression.
539/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000540bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000541 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000542 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
543 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000544 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000545 return Diag(Loc, diag::err_bad_new_type)
546 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000547 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000548 return Diag(Loc, diag::err_bad_new_type)
549 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000550 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000551 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000552 PDiag(diag::err_new_incomplete_type)
553 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000554 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000555 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000556 diag::err_allocation_of_abstract_type))
557 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000558
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000559 return false;
560}
561
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000562/// FindAllocationFunctions - Finds the overloads of operator new and delete
563/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000564bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
565 bool UseGlobal, QualType AllocType,
566 bool IsArray, Expr **PlaceArgs,
567 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000568 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000569 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 // --- Choosing an allocation function ---
571 // C++ 5.3.4p8 - 14 & 18
572 // 1) If UseGlobal is true, only look in the global scope. Else, also look
573 // in the scope of the allocated class.
574 // 2) If an array size is given, look for operator new[], else look for
575 // operator new.
576 // 3) The first argument is always size_t. Append the arguments from the
577 // placement form.
578 // FIXME: Also find the appropriate delete operator.
579
580 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
581 // We don't care about the actual value of this argument.
582 // FIXME: Should the Sema create the expression and embed it in the syntax
583 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000584 IntegerLiteral Size(llvm::APInt::getNullValue(
585 Context.Target.getPointerWidth(0)),
586 Context.getSizeType(),
587 SourceLocation());
588 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000589 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
590
591 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
592 IsArray ? OO_Array_New : OO_New);
593 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000594 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000595 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000596 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000597 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000598 AllocArgs.size(), Record, /*AllowMissing=*/true,
599 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000600 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000601 }
602 if (!OperatorNew) {
603 // Didn't find a member overload. Look for a global one.
604 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000605 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000606 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
608 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000609 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000610 }
611
Anders Carlssond9583892009-05-31 20:26:12 +0000612 // FindAllocationOverload can change the passed in arguments, so we need to
613 // copy them back.
614 if (NumPlaceArgs > 0)
615 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000617 return false;
618}
619
Sebastian Redl7f662392008-12-04 22:20:51 +0000620/// FindAllocationOverload - Find an fitting overload for the allocation
621/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000622bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
623 DeclarationName Name, Expr** Args,
624 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000625 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000626 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
627 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000628 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000629 if (AllowMissing)
630 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000631 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000632 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000633 }
634
John McCallf36e02d2009-10-09 21:13:30 +0000635 // FIXME: handle ambiguity
636
Sebastian Redl7f662392008-12-04 22:20:51 +0000637 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000638 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
639 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000640 // Even member operator new/delete are implicitly treated as
641 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000642 if (FunctionDecl *Fn =
643 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000644 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
645 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000646 continue;
647 }
648
649 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000650 }
651
652 // Do the resolution.
653 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000654 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000655 case OR_Success: {
656 // Got one!
657 FunctionDecl *FnDecl = Best->Function;
658 // The first argument is size_t, and the first parameter must be size_t,
659 // too. This is checked on declaration and can be assumed. (It can't be
660 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000661 // Whatch out for variadic allocator function.
662 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
663 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000664 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000665 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000666 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000667 return true;
668 }
669 Operator = FnDecl;
670 return false;
671 }
672
673 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000674 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000675 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000676 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000677 return true;
678
679 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000680 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000681 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000682 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000683 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000684
685 case OR_Deleted:
686 Diag(StartLoc, diag::err_ovl_deleted_call)
687 << Best->Function->isDeleted()
688 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000689 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000690 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000691 }
692 assert(false && "Unreachable, bad result from BestViableFunction");
693 return true;
694}
695
696
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000697/// DeclareGlobalNewDelete - Declare the global forms of operator new and
698/// delete. These are:
699/// @code
700/// void* operator new(std::size_t) throw(std::bad_alloc);
701/// void* operator new[](std::size_t) throw(std::bad_alloc);
702/// void operator delete(void *) throw();
703/// void operator delete[](void *) throw();
704/// @endcode
705/// Note that the placement and nothrow forms of new are *not* implicitly
706/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000707void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000708 if (GlobalNewDeleteDeclared)
709 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000710
711 // C++ [basic.std.dynamic]p2:
712 // [...] The following allocation and deallocation functions (18.4) are
713 // implicitly declared in global scope in each translation unit of a
714 // program
715 //
716 // void* operator new(std::size_t) throw(std::bad_alloc);
717 // void* operator new[](std::size_t) throw(std::bad_alloc);
718 // void operator delete(void*) throw();
719 // void operator delete[](void*) throw();
720 //
721 // These implicit declarations introduce only the function names operator
722 // new, operator new[], operator delete, operator delete[].
723 //
724 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
725 // "std" or "bad_alloc" as necessary to form the exception specification.
726 // However, we do not make these implicit declarations visible to name
727 // lookup.
728 if (!StdNamespace) {
729 // The "std" namespace has not yet been defined, so build one implicitly.
730 StdNamespace = NamespaceDecl::Create(Context,
731 Context.getTranslationUnitDecl(),
732 SourceLocation(),
733 &PP.getIdentifierTable().get("std"));
734 StdNamespace->setImplicit(true);
735 }
736
737 if (!StdBadAlloc) {
738 // The "std::bad_alloc" class has not yet been declared, so build it
739 // implicitly.
740 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
741 StdNamespace,
742 SourceLocation(),
743 &PP.getIdentifierTable().get("bad_alloc"),
744 SourceLocation(), 0);
745 StdBadAlloc->setImplicit(true);
746 }
747
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000748 GlobalNewDeleteDeclared = true;
749
750 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
751 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000752 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000753
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000754 DeclareGlobalAllocationFunction(
755 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000756 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000757 DeclareGlobalAllocationFunction(
758 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000759 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000760 DeclareGlobalAllocationFunction(
761 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
762 Context.VoidTy, VoidPtr);
763 DeclareGlobalAllocationFunction(
764 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
765 Context.VoidTy, VoidPtr);
766}
767
768/// DeclareGlobalAllocationFunction - Declares a single implicit global
769/// allocation function if it doesn't already exist.
770void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000771 QualType Return, QualType Argument,
772 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000773 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
774
775 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000776 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000777 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000778 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000779 Alloc != AllocEnd; ++Alloc) {
780 // FIXME: Do we need to check for default arguments here?
781 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
782 if (Func->getNumParams() == 1 &&
Douglas Gregor6e790ab2009-12-22 23:42:49 +0000783 Context.getCanonicalType(
784 Func->getParamDecl(0)->getType().getUnqualifiedType()) == Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000785 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000786 }
787 }
788
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000789 QualType BadAllocType;
790 bool HasBadAllocExceptionSpec
791 = (Name.getCXXOverloadedOperator() == OO_New ||
792 Name.getCXXOverloadedOperator() == OO_Array_New);
793 if (HasBadAllocExceptionSpec) {
794 assert(StdBadAlloc && "Must have std::bad_alloc declared");
795 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
796 }
797
798 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
799 true, false,
800 HasBadAllocExceptionSpec? 1 : 0,
801 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000802 FunctionDecl *Alloc =
803 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000804 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000805 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000806
807 if (AddMallocAttr)
808 Alloc->addAttr(::new (Context) MallocAttr());
809
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000810 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000811 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000812 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000813 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000814
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000815 // FIXME: Also add this declaration to the IdentifierResolver, but
816 // make sure it is at the end of the chain to coincide with the
817 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000818 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000819}
820
Anders Carlsson78f74552009-11-15 18:45:20 +0000821bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
822 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000823 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000824 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000825 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000826 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000827
John McCalla24dc2e2009-11-17 02:14:36 +0000828 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000829 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000830
831 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
832 F != FEnd; ++F) {
833 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
834 if (Delete->isUsualDeallocationFunction()) {
835 Operator = Delete;
836 return false;
837 }
838 }
839
840 // We did find operator delete/operator delete[] declarations, but
841 // none of them were suitable.
842 if (!Found.empty()) {
843 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
844 << Name << RD;
845
846 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
847 F != FEnd; ++F) {
848 Diag((*F)->getLocation(),
849 diag::note_delete_member_function_declared_here)
850 << Name;
851 }
852
853 return true;
854 }
855
856 // Look for a global declaration.
857 DeclareGlobalNewDelete();
858 DeclContext *TUDecl = Context.getTranslationUnitDecl();
859
860 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
861 Expr* DeallocArgs[1];
862 DeallocArgs[0] = &Null;
863 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
864 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
865 Operator))
866 return true;
867
868 assert(Operator && "Did not find a deallocation function!");
869 return false;
870}
871
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000872/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
873/// @code ::delete ptr; @endcode
874/// or
875/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000876Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000877Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000878 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000879 // C++ [expr.delete]p1:
880 // The operand shall have a pointer type, or a class type having a single
881 // conversion function to a pointer type. The result has type void.
882 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000883 // DR599 amends "pointer type" to "pointer to object type" in both cases.
884
Anders Carlssond67c4c32009-08-16 20:29:29 +0000885 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000888 if (!Ex->isTypeDependent()) {
889 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000890
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000891 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000892 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000893 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000894 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000895
John McCallba135432009-11-21 08:51:07 +0000896 for (UnresolvedSet::iterator I = Conversions->begin(),
897 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000898 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000899 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000900 continue;
901
John McCallba135432009-11-21 08:51:07 +0000902 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000903
904 QualType ConvType = Conv->getConversionType().getNonReferenceType();
905 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
906 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000907 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000908 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000909 if (ObjectPtrConversions.size() == 1) {
910 // We have a single conversion to a pointer-to-object type. Perform
911 // that conversion.
912 Operand.release();
913 if (!PerformImplicitConversion(Ex,
914 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000915 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000916 Operand = Owned(Ex);
917 Type = Ex->getType();
918 }
919 }
920 else if (ObjectPtrConversions.size() > 1) {
921 Diag(StartLoc, diag::err_ambiguous_delete_operand)
922 << Type << Ex->getSourceRange();
923 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
924 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +0000925 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000926 }
927 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000928 }
Sebastian Redl28507842009-02-26 14:39:58 +0000929 }
930
Sebastian Redlf53597f2009-03-15 17:47:39 +0000931 if (!Type->isPointerType())
932 return ExprError(Diag(StartLoc, diag::err_delete_operand)
933 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000934
Ted Kremenek6217b802009-07-29 21:53:49 +0000935 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000936 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000937 return ExprError(Diag(StartLoc, diag::err_delete_operand)
938 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000939 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000940 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000941 PDiag(diag::warn_delete_incomplete)
942 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000943 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000944
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000945 // C++ [expr.delete]p2:
946 // [Note: a pointer to a const type can be the operand of a
947 // delete-expression; it is not necessary to cast away the constness
948 // (5.2.11) of the pointer expression before it is used as the operand
949 // of the delete-expression. ]
950 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
951 CastExpr::CK_NoOp);
952
953 // Update the operand.
954 Operand.take();
955 Operand = ExprArg(*this, Ex);
956
Anders Carlssond67c4c32009-08-16 20:29:29 +0000957 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
958 ArrayForm ? OO_Array_Delete : OO_Delete);
959
Anders Carlsson78f74552009-11-15 18:45:20 +0000960 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
961 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
962
963 if (!UseGlobal &&
964 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000965 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000966
Anders Carlsson78f74552009-11-15 18:45:20 +0000967 if (!RD->hasTrivialDestructor())
968 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000969 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000970 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000971 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000972
Anders Carlssond67c4c32009-08-16 20:29:29 +0000973 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000974 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000975 DeclareGlobalNewDelete();
976 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000977 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000978 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000979 OperatorDelete))
980 return ExprError();
981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Sebastian Redl28507842009-02-26 14:39:58 +0000983 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000984 }
985
Sebastian Redlf53597f2009-03-15 17:47:39 +0000986 Operand.release();
987 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000988 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000989}
990
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000991/// \brief Check the use of the given variable as a C++ condition in an if,
992/// while, do-while, or switch statement.
993Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
994 QualType T = ConditionVar->getType();
995
996 // C++ [stmt.select]p2:
997 // The declarator shall not specify a function or an array.
998 if (T->isFunctionType())
999 return ExprError(Diag(ConditionVar->getLocation(),
1000 diag::err_invalid_use_of_function_type)
1001 << ConditionVar->getSourceRange());
1002 else if (T->isArrayType())
1003 return ExprError(Diag(ConditionVar->getLocation(),
1004 diag::err_invalid_use_of_array_type)
1005 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001006
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001007 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1008 ConditionVar->getLocation(),
1009 ConditionVar->getType().getNonReferenceType()));
1010}
1011
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001012/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1013bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1014 // C++ 6.4p4:
1015 // The value of a condition that is an initialized declaration in a statement
1016 // other than a switch statement is the value of the declared variable
1017 // implicitly converted to type bool. If that conversion is ill-formed, the
1018 // program is ill-formed.
1019 // The value of a condition that is an expression is the value of the
1020 // expression, implicitly converted to bool.
1021 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001022 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001023}
Douglas Gregor77a52232008-09-12 00:47:35 +00001024
1025/// Helper function to determine whether this is the (deprecated) C++
1026/// conversion from a string literal to a pointer to non-const char or
1027/// non-const wchar_t (for narrow and wide string literals,
1028/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001029bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001030Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1031 // Look inside the implicit cast, if it exists.
1032 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1033 From = Cast->getSubExpr();
1034
1035 // A string literal (2.13.4) that is not a wide string literal can
1036 // be converted to an rvalue of type "pointer to char"; a wide
1037 // string literal can be converted to an rvalue of type "pointer
1038 // to wchar_t" (C++ 4.2p2).
1039 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001040 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001041 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001042 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001043 // This conversion is considered only when there is an
1044 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001045 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001046 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1047 (!StrLit->isWide() &&
1048 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1049 ToPointeeType->getKind() == BuiltinType::Char_S))))
1050 return true;
1051 }
1052
1053 return false;
1054}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001055
1056/// PerformImplicitConversion - Perform an implicit conversion of the
1057/// expression From to the type ToType. Returns true if there was an
1058/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001059/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001060/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001061/// explicit user-defined conversions are permitted. @p Elidable should be true
1062/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1063/// resolution works differently in that case.
1064bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001065Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001066 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001067 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001068 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001069 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001070 Elidable, ICS);
1071}
1072
1073bool
1074Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001075 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001076 bool Elidable,
1077 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001078 ICS.setBad();
Sebastian Redle2b68332009-04-12 17:16:29 +00001079 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001080 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001081 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001082 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001083 /*ForceRValue=*/true,
1084 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001085 }
John McCall1d318332010-01-12 00:44:57 +00001086 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001087 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001088 /*SuppressUserConversions=*/false,
1089 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001090 /*ForceRValue=*/false,
1091 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001092 }
Douglas Gregor68647482009-12-16 03:45:30 +00001093 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001094}
1095
1096/// PerformImplicitConversion - Perform an implicit conversion of the
1097/// expression From to the type ToType using the pre-computed implicit
1098/// conversion sequence ICS. Returns true if there was an error, false
1099/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001100/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001101/// used in the error message.
1102bool
1103Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1104 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001105 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001106 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001107 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001108 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001109 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001110 return true;
1111 break;
1112
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001113 case ImplicitConversionSequence::UserDefinedConversion: {
1114
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001115 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1116 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001117 QualType BeforeToType;
1118 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001119 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001120
1121 // If the user-defined conversion is specified by a conversion function,
1122 // the initial standard conversion sequence converts the source type to
1123 // the implicit object parameter of the conversion function.
1124 BeforeToType = Context.getTagDeclType(Conv->getParent());
1125 } else if (const CXXConstructorDecl *Ctor =
1126 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001127 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001128 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001129 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001130 // If the user-defined conversion is specified by a constructor, the
1131 // initial standard conversion sequence converts the source type to the
1132 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001133 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1134 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001135 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001136 else
1137 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001138 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001139 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001140 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001141 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001142 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001143 return true;
1144 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001145
Anders Carlsson0aebc812009-09-09 21:33:21 +00001146 OwningExprResult CastArg
1147 = BuildCXXCastArgument(From->getLocStart(),
1148 ToType.getNonReferenceType(),
1149 CastKind, cast<CXXMethodDecl>(FD),
1150 Owned(From));
1151
1152 if (CastArg.isInvalid())
1153 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001154
1155 From = CastArg.takeAs<Expr>();
1156
Eli Friedmand8889622009-11-27 04:41:50 +00001157 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001158 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001159 }
John McCall1d318332010-01-12 00:44:57 +00001160
1161 case ImplicitConversionSequence::AmbiguousConversion:
1162 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1163 PDiag(diag::err_typecheck_ambiguous_condition)
1164 << From->getSourceRange());
1165 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001166
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001167 case ImplicitConversionSequence::EllipsisConversion:
1168 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001169 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001170
1171 case ImplicitConversionSequence::BadConversion:
1172 return true;
1173 }
1174
1175 // Everything went well.
1176 return false;
1177}
1178
1179/// PerformImplicitConversion - Perform an implicit conversion of the
1180/// expression From to the type ToType by following the standard
1181/// conversion sequence SCS. Returns true if there was an error, false
1182/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001183/// expression. Flavor is the context in which we're performing this
1184/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001185bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001186Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001187 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001188 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001189 // Overall FIXME: we are recomputing too many types here and doing far too
1190 // much extra work. What this means is that we need to keep track of more
1191 // information that is computed when we try the implicit conversion initially,
1192 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001193 QualType FromType = From->getType();
1194
Douglas Gregor225c41e2008-11-03 19:09:14 +00001195 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001196 // FIXME: When can ToType be a reference type?
1197 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001198 if (SCS.Second == ICK_Derived_To_Base) {
1199 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1200 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1201 MultiExprArg(*this, (void **)&From, 1),
1202 /*FIXME:ConstructLoc*/SourceLocation(),
1203 ConstructorArgs))
1204 return true;
1205 OwningExprResult FromResult =
1206 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1207 ToType, SCS.CopyConstructor,
1208 move_arg(ConstructorArgs));
1209 if (FromResult.isInvalid())
1210 return true;
1211 From = FromResult.takeAs<Expr>();
1212 return false;
1213 }
Mike Stump1eb44332009-09-09 15:08:12 +00001214 OwningExprResult FromResult =
1215 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1216 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001217 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001219 if (FromResult.isInvalid())
1220 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001222 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001223 return false;
1224 }
1225
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001226 // Perform the first implicit conversion.
1227 switch (SCS.First) {
1228 case ICK_Identity:
1229 case ICK_Lvalue_To_Rvalue:
1230 // Nothing to do.
1231 break;
1232
1233 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001234 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001235 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001236 break;
1237
1238 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001239 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001240 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1241 if (!Fn)
1242 return true;
1243
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001244 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1245 return true;
1246
Anders Carlsson96ad5332009-10-21 17:16:23 +00001247 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001248 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001249
Sebastian Redl759986e2009-10-17 20:50:27 +00001250 // If there's already an address-of operator in the expression, we have
1251 // the right type already, and the code below would just introduce an
1252 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001253 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001254 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001255 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001256 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001257 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001258 break;
1259
1260 default:
1261 assert(false && "Improper first standard conversion");
1262 break;
1263 }
1264
1265 // Perform the second implicit conversion
1266 switch (SCS.Second) {
1267 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001268 // If both sides are functions (or pointers/references to them), there could
1269 // be incompatible exception declarations.
1270 if (CheckExceptionSpecCompatibility(From, ToType))
1271 return true;
1272 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001273 break;
1274
Douglas Gregor43c79c22009-12-09 00:47:37 +00001275 case ICK_NoReturn_Adjustment:
1276 // If both sides are functions (or pointers/references to them), there could
1277 // be incompatible exception declarations.
1278 if (CheckExceptionSpecCompatibility(From, ToType))
1279 return true;
1280
1281 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1282 CastExpr::CK_NoOp);
1283 break;
1284
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001285 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001286 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001287 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1288 break;
1289
1290 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001292 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1293 break;
1294
1295 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001296 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001297 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1298 break;
1299
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001300 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001301 if (ToType->isFloatingType())
1302 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1303 else
1304 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1305 break;
1306
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001307 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001308 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1309 break;
1310
Douglas Gregorf9201e02009-02-11 23:02:49 +00001311 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001312 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001313 break;
1314
Anders Carlsson61faec12009-09-12 04:46:44 +00001315 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001316 if (SCS.IncompatibleObjC) {
1317 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001318 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001319 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001320 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001321 << From->getSourceRange();
1322 }
1323
Anders Carlsson61faec12009-09-12 04:46:44 +00001324
1325 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001326 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001327 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001328 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001329 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001330 }
1331
1332 case ICK_Pointer_Member: {
1333 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001334 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001335 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001336 if (CheckExceptionSpecCompatibility(From, ToType))
1337 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001338 ImpCastExprToType(From, ToType, Kind);
1339 break;
1340 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001341 case ICK_Boolean_Conversion: {
1342 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1343 if (FromType->isMemberPointerType())
1344 Kind = CastExpr::CK_MemberPointerToBoolean;
1345
1346 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001347 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001348 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001349
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001350 case ICK_Derived_To_Base:
1351 if (CheckDerivedToBaseConversion(From->getType(),
1352 ToType.getNonReferenceType(),
1353 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001354 From->getSourceRange(),
1355 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001356 return true;
1357 ImpCastExprToType(From, ToType.getNonReferenceType(),
1358 CastExpr::CK_DerivedToBase);
1359 break;
1360
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001361 default:
1362 assert(false && "Improper second standard conversion");
1363 break;
1364 }
1365
1366 switch (SCS.Third) {
1367 case ICK_Identity:
1368 // Nothing to do.
1369 break;
1370
1371 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001372 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1373 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001374 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001375 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001376 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001377 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001378
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001379 default:
1380 assert(false && "Improper second standard conversion");
1381 break;
1382 }
1383
1384 return false;
1385}
1386
Sebastian Redl64b45f72009-01-05 20:52:13 +00001387Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1388 SourceLocation KWLoc,
1389 SourceLocation LParen,
1390 TypeTy *Ty,
1391 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001392 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001394 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1395 // all traits except __is_class, __is_enum and __is_union require a the type
1396 // to be complete.
1397 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001398 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001399 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001400 return ExprError();
1401 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001402
1403 // There is no point in eagerly computing the value. The traits are designed
1404 // to be used from type trait templates, so Ty will be a template parameter
1405 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001406 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1407 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001408}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001409
1410QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001411 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001412 const char *OpSpelling = isIndirect ? "->*" : ".*";
1413 // C++ 5.5p2
1414 // The binary operator .* [p3: ->*] binds its second operand, which shall
1415 // be of type "pointer to member of T" (where T is a completely-defined
1416 // class type) [...]
1417 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001418 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001419 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001420 Diag(Loc, diag::err_bad_memptr_rhs)
1421 << OpSpelling << RType << rex->getSourceRange();
1422 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001423 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001424
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001425 QualType Class(MemPtr->getClass(), 0);
1426
1427 // C++ 5.5p2
1428 // [...] to its first operand, which shall be of class T or of a class of
1429 // which T is an unambiguous and accessible base class. [p3: a pointer to
1430 // such a class]
1431 QualType LType = lex->getType();
1432 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001433 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001434 LType = Ptr->getPointeeType().getNonReferenceType();
1435 else {
1436 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001437 << OpSpelling << 1 << LType
1438 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001439 return QualType();
1440 }
1441 }
1442
Douglas Gregora4923eb2009-11-16 21:35:15 +00001443 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001444 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1445 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001446 // FIXME: Would it be useful to print full ambiguity paths, or is that
1447 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001448 if (!IsDerivedFrom(LType, Class, Paths) ||
1449 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001450 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001451 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001452 << (int)isIndirect << lex->getType() <<
1453 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001454 return QualType();
1455 }
1456 }
1457
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001458 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001459 // Diagnose use of pointer-to-member type which when used as
1460 // the functional cast in a pointer-to-member expression.
1461 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1462 return QualType();
1463 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001464 // C++ 5.5p2
1465 // The result is an object or a function of the type specified by the
1466 // second operand.
1467 // The cv qualifiers are the union of those in the pointer and the left side,
1468 // in accordance with 5.5p5 and 5.2.5.
1469 // FIXME: This returns a dereferenced member function pointer as a normal
1470 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001471 // calling them. There's also a GCC extension to get a function pointer to the
1472 // thing, which is another complication, because this type - unlike the type
1473 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001474 // argument.
1475 // We probably need a "MemberFunctionClosureType" or something like that.
1476 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001477 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001478 return Result;
1479}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001480
1481/// \brief Get the target type of a standard or user-defined conversion.
1482static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001483 switch (ICS.getKind()) {
1484 case ImplicitConversionSequence::StandardConversion:
1485 return ICS.Standard.getToType();
1486 case ImplicitConversionSequence::UserDefinedConversion:
1487 return ICS.UserDefined.After.getToType();
1488 case ImplicitConversionSequence::AmbiguousConversion:
1489 return ICS.Ambiguous.getToType();
1490 case ImplicitConversionSequence::EllipsisConversion:
1491 case ImplicitConversionSequence::BadConversion:
1492 llvm_unreachable("function not valid for ellipsis or bad conversions");
1493 }
1494 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001495}
1496
1497/// \brief Try to convert a type to another according to C++0x 5.16p3.
1498///
1499/// This is part of the parameter validation for the ? operator. If either
1500/// value operand is a class type, the two operands are attempted to be
1501/// converted to each other. This function does the conversion in one direction.
1502/// It emits a diagnostic and returns true only if it finds an ambiguous
1503/// conversion.
1504static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1505 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001506 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001507 // C++0x 5.16p3
1508 // The process for determining whether an operand expression E1 of type T1
1509 // can be converted to match an operand expression E2 of type T2 is defined
1510 // as follows:
1511 // -- If E2 is an lvalue:
1512 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1513 // E1 can be converted to match E2 if E1 can be implicitly converted to
1514 // type "lvalue reference to T2", subject to the constraint that in the
1515 // conversion the reference must bind directly to E1.
1516 if (!Self.CheckReferenceInit(From,
1517 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001518 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001519 /*SuppressUserConversions=*/false,
1520 /*AllowExplicit=*/false,
1521 /*ForceRValue=*/false,
1522 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001523 {
John McCall1d318332010-01-12 00:44:57 +00001524 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001525 "expected a definite conversion");
1526 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001527 ICS.isStandard() ? ICS.Standard.DirectBinding
1528 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001529 if (DirectBinding)
1530 return false;
1531 }
1532 }
John McCall1d318332010-01-12 00:44:57 +00001533 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001534 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1535 // -- if E1 and E2 have class type, and the underlying class types are
1536 // the same or one is a base class of the other:
1537 QualType FTy = From->getType();
1538 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001539 const RecordType *FRec = FTy->getAs<RecordType>();
1540 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001541 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1542 if (FRec && TRec && (FRec == TRec ||
1543 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1544 // E1 can be converted to match E2 if the class of T2 is the
1545 // same type as, or a base class of, the class of T1, and
1546 // [cv2 > cv1].
1547 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1548 // Could still fail if there's no copy constructor.
1549 // FIXME: Is this a hard error then, or just a conversion failure? The
1550 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001551 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001552 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001553 /*ForceRValue=*/false,
1554 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001555 }
1556 } else {
1557 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1558 // implicitly converted to the type that expression E2 would have
1559 // if E2 were converted to an rvalue.
1560 // First find the decayed type.
1561 if (TTy->isFunctionType())
1562 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001563 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001564 TTy = Self.Context.getArrayDecayedType(TTy);
1565
1566 // Now try the implicit conversion.
1567 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001568 ICS = Self.TryImplicitConversion(From, TTy,
1569 /*SuppressUserConversions=*/false,
1570 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001571 /*ForceRValue=*/false,
1572 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001573 }
1574 return false;
1575}
1576
1577/// \brief Try to find a common type for two according to C++0x 5.16p5.
1578///
1579/// This is part of the parameter validation for the ? operator. If either
1580/// value operand is a class type, overload resolution is used to find a
1581/// conversion to a common type.
1582static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1583 SourceLocation Loc) {
1584 Expr *Args[2] = { LHS, RHS };
1585 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001586 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001587
1588 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001589 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001590 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001591 // We found a match. Perform the conversions on the arguments and move on.
1592 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001593 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001594 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001595 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001596 break;
1597 return false;
1598
Douglas Gregor20093b42009-12-09 23:02:17 +00001599 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001600 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1601 << LHS->getType() << RHS->getType()
1602 << LHS->getSourceRange() << RHS->getSourceRange();
1603 return true;
1604
Douglas Gregor20093b42009-12-09 23:02:17 +00001605 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001606 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1607 << LHS->getType() << RHS->getType()
1608 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001609 // FIXME: Print the possible common types by printing the return types of
1610 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001611 break;
1612
Douglas Gregor20093b42009-12-09 23:02:17 +00001613 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001614 assert(false && "Conditional operator has only built-in overloads");
1615 break;
1616 }
1617 return true;
1618}
1619
Sebastian Redl76458502009-04-17 16:30:52 +00001620/// \brief Perform an "extended" implicit conversion as returned by
1621/// TryClassUnification.
1622///
1623/// TryClassUnification generates ICSs that include reference bindings.
1624/// PerformImplicitConversion is not suitable for this; it chokes if the
1625/// second part of a standard conversion is ICK_DerivedToBase. This function
1626/// handles the reference binding specially.
1627static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001628 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001629 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001630 assert(ICS.Standard.DirectBinding &&
1631 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001632 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1633 // redoing all the work.
1634 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001635 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001636 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001637 /*SuppressUserConversions=*/false,
1638 /*AllowExplicit=*/false,
1639 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001640 }
John McCall1d318332010-01-12 00:44:57 +00001641 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001642 assert(ICS.UserDefined.After.DirectBinding &&
1643 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001644 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001645 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001646 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001647 /*SuppressUserConversions=*/false,
1648 /*AllowExplicit=*/false,
1649 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001650 }
Douglas Gregor68647482009-12-16 03:45:30 +00001651 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001652 return true;
1653 return false;
1654}
1655
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001656/// \brief Check the operands of ?: under C++ semantics.
1657///
1658/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1659/// extension. In this case, LHS == Cond. (But they're not aliases.)
1660QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1661 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001662 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1663 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001664
1665 // C++0x 5.16p1
1666 // The first expression is contextually converted to bool.
1667 if (!Cond->isTypeDependent()) {
1668 if (CheckCXXBooleanCondition(Cond))
1669 return QualType();
1670 }
1671
1672 // Either of the arguments dependent?
1673 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1674 return Context.DependentTy;
1675
John McCallb13c87f2009-11-05 09:23:39 +00001676 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1677
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001678 // C++0x 5.16p2
1679 // If either the second or the third operand has type (cv) void, ...
1680 QualType LTy = LHS->getType();
1681 QualType RTy = RHS->getType();
1682 bool LVoid = LTy->isVoidType();
1683 bool RVoid = RTy->isVoidType();
1684 if (LVoid || RVoid) {
1685 // ... then the [l2r] conversions are performed on the second and third
1686 // operands ...
1687 DefaultFunctionArrayConversion(LHS);
1688 DefaultFunctionArrayConversion(RHS);
1689 LTy = LHS->getType();
1690 RTy = RHS->getType();
1691
1692 // ... and one of the following shall hold:
1693 // -- The second or the third operand (but not both) is a throw-
1694 // expression; the result is of the type of the other and is an rvalue.
1695 bool LThrow = isa<CXXThrowExpr>(LHS);
1696 bool RThrow = isa<CXXThrowExpr>(RHS);
1697 if (LThrow && !RThrow)
1698 return RTy;
1699 if (RThrow && !LThrow)
1700 return LTy;
1701
1702 // -- Both the second and third operands have type void; the result is of
1703 // type void and is an rvalue.
1704 if (LVoid && RVoid)
1705 return Context.VoidTy;
1706
1707 // Neither holds, error.
1708 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1709 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1710 << LHS->getSourceRange() << RHS->getSourceRange();
1711 return QualType();
1712 }
1713
1714 // Neither is void.
1715
1716 // C++0x 5.16p3
1717 // Otherwise, if the second and third operand have different types, and
1718 // either has (cv) class type, and attempt is made to convert each of those
1719 // operands to the other.
1720 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1721 (LTy->isRecordType() || RTy->isRecordType())) {
1722 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1723 // These return true if a single direction is already ambiguous.
1724 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1725 return QualType();
1726 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1727 return QualType();
1728
John McCall1d318332010-01-12 00:44:57 +00001729 bool HaveL2R = !ICSLeftToRight.isBad();
1730 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001731 // If both can be converted, [...] the program is ill-formed.
1732 if (HaveL2R && HaveR2L) {
1733 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1734 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1735 return QualType();
1736 }
1737
1738 // If exactly one conversion is possible, that conversion is applied to
1739 // the chosen operand and the converted operands are used in place of the
1740 // original operands for the remainder of this section.
1741 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001742 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001743 return QualType();
1744 LTy = LHS->getType();
1745 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001746 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001747 return QualType();
1748 RTy = RHS->getType();
1749 }
1750 }
1751
1752 // C++0x 5.16p4
1753 // If the second and third operands are lvalues and have the same type,
1754 // the result is of that type [...]
1755 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1756 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1757 RHS->isLvalue(Context) == Expr::LV_Valid)
1758 return LTy;
1759
1760 // C++0x 5.16p5
1761 // Otherwise, the result is an rvalue. If the second and third operands
1762 // do not have the same type, and either has (cv) class type, ...
1763 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1764 // ... overload resolution is used to determine the conversions (if any)
1765 // to be applied to the operands. If the overload resolution fails, the
1766 // program is ill-formed.
1767 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1768 return QualType();
1769 }
1770
1771 // C++0x 5.16p6
1772 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1773 // conversions are performed on the second and third operands.
1774 DefaultFunctionArrayConversion(LHS);
1775 DefaultFunctionArrayConversion(RHS);
1776 LTy = LHS->getType();
1777 RTy = RHS->getType();
1778
1779 // After those conversions, one of the following shall hold:
1780 // -- The second and third operands have the same type; the result
1781 // is of that type.
1782 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1783 return LTy;
1784
1785 // -- The second and third operands have arithmetic or enumeration type;
1786 // the usual arithmetic conversions are performed to bring them to a
1787 // common type, and the result is of that type.
1788 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1789 UsualArithmeticConversions(LHS, RHS);
1790 return LHS->getType();
1791 }
1792
1793 // -- The second and third operands have pointer type, or one has pointer
1794 // type and the other is a null pointer constant; pointer conversions
1795 // and qualification conversions are performed to bring them to their
1796 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00001797 // -- The second and third operands have pointer to member type, or one has
1798 // pointer to member type and the other is a null pointer constant;
1799 // pointer to member conversions and qualification conversions are
1800 // performed to bring them to a common type, whose cv-qualification
1801 // shall match the cv-qualification of either the second or the third
1802 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001803 QualType Composite = FindCompositePointerType(LHS, RHS);
1804 if (!Composite.isNull())
1805 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001806
1807 // Similarly, attempt to find composite type of twp objective-c pointers.
1808 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1809 if (!Composite.isNull())
1810 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001811
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001812 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1813 << LHS->getType() << RHS->getType()
1814 << LHS->getSourceRange() << RHS->getSourceRange();
1815 return QualType();
1816}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001817
1818/// \brief Find a merged pointer type and convert the two expressions to it.
1819///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001820/// This finds the composite pointer type (or member pointer type) for @p E1
1821/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1822/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001823/// It does not emit diagnostics.
1824QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1825 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1826 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001828 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1829 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001830 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001831
1832 // C++0x 5.9p2
1833 // Pointer conversions and qualification conversions are performed on
1834 // pointer operands to bring them to their composite pointer type. If
1835 // one operand is a null pointer constant, the composite pointer type is
1836 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001837 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001838 if (T2->isMemberPointerType())
1839 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1840 else
1841 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001842 return T2;
1843 }
Douglas Gregorce940492009-09-25 04:25:58 +00001844 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001845 if (T1->isMemberPointerType())
1846 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1847 else
1848 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001849 return T1;
1850 }
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Douglas Gregor20b3e992009-08-24 17:42:35 +00001852 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001853 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1854 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001855 return QualType();
1856
1857 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1858 // the other has type "pointer to cv2 T" and the composite pointer type is
1859 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1860 // Otherwise, the composite pointer type is a pointer type similar to the
1861 // type of one of the operands, with a cv-qualification signature that is
1862 // the union of the cv-qualification signatures of the operand types.
1863 // In practice, the first part here is redundant; it's subsumed by the second.
1864 // What we do here is, we build the two possible composite types, and try the
1865 // conversions in both directions. If only one works, or if the two composite
1866 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001867 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001868 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1869 QualifierVector QualifierUnion;
1870 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1871 ContainingClassVector;
1872 ContainingClassVector MemberOfClass;
1873 QualType Composite1 = Context.getCanonicalType(T1),
1874 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001875 do {
1876 const PointerType *Ptr1, *Ptr2;
1877 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1878 (Ptr2 = Composite2->getAs<PointerType>())) {
1879 Composite1 = Ptr1->getPointeeType();
1880 Composite2 = Ptr2->getPointeeType();
1881 QualifierUnion.push_back(
1882 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1883 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1884 continue;
1885 }
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Douglas Gregor20b3e992009-08-24 17:42:35 +00001887 const MemberPointerType *MemPtr1, *MemPtr2;
1888 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1889 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1890 Composite1 = MemPtr1->getPointeeType();
1891 Composite2 = MemPtr2->getPointeeType();
1892 QualifierUnion.push_back(
1893 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1894 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1895 MemPtr2->getClass()));
1896 continue;
1897 }
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Douglas Gregor20b3e992009-08-24 17:42:35 +00001899 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Douglas Gregor20b3e992009-08-24 17:42:35 +00001901 // Cannot unwrap any more types.
1902 break;
1903 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregor20b3e992009-08-24 17:42:35 +00001905 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001906 ContainingClassVector::reverse_iterator MOC
1907 = MemberOfClass.rbegin();
1908 for (QualifierVector::reverse_iterator
1909 I = QualifierUnion.rbegin(),
1910 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001911 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001912 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001913 if (MOC->first && MOC->second) {
1914 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001915 Composite1 = Context.getMemberPointerType(
1916 Context.getQualifiedType(Composite1, Quals),
1917 MOC->first);
1918 Composite2 = Context.getMemberPointerType(
1919 Context.getQualifiedType(Composite2, Quals),
1920 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001921 } else {
1922 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001923 Composite1
1924 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1925 Composite2
1926 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001927 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001928 }
1929
Mike Stump1eb44332009-09-09 15:08:12 +00001930 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001931 TryImplicitConversion(E1, Composite1,
1932 /*SuppressUserConversions=*/false,
1933 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001934 /*ForceRValue=*/false,
1935 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001936 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001937 TryImplicitConversion(E2, Composite1,
1938 /*SuppressUserConversions=*/false,
1939 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001940 /*ForceRValue=*/false,
1941 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001943 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00001944 E1ToC2.setBad();
1945 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001946 if (Context.getCanonicalType(Composite1) !=
1947 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001948 E1ToC2 = TryImplicitConversion(E1, Composite2,
1949 /*SuppressUserConversions=*/false,
1950 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001951 /*ForceRValue=*/false,
1952 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001953 E2ToC2 = TryImplicitConversion(E2, Composite2,
1954 /*SuppressUserConversions=*/false,
1955 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001956 /*ForceRValue=*/false,
1957 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001958 }
1959
John McCall1d318332010-01-12 00:44:57 +00001960 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
1961 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001962 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001963 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
1964 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001965 return Composite1;
1966 }
1967 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00001968 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
1969 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001970 return Composite2;
1971 }
1972 return QualType();
1973}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001974
Anders Carlssondef11992009-05-30 20:36:53 +00001975Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001976 if (!Context.getLangOptions().CPlusPlus)
1977 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor51326552009-12-24 18:51:59 +00001979 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
1980
Ted Kremenek6217b802009-07-29 21:53:49 +00001981 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001982 if (!RT)
1983 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Anders Carlssondef11992009-05-30 20:36:53 +00001985 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1986 if (RD->hasTrivialDestructor())
1987 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Anders Carlsson283e4d52009-09-14 01:30:44 +00001989 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1990 QualType Ty = CE->getCallee()->getType();
1991 if (const PointerType *PT = Ty->getAs<PointerType>())
1992 Ty = PT->getPointeeType();
1993
John McCall183700f2009-09-21 23:43:11 +00001994 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001995 if (FTy->getResultType()->isReferenceType())
1996 return Owned(E);
1997 }
Mike Stump1eb44332009-09-09 15:08:12 +00001998 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001999 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002000 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002001 if (CXXDestructorDecl *Destructor =
2002 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2003 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002004 // FIXME: Add the temporary to the temporaries vector.
2005 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2006}
2007
Anders Carlsson0ece4912009-12-15 20:51:39 +00002008Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002009 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002011 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2012 assert(ExprTemporaries.size() >= FirstTemporary);
2013 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002014 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002016 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002017 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002018 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002019 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2020 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002022 return E;
2023}
2024
Douglas Gregor90f93822009-12-22 22:17:25 +00002025Sema::OwningExprResult
2026Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2027 if (SubExpr.isInvalid())
2028 return ExprError();
2029
2030 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2031}
2032
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002033FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2034 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2035 assert(ExprTemporaries.size() >= FirstTemporary);
2036
2037 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2038 CXXTemporary **Temporaries =
2039 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2040
2041 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2042
2043 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2044 ExprTemporaries.end());
2045
2046 return E;
2047}
2048
Mike Stump1eb44332009-09-09 15:08:12 +00002049Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002050Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2051 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2052 // Since this might be a postfix expression, get rid of ParenListExprs.
2053 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002055 Expr *BaseExpr = (Expr*)Base.get();
2056 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002058 QualType BaseType = BaseExpr->getType();
2059 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002060 // If we have a pointer to a dependent type and are using the -> operator,
2061 // the object type is the type that the pointer points to. We might still
2062 // have enough information about that type to do something useful.
2063 if (OpKind == tok::arrow)
2064 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2065 BaseType = Ptr->getPointeeType();
2066
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002067 ObjectType = BaseType.getAsOpaquePtr();
2068 return move(Base);
2069 }
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002071 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002072 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002073 // returned, with the original second operand.
2074 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002075 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002076 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002077 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002078 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002079
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002080 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002081 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002082 BaseExpr = (Expr*)Base.get();
2083 if (BaseExpr == NULL)
2084 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002085 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002086 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002087 BaseType = BaseExpr->getType();
2088 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002089 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002090 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002091 for (unsigned i = 0; i < Locations.size(); i++)
2092 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002093 return ExprError();
2094 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002095 }
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Douglas Gregor31658df2009-11-20 19:58:21 +00002097 if (BaseType->isPointerType())
2098 BaseType = BaseType->getPointeeType();
2099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
2101 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002102 // vector types or Objective-C interfaces. Just return early and let
2103 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002104 if (!BaseType->isRecordType()) {
2105 // C++ [basic.lookup.classref]p2:
2106 // [...] If the type of the object expression is of pointer to scalar
2107 // type, the unqualified-id is looked up in the context of the complete
2108 // postfix-expression.
2109 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002110 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Douglas Gregor03c57052009-11-17 05:17:33 +00002113 // The object type must be complete (or dependent).
2114 if (!BaseType->isDependentType() &&
2115 RequireCompleteType(OpLoc, BaseType,
2116 PDiag(diag::err_incomplete_member_access)))
2117 return ExprError();
2118
Douglas Gregorc68afe22009-09-03 21:38:09 +00002119 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002120 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002121 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002122 // type C (or of pointer to a class type C), the unqualified-id is looked
2123 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002124 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002125
Mike Stump1eb44332009-09-09 15:08:12 +00002126 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002127}
2128
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002129CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2130 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002131 if (PerformObjectArgumentInitialization(Exp, Method))
2132 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2133
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002134 MemberExpr *ME =
2135 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2136 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002137 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002138 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2139 CXXMemberCallExpr *CE =
2140 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2141 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002142 return CE;
2143}
2144
Anders Carlsson0aebc812009-09-09 21:33:21 +00002145Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2146 QualType Ty,
2147 CastExpr::CastKind Kind,
2148 CXXMethodDecl *Method,
2149 ExprArg Arg) {
2150 Expr *From = Arg.takeAs<Expr>();
2151
2152 switch (Kind) {
2153 default: assert(0 && "Unhandled cast kind!");
2154 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002155 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2156
2157 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2158 MultiExprArg(*this, (void **)&From, 1),
2159 CastLoc, ConstructorArgs))
2160 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002161
2162 OwningExprResult Result =
2163 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2164 move_arg(ConstructorArgs));
2165 if (Result.isInvalid())
2166 return ExprError();
2167
2168 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002169 }
2170
2171 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002172 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002173
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002174 // Create an implicit call expr that calls it.
2175 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002176 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002177 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002178 }
2179}
2180
Anders Carlsson165a0a02009-05-17 18:41:29 +00002181Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2182 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002183 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002184 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002185
Anders Carlsson165a0a02009-05-17 18:41:29 +00002186 return Owned(FullExpr);
2187}