blob: 942c6bc4fecc5fd511ce6418ec4aed9616073d53 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
Douglas Gregor487a75a2008-11-19 19:09:45 +000025/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000026/// name (e.g., operator void const *) as an expression. This is
27/// very similar to ActOnIdentifierExpr, except that instead of
28/// providing an identifier the parser provides the type of the
29/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000030Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000031Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000033 const CXXScopeSpec &SS,
34 bool isAddressOfOperand) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000035 //FIXME: Preserve type source info.
36 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregor50d62d12009-08-05 05:36:45 +000037 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Mike Stump1eb44332009-09-09 15:08:12 +000038 DeclarationName ConvName
Douglas Gregor2def4832008-11-17 20:34:05 +000039 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000040 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000041 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000042}
Sebastian Redlc42e1182008-11-11 11:37:55 +000043
Douglas Gregor487a75a2008-11-19 19:09:45 +000044/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000045/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000049Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000050Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51 OverloadedOperatorKind Op,
52 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000053 const CXXScopeSpec &SS,
54 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000056 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000057 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000058}
59
Sebastian Redlc42e1182008-11-11 11:37:55 +000060/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000061Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000062Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000064 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000065 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000066
67 if (isType)
68 // FIXME: Preserve type source info.
69 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
Chris Lattner572af492008-11-20 05:51:55 +000071 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCallf36e02d2009-10-09 21:13:30 +000072 LookupResult R;
73 LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
74 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000075 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000076 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000077 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000078
79 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
80
Douglas Gregorac7610d2009-06-22 20:57:11 +000081 if (!isType) {
82 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000083 // When typeid is applied to an expression other than an lvalue of a
84 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000085 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000086
Douglas Gregorac7610d2009-06-22 20:57:11 +000087 // FIXME: if the type of the expression is a class type, the class
88 // shall be completely defined.
89 bool isUnevaluatedOperand = true;
90 Expr *E = static_cast<Expr *>(TyOrExpr);
91 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
92 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000093 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000094 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
95 if (RecordD->isPolymorphic())
96 isUnevaluatedOperand = false;
97 }
98 }
Mike Stump1eb44332009-09-09 15:08:12 +000099
Douglas Gregorac7610d2009-06-22 20:57:11 +0000100 // If this is an unevaluated operand, clear out the set of declaration
101 // references we have been computing.
102 if (isUnevaluatedOperand)
103 PotentiallyReferencedDeclStack.back().clear();
104 }
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Sebastian Redlf53597f2009-03-15 17:47:39 +0000106 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
107 TypeInfoType.withConst(),
108 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000109}
110
Steve Naroff1b273c42007-09-16 14:56:35 +0000111/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000112Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000113Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000114 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000116 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
117 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
Chris Lattner50dd2892008-02-26 00:51:44 +0000119
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000120/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
121Action::OwningExprResult
122Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
123 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
124}
125
Chris Lattner50dd2892008-02-26 00:51:44 +0000126/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000127Action::OwningExprResult
128Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000129 Expr *Ex = E.takeAs<Expr>();
130 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
131 return ExprError();
132 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
133}
134
135/// CheckCXXThrowOperand - Validate the operand of a throw.
136bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
137 // C++ [except.throw]p3:
138 // [...] adjusting the type from "array of T" or "function returning T"
139 // to "pointer to T" or "pointer to function returning T", [...]
140 DefaultFunctionArrayConversion(E);
141
142 // If the type of the exception would be an incomplete type or a pointer
143 // to an incomplete type other than (cv) void the program is ill-formed.
144 QualType Ty = E->getType();
145 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000146 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000147 Ty = Ptr->getPointeeType();
148 isPointer = 1;
149 }
150 if (!isPointer || !Ty->isVoidType()) {
151 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000152 PDiag(isPointer ? diag::err_throw_incomplete_ptr
153 : diag::err_throw_incomplete)
154 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000155 return true;
156 }
157
158 // FIXME: Construct a temporary here.
159 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000160}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000161
Sebastian Redlf53597f2009-03-15 17:47:39 +0000162Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000163 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
164 /// is a non-lvalue expression whose value is the address of the object for
165 /// which the function is called.
166
Sebastian Redlf53597f2009-03-15 17:47:39 +0000167 if (!isa<FunctionDecl>(CurContext))
168 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000169
170 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
171 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000172 return Owned(new (Context) CXXThisExpr(ThisLoc,
173 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000174
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000176}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000177
178/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
179/// Can be interpreted either as function-style casting ("int(x)")
180/// or class type construction ("ClassType(x,y,z)")
181/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000182Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000183Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
184 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000185 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000186 SourceLocation *CommaLocs,
187 SourceLocation RParenLoc) {
188 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000189 // FIXME: Preserve type source info.
190 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191 unsigned NumExprs = exprs.size();
192 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000193 SourceLocation TyBeginLoc = TypeRange.getBegin();
194 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
195
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000197 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
200 return Owned(CXXUnresolvedConstructExpr::Create(Context,
201 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000202 LParenLoc,
203 Exprs, NumExprs,
204 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000205 }
206
Anders Carlssonbb60a502009-08-27 03:53:50 +0000207 if (Ty->isArrayType())
208 return ExprError(Diag(TyBeginLoc,
209 diag::err_value_init_for_array_type) << FullRange);
210 if (!Ty->isVoidType() &&
211 RequireCompleteType(TyBeginLoc, Ty,
212 PDiag(diag::err_invalid_incomplete_type_use)
213 << FullRange))
214 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000215
Anders Carlssonbb60a502009-08-27 03:53:50 +0000216 if (RequireNonAbstractType(TyBeginLoc, Ty,
217 diag::err_allocation_of_abstract_type))
218 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000219
220
Douglas Gregor506ae412009-01-16 18:33:17 +0000221 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000222 // If the expression list is a single expression, the type conversion
223 // expression is equivalent (in definedness, and if defined in meaning) to the
224 // corresponding cast expression.
225 //
226 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000227 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000228 CXXMethodDecl *Method = 0;
229 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
230 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000231 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000232
233 exprs.release();
234 if (Method) {
235 OwningExprResult CastArg
236 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
237 Kind, Method, Owned(Exprs[0]));
238 if (CastArg.isInvalid())
239 return ExprError();
240
241 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000242 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000243
244 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
245 Ty, TyBeginLoc, Kind,
246 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000247 }
248
Ted Kremenek6217b802009-07-29 21:53:49 +0000249 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000250 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000251
Mike Stump1eb44332009-09-09 15:08:12 +0000252 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000253 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000254 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
255
Douglas Gregor506ae412009-01-16 18:33:17 +0000256 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000257 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000258 TypeRange.getBegin(),
259 SourceRange(TypeRange.getBegin(),
260 RParenLoc),
261 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000262 IK_Direct,
263 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000264
Sebastian Redlf53597f2009-03-15 17:47:39 +0000265 if (!Constructor)
266 return ExprError();
267
Mike Stump1eb44332009-09-09 15:08:12 +0000268 OwningExprResult Result =
269 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000270 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000271 if (Result.isInvalid())
272 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Anders Carlssone7624a72009-08-27 05:08:22 +0000274 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000275 }
276
277 // Fall through to value-initialize an object of class type that
278 // doesn't have a user-declared default constructor.
279 }
280
281 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000282 // If the expression list specifies more than a single value, the type shall
283 // be a class with a suitably declared constructor.
284 //
285 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000286 return ExprError(Diag(CommaLocs[0],
287 diag::err_builtin_func_cast_more_than_one_arg)
288 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000289
290 assert(NumExprs == 0 && "Expected 0 expressions");
291
Douglas Gregor506ae412009-01-16 18:33:17 +0000292 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000293 // The expression T(), where T is a simple-type-specifier for a non-array
294 // complete object type or the (possibly cv-qualified) void type, creates an
295 // rvalue of the specified type, which is value-initialized.
296 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297 exprs.release();
298 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000299}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000300
301
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000302/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
303/// @code new (memory) int[size][4] @endcode
304/// or
305/// @code ::new Foo(23, "hello") @endcode
306/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000307Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000308Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000309 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000310 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000311 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000313 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000315 // If the specified type is an array, unwrap it and save the expression.
316 if (D.getNumTypeObjects() > 0 &&
317 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
318 DeclaratorChunk &Chunk = D.getTypeObject(0);
319 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000320 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
321 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000322 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
324 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000325
326 if (ParenTypeId) {
327 // Can't have dynamic array size when the type-id is in parentheses.
328 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
329 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
330 !NumElts->isIntegerConstantExpr(Context)) {
331 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
332 << NumElts->getSourceRange();
333 return ExprError();
334 }
335 }
336
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000337 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000338 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000339 }
340
Douglas Gregor043cad22009-09-11 00:18:58 +0000341 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000342 if (ArraySize) {
343 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000344 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
345 break;
346
347 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
348 if (Expr *NumElts = (Expr *)Array.NumElts) {
349 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
350 !NumElts->isIntegerConstantExpr(Context)) {
351 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
352 << NumElts->getSourceRange();
353 return ExprError();
354 }
355 }
356 }
357 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000358
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000359 //FIXME: Store DeclaratorInfo in CXXNew expression.
360 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000361 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000362 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000363 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364
Mike Stump1eb44332009-09-09 15:08:12 +0000365 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000366 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000367 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000368 PlacementRParen,
369 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000370 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000371 D.getSourceRange().getBegin(),
372 D.getSourceRange(),
373 Owned(ArraySize),
374 ConstructorLParen,
375 move(ConstructorArgs),
376 ConstructorRParen);
377}
378
Mike Stump1eb44332009-09-09 15:08:12 +0000379Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000380Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
381 SourceLocation PlacementLParen,
382 MultiExprArg PlacementArgs,
383 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000384 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000385 QualType AllocType,
386 SourceLocation TypeLoc,
387 SourceRange TypeRange,
388 ExprArg ArraySizeE,
389 SourceLocation ConstructorLParen,
390 MultiExprArg ConstructorArgs,
391 SourceLocation ConstructorRParen) {
392 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000393 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000394
Douglas Gregor3433cf72009-05-21 00:00:09 +0000395 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000396
397 // That every array dimension except the first is constant was already
398 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000399
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000400 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
401 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000402 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000403 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000404 QualType SizeType = ArraySize->getType();
405 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000406 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
407 diag::err_array_size_not_integral)
408 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000409 // Let's see if this is a constant < 0. If so, we reject it out of hand.
410 // We don't care about special rules, so we tell the machinery it's not
411 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000412 if (!ArraySize->isValueDependent()) {
413 llvm::APSInt Value;
414 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
415 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000416 llvm::APInt::getNullValue(Value.getBitWidth()),
417 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000418 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
419 diag::err_typecheck_negative_array_size)
420 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000421 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000422 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000423
Eli Friedman73c39ab2009-10-20 08:27:19 +0000424 ImpCastExprToType(ArraySize, Context.getSizeType(),
425 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000426 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000427
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000428 FunctionDecl *OperatorNew = 0;
429 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000430 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
431 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000432
Sebastian Redl28507842009-02-26 14:39:58 +0000433 if (!AllocType->isDependentType() &&
434 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
435 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000436 SourceRange(PlacementLParen, PlacementRParen),
437 UseGlobal, AllocType, ArraySize, PlaceArgs,
438 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000439 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000440
441 bool Init = ConstructorLParen.isValid();
442 // --- Choosing a constructor ---
443 // C++ 5.3.4p15
444 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
445 // the object is not initialized. If the object, or any part of it, is
446 // const-qualified, it's an error.
447 // 2) If T is a POD and there's an empty initializer, the object is value-
448 // initialized.
449 // 3) If T is a POD and there's one initializer argument, the object is copy-
450 // constructed.
451 // 4) If T is a POD and there's more initializer arguments, it's an error.
452 // 5) If T is not a POD, the initializer arguments are used as constructor
453 // arguments.
454 //
455 // Or by the C++0x formulation:
456 // 1) If there's no initializer, the object is default-initialized according
457 // to C++0x rules.
458 // 2) Otherwise, the object is direct-initialized.
459 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000460 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000461 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000462 unsigned NumConsArgs = ConstructorArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000463
464 if (AllocType->isDependentType() ||
465 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000466 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000467 } else if ((RT = AllocType->getAs<RecordType>()) &&
468 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000469 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
470
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000471 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000472 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000473 TypeLoc,
474 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000475 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000476 NumConsArgs != 0 ? IK_Direct : IK_Default,
477 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000478 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000479 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000480
481 // Take the converted constructor arguments and use them for the new
482 // expression.
483 NumConsArgs = ConvertedConstructorArgs.size();
484 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000485 } else {
486 if (!Init) {
487 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 if (AllocType.isConstQualified())
489 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000490 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000491 } else if (NumConsArgs == 0) {
492 // Object is value-initialized. Do nothing.
493 } else if (NumConsArgs == 1) {
494 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000495 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000496 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000497 DeclarationName() /*AllocType.getAsString()*/,
498 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000499 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000500 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000501 return ExprError(Diag(StartLoc,
502 diag::err_builtin_direct_init_more_than_one_arg)
503 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000504 }
505 }
506
507 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000508
Sebastian Redlf53597f2009-03-15 17:47:39 +0000509 PlacementArgs.release();
510 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000512 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000513 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000514 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000515 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000516}
517
518/// CheckAllocatedType - Checks that a type is suitable as the allocated type
519/// in a new-expression.
520/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000522 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000523 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
524 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000525 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000526 return Diag(Loc, diag::err_bad_new_type)
527 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000528 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000529 return Diag(Loc, diag::err_bad_new_type)
530 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000531 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000532 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000533 PDiag(diag::err_new_incomplete_type)
534 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000535 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000536 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000537 diag::err_allocation_of_abstract_type))
538 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000539
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000540 return false;
541}
542
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000543/// FindAllocationFunctions - Finds the overloads of operator new and delete
544/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000545bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
546 bool UseGlobal, QualType AllocType,
547 bool IsArray, Expr **PlaceArgs,
548 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000549 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000550 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000551 // --- Choosing an allocation function ---
552 // C++ 5.3.4p8 - 14 & 18
553 // 1) If UseGlobal is true, only look in the global scope. Else, also look
554 // in the scope of the allocated class.
555 // 2) If an array size is given, look for operator new[], else look for
556 // operator new.
557 // 3) The first argument is always size_t. Append the arguments from the
558 // placement form.
559 // FIXME: Also find the appropriate delete operator.
560
561 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
562 // We don't care about the actual value of this argument.
563 // FIXME: Should the Sema create the expression and embed it in the syntax
564 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000565 IntegerLiteral Size(llvm::APInt::getNullValue(
566 Context.Target.getPointerWidth(0)),
567 Context.getSizeType(),
568 SourceLocation());
569 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
571
572 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
573 IsArray ? OO_Array_New : OO_New);
574 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000575 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000576 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000577 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000578 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000579 AllocArgs.size(), Record, /*AllowMissing=*/true,
580 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000581 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000582 }
583 if (!OperatorNew) {
584 // Didn't find a member overload. Look for a global one.
585 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000586 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000587 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000588 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
589 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000590 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000591 }
592
Anders Carlssond9583892009-05-31 20:26:12 +0000593 // FindAllocationOverload can change the passed in arguments, so we need to
594 // copy them back.
595 if (NumPlaceArgs > 0)
596 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000598 return false;
599}
600
Sebastian Redl7f662392008-12-04 22:20:51 +0000601/// FindAllocationOverload - Find an fitting overload for the allocation
602/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000603bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
604 DeclarationName Name, Expr** Args,
605 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000606 bool AllowMissing, FunctionDecl *&Operator) {
John McCallf36e02d2009-10-09 21:13:30 +0000607 LookupResult R;
608 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
609 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000610 if (AllowMissing)
611 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000612 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000613 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000614 }
615
John McCallf36e02d2009-10-09 21:13:30 +0000616 // FIXME: handle ambiguity
617
Sebastian Redl7f662392008-12-04 22:20:51 +0000618 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000619 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
620 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000621 // Even member operator new/delete are implicitly treated as
622 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000623 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000624 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
625 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000626 continue;
627 }
628
629 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000630 }
631
632 // Do the resolution.
633 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000634 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000635 case OR_Success: {
636 // Got one!
637 FunctionDecl *FnDecl = Best->Function;
638 // The first argument is size_t, and the first parameter must be size_t,
639 // too. This is checked on declaration and can be assumed. (It can't be
640 // asserted on, though, since invalid decls are left in there.)
Douglas Gregor90916562009-09-29 18:16:17 +0000641 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000642 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000643 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000644 FnDecl->getParamDecl(i)->getType(),
645 "passing"))
646 return true;
647 }
648 Operator = FnDecl;
649 return false;
650 }
651
652 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000653 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000654 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000655 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
656 return true;
657
658 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000659 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000660 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000661 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
662 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000663
664 case OR_Deleted:
665 Diag(StartLoc, diag::err_ovl_deleted_call)
666 << Best->Function->isDeleted()
667 << Name << Range;
668 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
669 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000670 }
671 assert(false && "Unreachable, bad result from BestViableFunction");
672 return true;
673}
674
675
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000676/// DeclareGlobalNewDelete - Declare the global forms of operator new and
677/// delete. These are:
678/// @code
679/// void* operator new(std::size_t) throw(std::bad_alloc);
680/// void* operator new[](std::size_t) throw(std::bad_alloc);
681/// void operator delete(void *) throw();
682/// void operator delete[](void *) throw();
683/// @endcode
684/// Note that the placement and nothrow forms of new are *not* implicitly
685/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000686void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000687 if (GlobalNewDeleteDeclared)
688 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000689
690 // C++ [basic.std.dynamic]p2:
691 // [...] The following allocation and deallocation functions (18.4) are
692 // implicitly declared in global scope in each translation unit of a
693 // program
694 //
695 // void* operator new(std::size_t) throw(std::bad_alloc);
696 // void* operator new[](std::size_t) throw(std::bad_alloc);
697 // void operator delete(void*) throw();
698 // void operator delete[](void*) throw();
699 //
700 // These implicit declarations introduce only the function names operator
701 // new, operator new[], operator delete, operator delete[].
702 //
703 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
704 // "std" or "bad_alloc" as necessary to form the exception specification.
705 // However, we do not make these implicit declarations visible to name
706 // lookup.
707 if (!StdNamespace) {
708 // The "std" namespace has not yet been defined, so build one implicitly.
709 StdNamespace = NamespaceDecl::Create(Context,
710 Context.getTranslationUnitDecl(),
711 SourceLocation(),
712 &PP.getIdentifierTable().get("std"));
713 StdNamespace->setImplicit(true);
714 }
715
716 if (!StdBadAlloc) {
717 // The "std::bad_alloc" class has not yet been declared, so build it
718 // implicitly.
719 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
720 StdNamespace,
721 SourceLocation(),
722 &PP.getIdentifierTable().get("bad_alloc"),
723 SourceLocation(), 0);
724 StdBadAlloc->setImplicit(true);
725 }
726
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000727 GlobalNewDeleteDeclared = true;
728
729 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
730 QualType SizeT = Context.getSizeType();
731
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000732 DeclareGlobalAllocationFunction(
733 Context.DeclarationNames.getCXXOperatorName(OO_New),
734 VoidPtr, SizeT);
735 DeclareGlobalAllocationFunction(
736 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
737 VoidPtr, SizeT);
738 DeclareGlobalAllocationFunction(
739 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
740 Context.VoidTy, VoidPtr);
741 DeclareGlobalAllocationFunction(
742 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
743 Context.VoidTy, VoidPtr);
744}
745
746/// DeclareGlobalAllocationFunction - Declares a single implicit global
747/// allocation function if it doesn't already exist.
748void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000749 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000750 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
751
752 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000753 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000754 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000755 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000756 Alloc != AllocEnd; ++Alloc) {
757 // FIXME: Do we need to check for default arguments here?
758 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
759 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000760 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000761 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000762 }
763 }
764
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000765 QualType BadAllocType;
766 bool HasBadAllocExceptionSpec
767 = (Name.getCXXOverloadedOperator() == OO_New ||
768 Name.getCXXOverloadedOperator() == OO_Array_New);
769 if (HasBadAllocExceptionSpec) {
770 assert(StdBadAlloc && "Must have std::bad_alloc declared");
771 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
772 }
773
774 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
775 true, false,
776 HasBadAllocExceptionSpec? 1 : 0,
777 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000778 FunctionDecl *Alloc =
779 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000780 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000781 Alloc->setImplicit();
782 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000783 0, Argument, /*DInfo=*/0,
784 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000785 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000786
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000787 // FIXME: Also add this declaration to the IdentifierResolver, but
788 // make sure it is at the end of the chain to coincide with the
789 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000790 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000791}
792
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000793/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
794/// @code ::delete ptr; @endcode
795/// or
796/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000797Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000798Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000799 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000800 // C++ [expr.delete]p1:
801 // The operand shall have a pointer type, or a class type having a single
802 // conversion function to a pointer type. The result has type void.
803 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000804 // DR599 amends "pointer type" to "pointer to object type" in both cases.
805
Anders Carlssond67c4c32009-08-16 20:29:29 +0000806 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Sebastian Redlf53597f2009-03-15 17:47:39 +0000808 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000809 if (!Ex->isTypeDependent()) {
810 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000811
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000812 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000813 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000814 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
815 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000816 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000817
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000818 for (OverloadedFunctionDecl::function_iterator
819 Func = Conversions->function_begin(),
820 FuncEnd = Conversions->function_end();
821 Func != FuncEnd; ++Func) {
822 // Skip over templated conversion functions; they aren't considered.
823 if (isa<FunctionTemplateDecl>(*Func))
824 continue;
825
826 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
827
828 QualType ConvType = Conv->getConversionType().getNonReferenceType();
829 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
830 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000831 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000832 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000833 if (ObjectPtrConversions.size() == 1) {
834 // We have a single conversion to a pointer-to-object type. Perform
835 // that conversion.
836 Operand.release();
837 if (!PerformImplicitConversion(Ex,
838 ObjectPtrConversions.front()->getConversionType(),
839 "converting")) {
840 Operand = Owned(Ex);
841 Type = Ex->getType();
842 }
843 }
844 else if (ObjectPtrConversions.size() > 1) {
845 Diag(StartLoc, diag::err_ambiguous_delete_operand)
846 << Type << Ex->getSourceRange();
847 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
848 CXXConversionDecl *Conv = ObjectPtrConversions[i];
849 Diag(Conv->getLocation(), diag::err_ovl_candidate);
850 }
851 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000852 }
Sebastian Redl28507842009-02-26 14:39:58 +0000853 }
854
Sebastian Redlf53597f2009-03-15 17:47:39 +0000855 if (!Type->isPointerType())
856 return ExprError(Diag(StartLoc, diag::err_delete_operand)
857 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000858
Ted Kremenek6217b802009-07-29 21:53:49 +0000859 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000860 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000861 return ExprError(Diag(StartLoc, diag::err_delete_operand)
862 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000863 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000864 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000865 PDiag(diag::warn_delete_incomplete)
866 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000867 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000868
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000869 // C++ [expr.delete]p2:
870 // [Note: a pointer to a const type can be the operand of a
871 // delete-expression; it is not necessary to cast away the constness
872 // (5.2.11) of the pointer expression before it is used as the operand
873 // of the delete-expression. ]
874 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
875 CastExpr::CK_NoOp);
876
877 // Update the operand.
878 Operand.take();
879 Operand = ExprArg(*this, Ex);
880
Anders Carlssond67c4c32009-08-16 20:29:29 +0000881 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
882 ArrayForm ? OO_Array_Delete : OO_Delete);
883
884 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000885 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000886 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
Douglas Gregor90916562009-09-29 18:16:17 +0000887
888 // Try to find operator delete/operator delete[] in class scope.
John McCallf36e02d2009-10-09 21:13:30 +0000889 LookupResult Found;
890 LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
Douglas Gregor90916562009-09-29 18:16:17 +0000891 // FIXME: Diagnose ambiguity properly
892 assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
893 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
894 F != FEnd; ++F) {
895 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
896 if (Delete->isUsualDeallocationFunction()) {
897 OperatorDelete = Delete;
898 break;
899 }
900 }
901
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000902 if (!Record->hasTrivialDestructor())
903 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000904 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000905 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Anders Carlssond67c4c32009-08-16 20:29:29 +0000908 if (!OperatorDelete) {
909 // Didn't find a member overload. Look for a global one.
910 DeclareGlobalNewDelete();
911 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000912 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000913 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000914 OperatorDelete))
915 return ExprError();
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Sebastian Redl28507842009-02-26 14:39:58 +0000918 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000919 }
920
Sebastian Redlf53597f2009-03-15 17:47:39 +0000921 Operand.release();
922 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000923 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000924}
925
926
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000927/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
928/// C++ if/switch/while/for statement.
929/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000930Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000931Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
932 Declarator &D,
933 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000934 ExprArg AssignExprVal) {
935 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000936
937 // C++ 6.4p2:
938 // The declarator shall not specify a function or an array.
939 // The type-specifier-seq shall not contain typedef and shall not declare a
940 // new class or enumeration.
941
942 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
943 "Parser allowed 'typedef' as storage class of condition decl.");
944
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000945 // FIXME: Store DeclaratorInfo in the expression.
946 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000947 TagDecl *OwnedTag = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000948 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000950 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
951 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
952 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000953 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
954 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000955 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000956 Diag(StartLoc, diag::err_invalid_use_of_array_type)
957 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000958 } else if (OwnedTag && OwnedTag->isDefinition()) {
959 // The type-specifier-seq shall not declare a new class or enumeration.
960 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000961 }
962
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000963 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000964 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000965 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000966 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000967
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000968 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000969 // We know that the decl had to be a VarDecl because that is the only type of
970 // decl that can be assigned and the grammar requires an '='.
971 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
972 VD->setDeclaredInCondition(true);
973 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000974}
975
976/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
977bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
978 // C++ 6.4p4:
979 // The value of a condition that is an initialized declaration in a statement
980 // other than a switch statement is the value of the declared variable
981 // implicitly converted to type bool. If that conversion is ill-formed, the
982 // program is ill-formed.
983 // The value of a condition that is an expression is the value of the
984 // expression, implicitly converted to bool.
985 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000986 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000987}
Douglas Gregor77a52232008-09-12 00:47:35 +0000988
989/// Helper function to determine whether this is the (deprecated) C++
990/// conversion from a string literal to a pointer to non-const char or
991/// non-const wchar_t (for narrow and wide string literals,
992/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000993bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000994Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
995 // Look inside the implicit cast, if it exists.
996 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
997 From = Cast->getSubExpr();
998
999 // A string literal (2.13.4) that is not a wide string literal can
1000 // be converted to an rvalue of type "pointer to char"; a wide
1001 // string literal can be converted to an rvalue of type "pointer
1002 // to wchar_t" (C++ 4.2p2).
1003 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001004 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001005 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001006 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001007 // This conversion is considered only when there is an
1008 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001009 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001010 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1011 (!StrLit->isWide() &&
1012 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1013 ToPointeeType->getKind() == BuiltinType::Char_S))))
1014 return true;
1015 }
1016
1017 return false;
1018}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001019
1020/// PerformImplicitConversion - Perform an implicit conversion of the
1021/// expression From to the type ToType. Returns true if there was an
1022/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001023/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001024/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001025/// explicit user-defined conversions are permitted. @p Elidable should be true
1026/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1027/// resolution works differently in that case.
1028bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001029Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001030 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001031 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001032 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001033 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1034 Elidable, ICS);
1035}
1036
1037bool
1038Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1039 const char *Flavor, bool AllowExplicit,
1040 bool Elidable,
1041 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001042 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1043 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001044 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001045 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001046 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001047 /*ForceRValue=*/true,
1048 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001049 }
1050 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001051 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001052 /*SuppressUserConversions=*/false,
1053 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001054 /*ForceRValue=*/false,
1055 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001056 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001057 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1058}
1059
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001060/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1061/// for the derived to base conversion of the expression 'From'. All
1062/// necessary information is passed in ICS.
1063bool
1064Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1065 const ImplicitConversionSequence& ICS,
1066 const char *Flavor) {
1067 QualType BaseType =
1068 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1069 // Must do additional defined to base conversion.
1070 QualType DerivedType =
1071 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1072
1073 From = new (Context) ImplicitCastExpr(
1074 DerivedType.getNonReferenceType(),
1075 CastKind,
1076 From,
1077 DerivedType->isLValueReferenceType());
1078 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1079 CastExpr::CK_DerivedToBase, From,
1080 BaseType->isLValueReferenceType());
1081 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1082 OwningExprResult FromResult =
1083 BuildCXXConstructExpr(
1084 ICS.UserDefined.After.CopyConstructor->getLocation(),
1085 BaseType,
1086 ICS.UserDefined.After.CopyConstructor,
1087 MultiExprArg(*this, (void **)&From, 1));
1088 if (FromResult.isInvalid())
1089 return true;
1090 From = FromResult.takeAs<Expr>();
1091 return false;
1092}
1093
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001094/// PerformImplicitConversion - Perform an implicit conversion of the
1095/// expression From to the type ToType using the pre-computed implicit
1096/// conversion sequence ICS. Returns true if there was an error, false
1097/// otherwise. The expression From is replaced with the converted
1098/// expression. Flavor is the kind of conversion we're performing,
1099/// used in the error message.
1100bool
1101Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1102 const ImplicitConversionSequence &ICS,
1103 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001104 switch (ICS.ConversionKind) {
1105 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001106 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001107 return true;
1108 break;
1109
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001110 case ImplicitConversionSequence::UserDefinedConversion: {
1111
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001112 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1113 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001114 QualType BeforeToType;
1115 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001116 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001117
1118 // If the user-defined conversion is specified by a conversion function,
1119 // the initial standard conversion sequence converts the source type to
1120 // the implicit object parameter of the conversion function.
1121 BeforeToType = Context.getTagDeclType(Conv->getParent());
1122 } else if (const CXXConstructorDecl *Ctor =
1123 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001124 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001125
1126 // If the user-defined conversion is specified by a constructor, the
1127 // initial standard conversion sequence converts the source type to the
1128 // type required by the argument of the constructor
1129 BeforeToType = Ctor->getParamDecl(0)->getType();
1130 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001131 else
1132 assert(0 && "Unknown conversion function kind!");
1133
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001134 if (PerformImplicitConversion(From, BeforeToType,
1135 ICS.UserDefined.Before, "converting"))
1136 return true;
1137
Anders Carlsson0aebc812009-09-09 21:33:21 +00001138 OwningExprResult CastArg
1139 = BuildCXXCastArgument(From->getLocStart(),
1140 ToType.getNonReferenceType(),
1141 CastKind, cast<CXXMethodDecl>(FD),
1142 Owned(From));
1143
1144 if (CastArg.isInvalid())
1145 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001146
1147 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1148 ICS.UserDefined.After.CopyConstructor) {
1149 From = CastArg.takeAs<Expr>();
1150 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1151 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001152
1153 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1154 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1155 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001156
Anders Carlsson626c2d62009-09-15 05:49:31 +00001157 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001158 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001159 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001160 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001161 }
1162
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001163 case ImplicitConversionSequence::EllipsisConversion:
1164 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001165 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001166
1167 case ImplicitConversionSequence::BadConversion:
1168 return true;
1169 }
1170
1171 // Everything went well.
1172 return false;
1173}
1174
1175/// PerformImplicitConversion - Perform an implicit conversion of the
1176/// expression From to the type ToType by following the standard
1177/// conversion sequence SCS. Returns true if there was an error, false
1178/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001179/// expression. Flavor is the context in which we're performing this
1180/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001181bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001182Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001183 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001184 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001185 // Overall FIXME: we are recomputing too many types here and doing far too
1186 // much extra work. What this means is that we need to keep track of more
1187 // information that is computed when we try the implicit conversion initially,
1188 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001189 QualType FromType = From->getType();
1190
Douglas Gregor225c41e2008-11-03 19:09:14 +00001191 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001192 // FIXME: When can ToType be a reference type?
1193 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001194 if (SCS.Second == ICK_Derived_To_Base) {
1195 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1196 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1197 MultiExprArg(*this, (void **)&From, 1),
1198 /*FIXME:ConstructLoc*/SourceLocation(),
1199 ConstructorArgs))
1200 return true;
1201 OwningExprResult FromResult =
1202 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1203 ToType, SCS.CopyConstructor,
1204 move_arg(ConstructorArgs));
1205 if (FromResult.isInvalid())
1206 return true;
1207 From = FromResult.takeAs<Expr>();
1208 return false;
1209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210 OwningExprResult FromResult =
1211 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1212 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001213 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001215 if (FromResult.isInvalid())
1216 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001218 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001219 return false;
1220 }
1221
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001222 // Perform the first implicit conversion.
1223 switch (SCS.First) {
1224 case ICK_Identity:
1225 case ICK_Lvalue_To_Rvalue:
1226 // Nothing to do.
1227 break;
1228
1229 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001230 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001231 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001232 break;
1233
1234 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001235 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001236 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1237 if (!Fn)
1238 return true;
1239
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001240 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1241 return true;
1242
Anders Carlsson96ad5332009-10-21 17:16:23 +00001243 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001244 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001245
Sebastian Redl759986e2009-10-17 20:50:27 +00001246 // If there's already an address-of operator in the expression, we have
1247 // the right type already, and the code below would just introduce an
1248 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001249 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001250 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001251 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001252 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001253 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001254 break;
1255
1256 default:
1257 assert(false && "Improper first standard conversion");
1258 break;
1259 }
1260
1261 // Perform the second implicit conversion
1262 switch (SCS.Second) {
1263 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001264 // If both sides are functions (or pointers/references to them), there could
1265 // be incompatible exception declarations.
1266 if (CheckExceptionSpecCompatibility(From, ToType))
1267 return true;
1268 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001269 break;
1270
1271 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001272 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001273 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1274 break;
1275
1276 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001277 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001278 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1279 break;
1280
1281 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001282 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001283 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1284 break;
1285
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001286 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001287 if (ToType->isFloatingType())
1288 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1289 else
1290 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1291 break;
1292
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001293 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001294 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1295 break;
1296
Douglas Gregorf9201e02009-02-11 23:02:49 +00001297 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001298 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001299 break;
1300
Anders Carlsson61faec12009-09-12 04:46:44 +00001301 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001302 if (SCS.IncompatibleObjC) {
1303 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001304 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001305 diag::ext_typecheck_convert_incompatible_pointer)
1306 << From->getType() << ToType << Flavor
1307 << From->getSourceRange();
1308 }
1309
Anders Carlsson61faec12009-09-12 04:46:44 +00001310
1311 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1312 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001313 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001314 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001315 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001316 }
1317
1318 case ICK_Pointer_Member: {
1319 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1320 if (CheckMemberPointerConversion(From, ToType, Kind))
1321 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001322 if (CheckExceptionSpecCompatibility(From, ToType))
1323 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001324 ImpCastExprToType(From, ToType, Kind);
1325 break;
1326 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001327 case ICK_Boolean_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001328 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001329 break;
1330
1331 default:
1332 assert(false && "Improper second standard conversion");
1333 break;
1334 }
1335
1336 switch (SCS.Third) {
1337 case ICK_Identity:
1338 // Nothing to do.
1339 break;
1340
1341 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001342 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1343 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001344 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001345 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001346 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001347 break;
1348
1349 default:
1350 assert(false && "Improper second standard conversion");
1351 break;
1352 }
1353
1354 return false;
1355}
1356
Sebastian Redl64b45f72009-01-05 20:52:13 +00001357Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1358 SourceLocation KWLoc,
1359 SourceLocation LParen,
1360 TypeTy *Ty,
1361 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001362 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001364 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1365 // all traits except __is_class, __is_enum and __is_union require a the type
1366 // to be complete.
1367 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001368 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001369 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001370 return ExprError();
1371 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001372
1373 // There is no point in eagerly computing the value. The traits are designed
1374 // to be used from type trait templates, so Ty will be a template parameter
1375 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001376 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1377 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001378}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001379
1380QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001381 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001382 const char *OpSpelling = isIndirect ? "->*" : ".*";
1383 // C++ 5.5p2
1384 // The binary operator .* [p3: ->*] binds its second operand, which shall
1385 // be of type "pointer to member of T" (where T is a completely-defined
1386 // class type) [...]
1387 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001388 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001389 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001390 Diag(Loc, diag::err_bad_memptr_rhs)
1391 << OpSpelling << RType << rex->getSourceRange();
1392 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001393 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001394
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001395 QualType Class(MemPtr->getClass(), 0);
1396
1397 // C++ 5.5p2
1398 // [...] to its first operand, which shall be of class T or of a class of
1399 // which T is an unambiguous and accessible base class. [p3: a pointer to
1400 // such a class]
1401 QualType LType = lex->getType();
1402 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001403 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001404 LType = Ptr->getPointeeType().getNonReferenceType();
1405 else {
1406 Diag(Loc, diag::err_bad_memptr_lhs)
1407 << OpSpelling << 1 << LType << lex->getSourceRange();
1408 return QualType();
1409 }
1410 }
1411
1412 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1413 Context.getCanonicalType(LType).getUnqualifiedType()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001414 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1415 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001416 // FIXME: Would it be useful to print full ambiguity paths, or is that
1417 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001418 if (!IsDerivedFrom(LType, Class, Paths) ||
1419 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1420 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1421 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1422 return QualType();
1423 }
1424 }
1425
1426 // C++ 5.5p2
1427 // The result is an object or a function of the type specified by the
1428 // second operand.
1429 // The cv qualifiers are the union of those in the pointer and the left side,
1430 // in accordance with 5.5p5 and 5.2.5.
1431 // FIXME: This returns a dereferenced member function pointer as a normal
1432 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001433 // calling them. There's also a GCC extension to get a function pointer to the
1434 // thing, which is another complication, because this type - unlike the type
1435 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001436 // argument.
1437 // We probably need a "MemberFunctionClosureType" or something like that.
1438 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001439 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001440 return Result;
1441}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001442
1443/// \brief Get the target type of a standard or user-defined conversion.
1444static QualType TargetType(const ImplicitConversionSequence &ICS) {
1445 assert((ICS.ConversionKind ==
1446 ImplicitConversionSequence::StandardConversion ||
1447 ICS.ConversionKind ==
1448 ImplicitConversionSequence::UserDefinedConversion) &&
1449 "function only valid for standard or user-defined conversions");
1450 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1451 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1452 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1453}
1454
1455/// \brief Try to convert a type to another according to C++0x 5.16p3.
1456///
1457/// This is part of the parameter validation for the ? operator. If either
1458/// value operand is a class type, the two operands are attempted to be
1459/// converted to each other. This function does the conversion in one direction.
1460/// It emits a diagnostic and returns true only if it finds an ambiguous
1461/// conversion.
1462static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1463 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001464 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001465 // C++0x 5.16p3
1466 // The process for determining whether an operand expression E1 of type T1
1467 // can be converted to match an operand expression E2 of type T2 is defined
1468 // as follows:
1469 // -- If E2 is an lvalue:
1470 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1471 // E1 can be converted to match E2 if E1 can be implicitly converted to
1472 // type "lvalue reference to T2", subject to the constraint that in the
1473 // conversion the reference must bind directly to E1.
1474 if (!Self.CheckReferenceInit(From,
1475 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001476 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001477 /*SuppressUserConversions=*/false,
1478 /*AllowExplicit=*/false,
1479 /*ForceRValue=*/false,
1480 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001481 {
1482 assert((ICS.ConversionKind ==
1483 ImplicitConversionSequence::StandardConversion ||
1484 ICS.ConversionKind ==
1485 ImplicitConversionSequence::UserDefinedConversion) &&
1486 "expected a definite conversion");
1487 bool DirectBinding =
1488 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1489 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1490 if (DirectBinding)
1491 return false;
1492 }
1493 }
1494 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1495 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1496 // -- if E1 and E2 have class type, and the underlying class types are
1497 // the same or one is a base class of the other:
1498 QualType FTy = From->getType();
1499 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001500 const RecordType *FRec = FTy->getAs<RecordType>();
1501 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001502 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1503 if (FRec && TRec && (FRec == TRec ||
1504 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1505 // E1 can be converted to match E2 if the class of T2 is the
1506 // same type as, or a base class of, the class of T1, and
1507 // [cv2 > cv1].
1508 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1509 // Could still fail if there's no copy constructor.
1510 // FIXME: Is this a hard error then, or just a conversion failure? The
1511 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001512 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001513 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001514 /*ForceRValue=*/false,
1515 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001516 }
1517 } else {
1518 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1519 // implicitly converted to the type that expression E2 would have
1520 // if E2 were converted to an rvalue.
1521 // First find the decayed type.
1522 if (TTy->isFunctionType())
1523 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001524 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001525 TTy = Self.Context.getArrayDecayedType(TTy);
1526
1527 // Now try the implicit conversion.
1528 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001529 ICS = Self.TryImplicitConversion(From, TTy,
1530 /*SuppressUserConversions=*/false,
1531 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001532 /*ForceRValue=*/false,
1533 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001534 }
1535 return false;
1536}
1537
1538/// \brief Try to find a common type for two according to C++0x 5.16p5.
1539///
1540/// This is part of the parameter validation for the ? operator. If either
1541/// value operand is a class type, overload resolution is used to find a
1542/// conversion to a common type.
1543static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1544 SourceLocation Loc) {
1545 Expr *Args[2] = { LHS, RHS };
1546 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001547 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001548
1549 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001550 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001551 case Sema::OR_Success:
1552 // We found a match. Perform the conversions on the arguments and move on.
1553 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1554 Best->Conversions[0], "converting") ||
1555 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1556 Best->Conversions[1], "converting"))
1557 break;
1558 return false;
1559
1560 case Sema::OR_No_Viable_Function:
1561 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1562 << LHS->getType() << RHS->getType()
1563 << LHS->getSourceRange() << RHS->getSourceRange();
1564 return true;
1565
1566 case Sema::OR_Ambiguous:
1567 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1568 << LHS->getType() << RHS->getType()
1569 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001570 // FIXME: Print the possible common types by printing the return types of
1571 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001572 break;
1573
1574 case Sema::OR_Deleted:
1575 assert(false && "Conditional operator has only built-in overloads");
1576 break;
1577 }
1578 return true;
1579}
1580
Sebastian Redl76458502009-04-17 16:30:52 +00001581/// \brief Perform an "extended" implicit conversion as returned by
1582/// TryClassUnification.
1583///
1584/// TryClassUnification generates ICSs that include reference bindings.
1585/// PerformImplicitConversion is not suitable for this; it chokes if the
1586/// second part of a standard conversion is ICK_DerivedToBase. This function
1587/// handles the reference binding specially.
1588static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001589 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001590 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1591 ICS.Standard.ReferenceBinding) {
1592 assert(ICS.Standard.DirectBinding &&
1593 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001594 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1595 // redoing all the work.
1596 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001597 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001598 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001599 /*SuppressUserConversions=*/false,
1600 /*AllowExplicit=*/false,
1601 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001602 }
1603 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1604 ICS.UserDefined.After.ReferenceBinding) {
1605 assert(ICS.UserDefined.After.DirectBinding &&
1606 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001607 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001608 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001609 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001610 /*SuppressUserConversions=*/false,
1611 /*AllowExplicit=*/false,
1612 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001613 }
1614 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1615 return true;
1616 return false;
1617}
1618
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001619/// \brief Check the operands of ?: under C++ semantics.
1620///
1621/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1622/// extension. In this case, LHS == Cond. (But they're not aliases.)
1623QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1624 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001625 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1626 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001627
1628 // C++0x 5.16p1
1629 // The first expression is contextually converted to bool.
1630 if (!Cond->isTypeDependent()) {
1631 if (CheckCXXBooleanCondition(Cond))
1632 return QualType();
1633 }
1634
1635 // Either of the arguments dependent?
1636 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1637 return Context.DependentTy;
1638
1639 // C++0x 5.16p2
1640 // If either the second or the third operand has type (cv) void, ...
1641 QualType LTy = LHS->getType();
1642 QualType RTy = RHS->getType();
1643 bool LVoid = LTy->isVoidType();
1644 bool RVoid = RTy->isVoidType();
1645 if (LVoid || RVoid) {
1646 // ... then the [l2r] conversions are performed on the second and third
1647 // operands ...
1648 DefaultFunctionArrayConversion(LHS);
1649 DefaultFunctionArrayConversion(RHS);
1650 LTy = LHS->getType();
1651 RTy = RHS->getType();
1652
1653 // ... and one of the following shall hold:
1654 // -- The second or the third operand (but not both) is a throw-
1655 // expression; the result is of the type of the other and is an rvalue.
1656 bool LThrow = isa<CXXThrowExpr>(LHS);
1657 bool RThrow = isa<CXXThrowExpr>(RHS);
1658 if (LThrow && !RThrow)
1659 return RTy;
1660 if (RThrow && !LThrow)
1661 return LTy;
1662
1663 // -- Both the second and third operands have type void; the result is of
1664 // type void and is an rvalue.
1665 if (LVoid && RVoid)
1666 return Context.VoidTy;
1667
1668 // Neither holds, error.
1669 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1670 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1671 << LHS->getSourceRange() << RHS->getSourceRange();
1672 return QualType();
1673 }
1674
1675 // Neither is void.
1676
1677 // C++0x 5.16p3
1678 // Otherwise, if the second and third operand have different types, and
1679 // either has (cv) class type, and attempt is made to convert each of those
1680 // operands to the other.
1681 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1682 (LTy->isRecordType() || RTy->isRecordType())) {
1683 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1684 // These return true if a single direction is already ambiguous.
1685 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1686 return QualType();
1687 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1688 return QualType();
1689
1690 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1691 ImplicitConversionSequence::BadConversion;
1692 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1693 ImplicitConversionSequence::BadConversion;
1694 // If both can be converted, [...] the program is ill-formed.
1695 if (HaveL2R && HaveR2L) {
1696 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1697 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1698 return QualType();
1699 }
1700
1701 // If exactly one conversion is possible, that conversion is applied to
1702 // the chosen operand and the converted operands are used in place of the
1703 // original operands for the remainder of this section.
1704 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001705 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001706 return QualType();
1707 LTy = LHS->getType();
1708 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001709 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001710 return QualType();
1711 RTy = RHS->getType();
1712 }
1713 }
1714
1715 // C++0x 5.16p4
1716 // If the second and third operands are lvalues and have the same type,
1717 // the result is of that type [...]
1718 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1719 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1720 RHS->isLvalue(Context) == Expr::LV_Valid)
1721 return LTy;
1722
1723 // C++0x 5.16p5
1724 // Otherwise, the result is an rvalue. If the second and third operands
1725 // do not have the same type, and either has (cv) class type, ...
1726 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1727 // ... overload resolution is used to determine the conversions (if any)
1728 // to be applied to the operands. If the overload resolution fails, the
1729 // program is ill-formed.
1730 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1731 return QualType();
1732 }
1733
1734 // C++0x 5.16p6
1735 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1736 // conversions are performed on the second and third operands.
1737 DefaultFunctionArrayConversion(LHS);
1738 DefaultFunctionArrayConversion(RHS);
1739 LTy = LHS->getType();
1740 RTy = RHS->getType();
1741
1742 // After those conversions, one of the following shall hold:
1743 // -- The second and third operands have the same type; the result
1744 // is of that type.
1745 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1746 return LTy;
1747
1748 // -- The second and third operands have arithmetic or enumeration type;
1749 // the usual arithmetic conversions are performed to bring them to a
1750 // common type, and the result is of that type.
1751 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1752 UsualArithmeticConversions(LHS, RHS);
1753 return LHS->getType();
1754 }
1755
1756 // -- The second and third operands have pointer type, or one has pointer
1757 // type and the other is a null pointer constant; pointer conversions
1758 // and qualification conversions are performed to bring them to their
1759 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001760 QualType Composite = FindCompositePointerType(LHS, RHS);
1761 if (!Composite.isNull())
1762 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001763
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001764 // Fourth bullet is same for pointers-to-member. However, the possible
1765 // conversions are far more limited: we have null-to-pointer, upcast of
1766 // containing class, and second-level cv-ness.
1767 // cv-ness is not a union, but must match one of the two operands. (Which,
1768 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001769 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1770 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001771 if (LMemPtr &&
1772 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001773 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001774 return LTy;
1775 }
Douglas Gregorce940492009-09-25 04:25:58 +00001776 if (RMemPtr &&
1777 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001778 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001779 return RTy;
1780 }
1781 if (LMemPtr && RMemPtr) {
1782 QualType LPointee = LMemPtr->getPointeeType();
1783 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001784
1785 QualifierCollector LPQuals, RPQuals;
1786 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1787 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1788
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001789 // First, we check that the unqualified pointee type is the same. If it's
1790 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001791 if (LPCan == RPCan) {
1792
1793 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001794 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001795
1796 Qualifiers MergedQuals = LPQuals + RPQuals;
1797
1798 bool CompatibleQuals = true;
1799 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1800 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1801 CompatibleQuals = false;
1802 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1803 // FIXME:
1804 // C99 6.5.15 as modified by TR 18037:
1805 // If the second and third operands are pointers into different
1806 // address spaces, the address spaces must overlap.
1807 CompatibleQuals = false;
1808 // FIXME: GC qualifiers?
1809
1810 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001811 // Third, we check if either of the container classes is derived from
1812 // the other.
1813 QualType LContainer(LMemPtr->getClass(), 0);
1814 QualType RContainer(RMemPtr->getClass(), 0);
1815 QualType MoreDerived;
1816 if (Context.getCanonicalType(LContainer) ==
1817 Context.getCanonicalType(RContainer))
1818 MoreDerived = LContainer;
1819 else if (IsDerivedFrom(LContainer, RContainer))
1820 MoreDerived = LContainer;
1821 else if (IsDerivedFrom(RContainer, LContainer))
1822 MoreDerived = RContainer;
1823
1824 if (!MoreDerived.isNull()) {
1825 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1826 // We don't use ImpCastExprToType here because this could still fail
1827 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001828 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1829 QualType Common
1830 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001831 if (PerformImplicitConversion(LHS, Common, "converting"))
1832 return QualType();
1833 if (PerformImplicitConversion(RHS, Common, "converting"))
1834 return QualType();
1835 return Common;
1836 }
1837 }
1838 }
1839 }
1840
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001841 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1842 << LHS->getType() << RHS->getType()
1843 << LHS->getSourceRange() << RHS->getSourceRange();
1844 return QualType();
1845}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001846
1847/// \brief Find a merged pointer type and convert the two expressions to it.
1848///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001849/// This finds the composite pointer type (or member pointer type) for @p E1
1850/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1851/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001852/// It does not emit diagnostics.
1853QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1854 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1855 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor20b3e992009-08-24 17:42:35 +00001857 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1858 !T2->isPointerType() && !T2->isMemberPointerType())
1859 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001860
Douglas Gregor20b3e992009-08-24 17:42:35 +00001861 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001863 // C++0x 5.9p2
1864 // Pointer conversions and qualification conversions are performed on
1865 // pointer operands to bring them to their composite pointer type. If
1866 // one operand is a null pointer constant, the composite pointer type is
1867 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001868 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001869 if (T2->isMemberPointerType())
1870 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1871 else
1872 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001873 return T2;
1874 }
Douglas Gregorce940492009-09-25 04:25:58 +00001875 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001876 if (T1->isMemberPointerType())
1877 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1878 else
1879 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001880 return T1;
1881 }
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Douglas Gregor20b3e992009-08-24 17:42:35 +00001883 // Now both have to be pointers or member pointers.
1884 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1885 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001886 return QualType();
1887
1888 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1889 // the other has type "pointer to cv2 T" and the composite pointer type is
1890 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1891 // Otherwise, the composite pointer type is a pointer type similar to the
1892 // type of one of the operands, with a cv-qualification signature that is
1893 // the union of the cv-qualification signatures of the operand types.
1894 // In practice, the first part here is redundant; it's subsumed by the second.
1895 // What we do here is, we build the two possible composite types, and try the
1896 // conversions in both directions. If only one works, or if the two composite
1897 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001898 // FIXME: extended qualifiers?
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001899 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001900 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001901 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001902 do {
1903 const PointerType *Ptr1, *Ptr2;
1904 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1905 (Ptr2 = Composite2->getAs<PointerType>())) {
1906 Composite1 = Ptr1->getPointeeType();
1907 Composite2 = Ptr2->getPointeeType();
1908 QualifierUnion.push_back(
1909 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1910 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1911 continue;
1912 }
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Douglas Gregor20b3e992009-08-24 17:42:35 +00001914 const MemberPointerType *MemPtr1, *MemPtr2;
1915 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1916 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1917 Composite1 = MemPtr1->getPointeeType();
1918 Composite2 = MemPtr2->getPointeeType();
1919 QualifierUnion.push_back(
1920 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1921 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1922 MemPtr2->getClass()));
1923 continue;
1924 }
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Douglas Gregor20b3e992009-08-24 17:42:35 +00001926 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Douglas Gregor20b3e992009-08-24 17:42:35 +00001928 // Cannot unwrap any more types.
1929 break;
1930 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Douglas Gregor20b3e992009-08-24 17:42:35 +00001932 // Rewrap the composites as pointers or member pointers with the union CVRs.
1933 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1934 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001935 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001936 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001937 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001938 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001939 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001940 if (MOC->first && MOC->second) {
1941 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001942 Composite1 = Context.getMemberPointerType(
1943 Context.getQualifiedType(Composite1, Quals),
1944 MOC->first);
1945 Composite2 = Context.getMemberPointerType(
1946 Context.getQualifiedType(Composite2, Quals),
1947 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001948 } else {
1949 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001950 Composite1
1951 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1952 Composite2
1953 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001954 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001955 }
1956
Mike Stump1eb44332009-09-09 15:08:12 +00001957 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001958 TryImplicitConversion(E1, Composite1,
1959 /*SuppressUserConversions=*/false,
1960 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001961 /*ForceRValue=*/false,
1962 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001963 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001964 TryImplicitConversion(E2, Composite1,
1965 /*SuppressUserConversions=*/false,
1966 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001967 /*ForceRValue=*/false,
1968 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001970 ImplicitConversionSequence E1ToC2, E2ToC2;
1971 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1972 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1973 if (Context.getCanonicalType(Composite1) !=
1974 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001975 E1ToC2 = TryImplicitConversion(E1, Composite2,
1976 /*SuppressUserConversions=*/false,
1977 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001978 /*ForceRValue=*/false,
1979 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001980 E2ToC2 = TryImplicitConversion(E2, Composite2,
1981 /*SuppressUserConversions=*/false,
1982 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001983 /*ForceRValue=*/false,
1984 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001985 }
1986
1987 bool ToC1Viable = E1ToC1.ConversionKind !=
1988 ImplicitConversionSequence::BadConversion
1989 && E2ToC1.ConversionKind !=
1990 ImplicitConversionSequence::BadConversion;
1991 bool ToC2Viable = E1ToC2.ConversionKind !=
1992 ImplicitConversionSequence::BadConversion
1993 && E2ToC2.ConversionKind !=
1994 ImplicitConversionSequence::BadConversion;
1995 if (ToC1Viable && !ToC2Viable) {
1996 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1997 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1998 return Composite1;
1999 }
2000 if (ToC2Viable && !ToC1Viable) {
2001 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2002 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2003 return Composite2;
2004 }
2005 return QualType();
2006}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002007
Anders Carlssondef11992009-05-30 20:36:53 +00002008Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002009 if (!Context.getLangOptions().CPlusPlus)
2010 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Ted Kremenek6217b802009-07-29 21:53:49 +00002012 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002013 if (!RT)
2014 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Anders Carlssondef11992009-05-30 20:36:53 +00002016 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2017 if (RD->hasTrivialDestructor())
2018 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Anders Carlsson283e4d52009-09-14 01:30:44 +00002020 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2021 QualType Ty = CE->getCallee()->getType();
2022 if (const PointerType *PT = Ty->getAs<PointerType>())
2023 Ty = PT->getPointeeType();
2024
John McCall183700f2009-09-21 23:43:11 +00002025 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002026 if (FTy->getResultType()->isReferenceType())
2027 return Owned(E);
2028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002030 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002031 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002032 if (CXXDestructorDecl *Destructor =
2033 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2034 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002035 // FIXME: Add the temporary to the temporaries vector.
2036 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2037}
2038
Mike Stump1eb44332009-09-09 15:08:12 +00002039Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002040 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002041 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002043 if (ExprTemporaries.empty())
2044 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002046 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002047 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002048 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002049 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002050 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002052 return E;
2053}
2054
Mike Stump1eb44332009-09-09 15:08:12 +00002055Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002056Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2057 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2058 // Since this might be a postfix expression, get rid of ParenListExprs.
2059 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002061 Expr *BaseExpr = (Expr*)Base.get();
2062 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002064 QualType BaseType = BaseExpr->getType();
2065 if (BaseType->isDependentType()) {
2066 // FIXME: member of the current instantiation
2067 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 }
2096 }
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002098 if (BaseType->isPointerType())
2099 BaseType = BaseType->getPointeeType();
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 Gregorc68afe22009-09-03 21:38:09 +00002113 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002114 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00002115 // unqualified-id, and the type of the object expres- sion is of a class
2116 // type C (or of pointer to a class type C), the unqualified-id is looked
2117 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002118 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002119 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002120}
2121
Anders Carlssonec773872009-08-25 23:46:41 +00002122Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00002123Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00002124 SourceLocation OpLoc,
2125 tok::TokenKind OpKind,
2126 SourceLocation ClassNameLoc,
2127 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002128 const CXXScopeSpec &SS,
2129 bool HasTrailingLParen) {
2130 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00002131 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002132
Douglas Gregora71d8192009-09-04 17:36:40 +00002133 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00002134 if (isUnknownSpecialization(SS))
2135 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002136 ClassName);
2137 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00002138 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregordd62b152009-10-19 22:04:39 +00002139
2140 // FIXME: If Base is dependent, we might not be able to resolve it here.
Douglas Gregora71d8192009-09-04 17:36:40 +00002141 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00002142 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00002143 << ClassName;
2144 return ExprError();
2145 }
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Douglas Gregora71d8192009-09-04 17:36:40 +00002147 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002148 }
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Douglas Gregordd62b152009-10-19 22:04:39 +00002150 return ActOnDestructorReferenceExpr(S, move(Base), OpLoc, OpKind,
2151 SourceRange(ClassNameLoc),
2152 BaseType.getAsOpaquePtr(),
2153 SS, HasTrailingLParen);
2154}
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002155
Douglas Gregordd62b152009-10-19 22:04:39 +00002156Sema::OwningExprResult
2157Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
2158 SourceLocation OpLoc,
2159 tok::TokenKind OpKind,
2160 SourceRange TypeRange,
2161 TypeTy *T,
2162 const CXXScopeSpec &SS,
2163 bool HasTrailingLParen) {
2164 QualType Type = QualType::getFromOpaquePtr(T);
2165 CanQualType CanType = Context.getCanonicalType(Type);
2166 DeclarationName DtorName =
2167 Context.DeclarationNames.getCXXDestructorName(CanType);
2168
Douglas Gregora78c5c32009-09-04 18:29:40 +00002169 OwningExprResult Result
Douglas Gregordd62b152009-10-19 22:04:39 +00002170 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2171 TypeRange.getBegin(), DtorName, DeclPtrTy(),
2172 &SS);
Douglas Gregora78c5c32009-09-04 18:29:40 +00002173 if (Result.isInvalid() || HasTrailingLParen)
2174 return move(Result);
Douglas Gregordd62b152009-10-19 22:04:39 +00002175
Mike Stump1eb44332009-09-09 15:08:12 +00002176 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00002177 // immediately call them. Since the next token is not a '(', produce a
2178 // diagnostic and build the call now.
2179 Expr *E = (Expr *)Result.get();
Douglas Gregordd62b152009-10-19 22:04:39 +00002180 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(TypeRange.getEnd());
Douglas Gregora78c5c32009-09-04 18:29:40 +00002181 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2182 << isa<CXXPseudoDestructorExpr>(E)
2183 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregordd62b152009-10-19 22:04:39 +00002184
Mike Stump1eb44332009-09-09 15:08:12 +00002185 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002186 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00002187}
2188
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00002189Sema::OwningExprResult
2190Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2191 SourceLocation OpLoc,
2192 tok::TokenKind OpKind,
2193 SourceLocation ClassNameLoc,
2194 OverloadedOperatorKind OverOpKind,
2195 const CXXScopeSpec *SS) {
2196 if (SS && SS->isInvalid())
2197 return ExprError();
2198
2199 DeclarationName Name =
2200 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2201
2202 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2203 Name, DeclPtrTy(), SS);
2204}
2205
2206Sema::OwningExprResult
2207Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2208 SourceLocation OpLoc,
2209 tok::TokenKind OpKind,
2210 SourceLocation ClassNameLoc,
2211 TypeTy *Ty,
2212 const CXXScopeSpec *SS) {
2213 if (SS && SS->isInvalid())
2214 return ExprError();
2215
2216 //FIXME: Preserve type source info.
2217 QualType ConvType = GetTypeFromParser(Ty);
2218 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2219 DeclarationName ConvName =
2220 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2221
2222 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2223 ConvName, DeclPtrTy(), SS);
2224}
2225
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002226CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2227 CXXMethodDecl *Method) {
2228 MemberExpr *ME =
2229 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2230 SourceLocation(), Method->getType());
2231 QualType ResultType;
2232 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2233 ResultType = Conv->getConversionType().getNonReferenceType();
2234 else
2235 ResultType = Method->getResultType().getNonReferenceType();
2236
2237 CXXMemberCallExpr *CE =
2238 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2239 ResultType,
2240 SourceLocation());
2241 return CE;
2242}
2243
Anders Carlsson0aebc812009-09-09 21:33:21 +00002244Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2245 QualType Ty,
2246 CastExpr::CastKind Kind,
2247 CXXMethodDecl *Method,
2248 ExprArg Arg) {
2249 Expr *From = Arg.takeAs<Expr>();
2250
2251 switch (Kind) {
2252 default: assert(0 && "Unhandled cast kind!");
2253 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002254 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2255
2256 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2257 MultiExprArg(*this, (void **)&From, 1),
2258 CastLoc, ConstructorArgs))
2259 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002260
2261 OwningExprResult Result =
2262 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2263 move_arg(ConstructorArgs));
2264 if (Result.isInvalid())
2265 return ExprError();
2266
2267 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002268 }
2269
2270 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002271 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2272
2273 // Cast to base if needed.
2274 if (PerformObjectArgumentInitialization(From, Method))
2275 return ExprError();
2276
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002277 // Create an implicit call expr that calls it.
2278 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002279 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002280 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002281 }
2282}
2283
Anders Carlsson165a0a02009-05-17 18:41:29 +00002284Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2285 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002286 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002287 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002288 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002289
Anders Carlssonec773872009-08-25 23:46:41 +00002290
Anders Carlsson165a0a02009-05-17 18:41:29 +00002291 return Owned(FullExpr);
2292}
Douglas Gregore961afb2009-10-22 07:08:30 +00002293
2294/// \brief Determine whether a reference to the given declaration in the
2295/// current context is an implicit member access
2296/// (C++ [class.mfct.non-static]p2).
2297///
2298/// FIXME: Should Objective-C also use this approach?
2299///
2300/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2301/// name of the declaration referenced.
2302///
2303/// \param D the declaration being referenced from the current scope.
2304///
2305/// \param NameLoc the location of the name in the source.
2306///
2307/// \param ThisType if the reference to this declaration is an implicit member
2308/// access, will be set to the type of the "this" pointer to be used when
2309/// building that implicit member access.
2310///
2311/// \param MemberType if the reference to this declaration is an implicit
2312/// member access, will be set to the type of the member being referenced
2313/// (for use at the type of the resulting member access expression).
2314///
2315/// \returns true if this is an implicit member reference (in which case
2316/// \p ThisType and \p MemberType will be set), or false if it is not an
2317/// implicit member reference.
2318bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2319 SourceLocation NameLoc, QualType &ThisType,
2320 QualType &MemberType) {
2321 // If this isn't a C++ method, then it isn't an implicit member reference.
2322 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2323 if (!MD || MD->isStatic())
2324 return false;
2325
2326 // C++ [class.mfct.nonstatic]p2:
2327 // [...] if name lookup (3.4.1) resolves the name in the
2328 // id-expression to a nonstatic nontype member of class X or of
2329 // a base class of X, the id-expression is transformed into a
2330 // class member access expression (5.2.5) using (*this) (9.3.2)
2331 // as the postfix-expression to the left of the '.' operator.
2332 DeclContext *Ctx = 0;
2333 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2334 Ctx = FD->getDeclContext();
2335 MemberType = FD->getType();
2336
2337 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2338 MemberType = RefType->getPointeeType();
2339 else if (!FD->isMutable())
2340 MemberType
2341 = Context.getQualifiedType(MemberType,
2342 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2343 } else {
2344 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2345 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2346 FunctionTemplateDecl *FunTmpl = 0;
2347 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2348 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2349
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002350 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002351 if (Method && !Method->isStatic()) {
2352 Ctx = Method->getParent();
2353 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2354 MemberType = Method->getType();
2355 else
2356 MemberType = Context.OverloadTy;
2357 break;
2358 }
2359 }
2360 }
2361
2362 if (!Ctx || !Ctx->isRecord())
2363 return false;
2364
2365 // Determine whether the declaration(s) we found are actually in a base
2366 // class. If not, this isn't an implicit member reference.
2367 ThisType = MD->getThisType(Context);
2368 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2369 QualType ClassType
2370 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2371 return Context.hasSameType(CtxType, ClassType) ||
2372 IsDerivedFrom(ClassType, CtxType);
2373}
2374