blob: 6f26ea1eeef92554bde94cd6138b6b8f70a321d9 [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;
315 unsigned Skip = 0;
316 // If the specified type is an array, unwrap it and save the expression.
317 if (D.getNumTypeObjects() > 0 &&
318 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
319 DeclaratorChunk &Chunk = D.getTypeObject(0);
320 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000321 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
322 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000323 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000324 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
325 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000326 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
327 Skip = 1;
328 }
329
Douglas Gregor043cad22009-09-11 00:18:58 +0000330 // Every dimension shall be of constant size.
331 if (D.getNumTypeObjects() > 0 &&
332 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
333 for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
334 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
335 break;
336
337 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
338 if (Expr *NumElts = (Expr *)Array.NumElts) {
339 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
340 !NumElts->isIntegerConstantExpr(Context)) {
341 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
342 << NumElts->getSourceRange();
343 return ExprError();
344 }
345 }
346 }
347 }
348
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000349 //FIXME: Store DeclaratorInfo in CXXNew expression.
350 DeclaratorInfo *DInfo = 0;
351 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000352 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000353 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000354
Mike Stump1eb44332009-09-09 15:08:12 +0000355 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000356 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000357 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000358 PlacementRParen,
359 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000360 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000361 D.getSourceRange().getBegin(),
362 D.getSourceRange(),
363 Owned(ArraySize),
364 ConstructorLParen,
365 move(ConstructorArgs),
366 ConstructorRParen);
367}
368
Mike Stump1eb44332009-09-09 15:08:12 +0000369Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000370Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
371 SourceLocation PlacementLParen,
372 MultiExprArg PlacementArgs,
373 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000374 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000375 QualType AllocType,
376 SourceLocation TypeLoc,
377 SourceRange TypeRange,
378 ExprArg ArraySizeE,
379 SourceLocation ConstructorLParen,
380 MultiExprArg ConstructorArgs,
381 SourceLocation ConstructorRParen) {
382 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000384
Douglas Gregor3433cf72009-05-21 00:00:09 +0000385 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000386
387 // That every array dimension except the first is constant was already
388 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000389
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000390 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
391 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000392 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000393 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000394 QualType SizeType = ArraySize->getType();
395 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
397 diag::err_array_size_not_integral)
398 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000399 // Let's see if this is a constant < 0. If so, we reject it out of hand.
400 // We don't care about special rules, so we tell the machinery it's not
401 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000402 if (!ArraySize->isValueDependent()) {
403 llvm::APSInt Value;
404 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
405 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000406 llvm::APInt::getNullValue(Value.getBitWidth()),
407 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000408 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
409 diag::err_typecheck_negative_array_size)
410 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000411 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000412 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000413
Eli Friedman73c39ab2009-10-20 08:27:19 +0000414 ImpCastExprToType(ArraySize, Context.getSizeType(),
415 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000416 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000417
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000418 FunctionDecl *OperatorNew = 0;
419 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000420 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
421 unsigned NumPlaceArgs = PlacementArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000422
Sebastian Redl28507842009-02-26 14:39:58 +0000423 if (!AllocType->isDependentType() &&
424 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
425 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000426 SourceRange(PlacementLParen, PlacementRParen),
427 UseGlobal, AllocType, ArraySize, PlaceArgs,
428 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000430
431 bool Init = ConstructorLParen.isValid();
432 // --- Choosing a constructor ---
433 // C++ 5.3.4p15
434 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
435 // the object is not initialized. If the object, or any part of it, is
436 // const-qualified, it's an error.
437 // 2) If T is a POD and there's an empty initializer, the object is value-
438 // initialized.
439 // 3) If T is a POD and there's one initializer argument, the object is copy-
440 // constructed.
441 // 4) If T is a POD and there's more initializer arguments, it's an error.
442 // 5) If T is not a POD, the initializer arguments are used as constructor
443 // arguments.
444 //
445 // Or by the C++0x formulation:
446 // 1) If there's no initializer, the object is default-initialized according
447 // to C++0x rules.
448 // 2) Otherwise, the object is direct-initialized.
449 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000450 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000451 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000452 unsigned NumConsArgs = ConstructorArgs.size();
Douglas Gregor089407b2009-10-17 21:40:42 +0000453
454 if (AllocType->isDependentType() ||
455 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000456 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000457 } else if ((RT = AllocType->getAs<RecordType>()) &&
458 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000459 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
460
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000461 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000462 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000463 TypeLoc,
464 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000465 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000466 NumConsArgs != 0 ? IK_Direct : IK_Default,
467 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000468 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000469 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000470
471 // Take the converted constructor arguments and use them for the new
472 // expression.
473 NumConsArgs = ConvertedConstructorArgs.size();
474 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000475 } else {
476 if (!Init) {
477 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000478 if (AllocType.isConstQualified())
479 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000480 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000481 } else if (NumConsArgs == 0) {
482 // Object is value-initialized. Do nothing.
483 } else if (NumConsArgs == 1) {
484 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000485 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000486 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000487 DeclarationName() /*AllocType.getAsString()*/,
488 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000489 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000490 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000491 return ExprError(Diag(StartLoc,
492 diag::err_builtin_direct_init_more_than_one_arg)
493 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000494 }
495 }
496
497 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000498
Sebastian Redlf53597f2009-03-15 17:47:39 +0000499 PlacementArgs.release();
500 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000501 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000502 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000503 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000504 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000505 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000506}
507
508/// CheckAllocatedType - Checks that a type is suitable as the allocated type
509/// in a new-expression.
510/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000512 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000513 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
514 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000515 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000516 return Diag(Loc, diag::err_bad_new_type)
517 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000518 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000519 return Diag(Loc, diag::err_bad_new_type)
520 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000521 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000522 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000523 PDiag(diag::err_new_incomplete_type)
524 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000525 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000526 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000527 diag::err_allocation_of_abstract_type))
528 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000529
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000530 return false;
531}
532
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000533/// FindAllocationFunctions - Finds the overloads of operator new and delete
534/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000535bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
536 bool UseGlobal, QualType AllocType,
537 bool IsArray, Expr **PlaceArgs,
538 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000539 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000540 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000541 // --- Choosing an allocation function ---
542 // C++ 5.3.4p8 - 14 & 18
543 // 1) If UseGlobal is true, only look in the global scope. Else, also look
544 // in the scope of the allocated class.
545 // 2) If an array size is given, look for operator new[], else look for
546 // operator new.
547 // 3) The first argument is always size_t. Append the arguments from the
548 // placement form.
549 // FIXME: Also find the appropriate delete operator.
550
551 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
552 // We don't care about the actual value of this argument.
553 // FIXME: Should the Sema create the expression and embed it in the syntax
554 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000555 IntegerLiteral Size(llvm::APInt::getNullValue(
556 Context.Target.getPointerWidth(0)),
557 Context.getSizeType(),
558 SourceLocation());
559 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000560 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
561
562 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
563 IsArray ? OO_Array_New : OO_New);
564 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000565 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000566 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000567 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000568 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000569 AllocArgs.size(), Record, /*AllowMissing=*/true,
570 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000571 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000572 }
573 if (!OperatorNew) {
574 // Didn't find a member overload. Look for a global one.
575 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000576 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000577 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000578 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
579 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000580 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000581 }
582
Anders Carlssond9583892009-05-31 20:26:12 +0000583 // FindAllocationOverload can change the passed in arguments, so we need to
584 // copy them back.
585 if (NumPlaceArgs > 0)
586 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000588 return false;
589}
590
Sebastian Redl7f662392008-12-04 22:20:51 +0000591/// FindAllocationOverload - Find an fitting overload for the allocation
592/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000593bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
594 DeclarationName Name, Expr** Args,
595 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000596 bool AllowMissing, FunctionDecl *&Operator) {
John McCallf36e02d2009-10-09 21:13:30 +0000597 LookupResult R;
598 LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
599 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000600 if (AllowMissing)
601 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000602 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000603 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000604 }
605
John McCallf36e02d2009-10-09 21:13:30 +0000606 // FIXME: handle ambiguity
607
Sebastian Redl7f662392008-12-04 22:20:51 +0000608 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000609 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
610 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000611 // Even member operator new/delete are implicitly treated as
612 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000613 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000614 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
615 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000616 continue;
617 }
618
619 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000620 }
621
622 // Do the resolution.
623 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000624 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000625 case OR_Success: {
626 // Got one!
627 FunctionDecl *FnDecl = Best->Function;
628 // The first argument is size_t, and the first parameter must be size_t,
629 // too. This is checked on declaration and can be assumed. (It can't be
630 // asserted on, though, since invalid decls are left in there.)
Douglas Gregor90916562009-09-29 18:16:17 +0000631 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000632 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000633 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 FnDecl->getParamDecl(i)->getType(),
635 "passing"))
636 return true;
637 }
638 Operator = FnDecl;
639 return false;
640 }
641
642 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000643 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000644 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000645 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
646 return true;
647
648 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000649 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000650 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000651 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
652 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000653
654 case OR_Deleted:
655 Diag(StartLoc, diag::err_ovl_deleted_call)
656 << Best->Function->isDeleted()
657 << Name << Range;
658 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
659 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000660 }
661 assert(false && "Unreachable, bad result from BestViableFunction");
662 return true;
663}
664
665
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000666/// DeclareGlobalNewDelete - Declare the global forms of operator new and
667/// delete. These are:
668/// @code
669/// void* operator new(std::size_t) throw(std::bad_alloc);
670/// void* operator new[](std::size_t) throw(std::bad_alloc);
671/// void operator delete(void *) throw();
672/// void operator delete[](void *) throw();
673/// @endcode
674/// Note that the placement and nothrow forms of new are *not* implicitly
675/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000676void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000677 if (GlobalNewDeleteDeclared)
678 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000679
680 // C++ [basic.std.dynamic]p2:
681 // [...] The following allocation and deallocation functions (18.4) are
682 // implicitly declared in global scope in each translation unit of a
683 // program
684 //
685 // void* operator new(std::size_t) throw(std::bad_alloc);
686 // void* operator new[](std::size_t) throw(std::bad_alloc);
687 // void operator delete(void*) throw();
688 // void operator delete[](void*) throw();
689 //
690 // These implicit declarations introduce only the function names operator
691 // new, operator new[], operator delete, operator delete[].
692 //
693 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
694 // "std" or "bad_alloc" as necessary to form the exception specification.
695 // However, we do not make these implicit declarations visible to name
696 // lookup.
697 if (!StdNamespace) {
698 // The "std" namespace has not yet been defined, so build one implicitly.
699 StdNamespace = NamespaceDecl::Create(Context,
700 Context.getTranslationUnitDecl(),
701 SourceLocation(),
702 &PP.getIdentifierTable().get("std"));
703 StdNamespace->setImplicit(true);
704 }
705
706 if (!StdBadAlloc) {
707 // The "std::bad_alloc" class has not yet been declared, so build it
708 // implicitly.
709 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
710 StdNamespace,
711 SourceLocation(),
712 &PP.getIdentifierTable().get("bad_alloc"),
713 SourceLocation(), 0);
714 StdBadAlloc->setImplicit(true);
715 }
716
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000717 GlobalNewDeleteDeclared = true;
718
719 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
720 QualType SizeT = Context.getSizeType();
721
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000722 DeclareGlobalAllocationFunction(
723 Context.DeclarationNames.getCXXOperatorName(OO_New),
724 VoidPtr, SizeT);
725 DeclareGlobalAllocationFunction(
726 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
727 VoidPtr, SizeT);
728 DeclareGlobalAllocationFunction(
729 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
730 Context.VoidTy, VoidPtr);
731 DeclareGlobalAllocationFunction(
732 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
733 Context.VoidTy, VoidPtr);
734}
735
736/// DeclareGlobalAllocationFunction - Declares a single implicit global
737/// allocation function if it doesn't already exist.
738void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000739 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000740 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
741
742 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000743 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000744 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000745 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000746 Alloc != AllocEnd; ++Alloc) {
747 // FIXME: Do we need to check for default arguments here?
748 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
749 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000750 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000751 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000752 }
753 }
754
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000755 QualType BadAllocType;
756 bool HasBadAllocExceptionSpec
757 = (Name.getCXXOverloadedOperator() == OO_New ||
758 Name.getCXXOverloadedOperator() == OO_Array_New);
759 if (HasBadAllocExceptionSpec) {
760 assert(StdBadAlloc && "Must have std::bad_alloc declared");
761 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
762 }
763
764 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
765 true, false,
766 HasBadAllocExceptionSpec? 1 : 0,
767 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000768 FunctionDecl *Alloc =
769 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000770 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000771 Alloc->setImplicit();
772 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000773 0, Argument, /*DInfo=*/0,
774 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000775 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000776
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000777 // FIXME: Also add this declaration to the IdentifierResolver, but
778 // make sure it is at the end of the chain to coincide with the
779 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000780 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000781}
782
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000783/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
784/// @code ::delete ptr; @endcode
785/// or
786/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000787Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000788Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000789 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000790 // C++ [expr.delete]p1:
791 // The operand shall have a pointer type, or a class type having a single
792 // conversion function to a pointer type. The result has type void.
793 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000794 // DR599 amends "pointer type" to "pointer to object type" in both cases.
795
Anders Carlssond67c4c32009-08-16 20:29:29 +0000796 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Sebastian Redlf53597f2009-03-15 17:47:39 +0000798 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000799 if (!Ex->isTypeDependent()) {
800 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000801
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000802 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000803 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000804 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
805 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000806 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000807
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000808 for (OverloadedFunctionDecl::function_iterator
809 Func = Conversions->function_begin(),
810 FuncEnd = Conversions->function_end();
811 Func != FuncEnd; ++Func) {
812 // Skip over templated conversion functions; they aren't considered.
813 if (isa<FunctionTemplateDecl>(*Func))
814 continue;
815
816 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
817
818 QualType ConvType = Conv->getConversionType().getNonReferenceType();
819 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
820 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000821 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000822 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000823 if (ObjectPtrConversions.size() == 1) {
824 // We have a single conversion to a pointer-to-object type. Perform
825 // that conversion.
826 Operand.release();
827 if (!PerformImplicitConversion(Ex,
828 ObjectPtrConversions.front()->getConversionType(),
829 "converting")) {
830 Operand = Owned(Ex);
831 Type = Ex->getType();
832 }
833 }
834 else if (ObjectPtrConversions.size() > 1) {
835 Diag(StartLoc, diag::err_ambiguous_delete_operand)
836 << Type << Ex->getSourceRange();
837 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
838 CXXConversionDecl *Conv = ObjectPtrConversions[i];
839 Diag(Conv->getLocation(), diag::err_ovl_candidate);
840 }
841 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000842 }
Sebastian Redl28507842009-02-26 14:39:58 +0000843 }
844
Sebastian Redlf53597f2009-03-15 17:47:39 +0000845 if (!Type->isPointerType())
846 return ExprError(Diag(StartLoc, diag::err_delete_operand)
847 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000848
Ted Kremenek6217b802009-07-29 21:53:49 +0000849 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000850 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000851 return ExprError(Diag(StartLoc, diag::err_delete_operand)
852 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000853 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000854 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000855 PDiag(diag::warn_delete_incomplete)
856 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000857 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000858
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000859 // C++ [expr.delete]p2:
860 // [Note: a pointer to a const type can be the operand of a
861 // delete-expression; it is not necessary to cast away the constness
862 // (5.2.11) of the pointer expression before it is used as the operand
863 // of the delete-expression. ]
864 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
865 CastExpr::CK_NoOp);
866
867 // Update the operand.
868 Operand.take();
869 Operand = ExprArg(*this, Ex);
870
Anders Carlssond67c4c32009-08-16 20:29:29 +0000871 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
872 ArrayForm ? OO_Array_Delete : OO_Delete);
873
874 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000875 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000876 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
Douglas Gregor90916562009-09-29 18:16:17 +0000877
878 // Try to find operator delete/operator delete[] in class scope.
John McCallf36e02d2009-10-09 21:13:30 +0000879 LookupResult Found;
880 LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
Douglas Gregor90916562009-09-29 18:16:17 +0000881 // FIXME: Diagnose ambiguity properly
882 assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
883 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
884 F != FEnd; ++F) {
885 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
886 if (Delete->isUsualDeallocationFunction()) {
887 OperatorDelete = Delete;
888 break;
889 }
890 }
891
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000892 if (!Record->hasTrivialDestructor())
893 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000894 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000895 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Anders Carlssond67c4c32009-08-16 20:29:29 +0000898 if (!OperatorDelete) {
899 // Didn't find a member overload. Look for a global one.
900 DeclareGlobalNewDelete();
901 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000902 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000903 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000904 OperatorDelete))
905 return ExprError();
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Sebastian Redl28507842009-02-26 14:39:58 +0000908 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000909 }
910
Sebastian Redlf53597f2009-03-15 17:47:39 +0000911 Operand.release();
912 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000913 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000914}
915
916
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000917/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
918/// C++ if/switch/while/for statement.
919/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000920Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000921Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
922 Declarator &D,
923 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000924 ExprArg AssignExprVal) {
925 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000926
927 // C++ 6.4p2:
928 // The declarator shall not specify a function or an array.
929 // The type-specifier-seq shall not contain typedef and shall not declare a
930 // new class or enumeration.
931
932 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
933 "Parser allowed 'typedef' as storage class of condition decl.");
934
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000935 // FIXME: Store DeclaratorInfo in the expression.
936 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000937 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000938 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000940 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
941 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
942 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000943 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
944 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000945 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000946 Diag(StartLoc, diag::err_invalid_use_of_array_type)
947 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000948 } else if (OwnedTag && OwnedTag->isDefinition()) {
949 // The type-specifier-seq shall not declare a new class or enumeration.
950 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000951 }
952
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000953 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000954 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000955 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000956 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000957
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000958 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000959 // We know that the decl had to be a VarDecl because that is the only type of
960 // decl that can be assigned and the grammar requires an '='.
961 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
962 VD->setDeclaredInCondition(true);
963 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000964}
965
966/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
967bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
968 // C++ 6.4p4:
969 // The value of a condition that is an initialized declaration in a statement
970 // other than a switch statement is the value of the declared variable
971 // implicitly converted to type bool. If that conversion is ill-formed, the
972 // program is ill-formed.
973 // The value of a condition that is an expression is the value of the
974 // expression, implicitly converted to bool.
975 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000976 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000977}
Douglas Gregor77a52232008-09-12 00:47:35 +0000978
979/// Helper function to determine whether this is the (deprecated) C++
980/// conversion from a string literal to a pointer to non-const char or
981/// non-const wchar_t (for narrow and wide string literals,
982/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000983bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000984Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
985 // Look inside the implicit cast, if it exists.
986 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
987 From = Cast->getSubExpr();
988
989 // A string literal (2.13.4) that is not a wide string literal can
990 // be converted to an rvalue of type "pointer to char"; a wide
991 // string literal can be converted to an rvalue of type "pointer
992 // to wchar_t" (C++ 4.2p2).
993 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000994 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000995 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000996 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000997 // This conversion is considered only when there is an
998 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +0000999 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001000 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1001 (!StrLit->isWide() &&
1002 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1003 ToPointeeType->getKind() == BuiltinType::Char_S))))
1004 return true;
1005 }
1006
1007 return false;
1008}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001009
1010/// PerformImplicitConversion - Perform an implicit conversion of the
1011/// expression From to the type ToType. Returns true if there was an
1012/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001013/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001014/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001015/// explicit user-defined conversions are permitted. @p Elidable should be true
1016/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1017/// resolution works differently in that case.
1018bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001019Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001020 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001021 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001022 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001023 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1024 Elidable, ICS);
1025}
1026
1027bool
1028Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1029 const char *Flavor, bool AllowExplicit,
1030 bool Elidable,
1031 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001032 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1033 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001034 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001035 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001036 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001037 /*ForceRValue=*/true,
1038 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001039 }
1040 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001041 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001042 /*SuppressUserConversions=*/false,
1043 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001044 /*ForceRValue=*/false,
1045 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001046 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001047 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1048}
1049
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001050/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1051/// for the derived to base conversion of the expression 'From'. All
1052/// necessary information is passed in ICS.
1053bool
1054Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1055 const ImplicitConversionSequence& ICS,
1056 const char *Flavor) {
1057 QualType BaseType =
1058 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1059 // Must do additional defined to base conversion.
1060 QualType DerivedType =
1061 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1062
1063 From = new (Context) ImplicitCastExpr(
1064 DerivedType.getNonReferenceType(),
1065 CastKind,
1066 From,
1067 DerivedType->isLValueReferenceType());
1068 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1069 CastExpr::CK_DerivedToBase, From,
1070 BaseType->isLValueReferenceType());
1071 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1072 OwningExprResult FromResult =
1073 BuildCXXConstructExpr(
1074 ICS.UserDefined.After.CopyConstructor->getLocation(),
1075 BaseType,
1076 ICS.UserDefined.After.CopyConstructor,
1077 MultiExprArg(*this, (void **)&From, 1));
1078 if (FromResult.isInvalid())
1079 return true;
1080 From = FromResult.takeAs<Expr>();
1081 return false;
1082}
1083
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001084/// PerformImplicitConversion - Perform an implicit conversion of the
1085/// expression From to the type ToType using the pre-computed implicit
1086/// conversion sequence ICS. Returns true if there was an error, false
1087/// otherwise. The expression From is replaced with the converted
1088/// expression. Flavor is the kind of conversion we're performing,
1089/// used in the error message.
1090bool
1091Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1092 const ImplicitConversionSequence &ICS,
1093 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001094 switch (ICS.ConversionKind) {
1095 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001096 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001097 return true;
1098 break;
1099
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001100 case ImplicitConversionSequence::UserDefinedConversion: {
1101
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001102 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1103 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001104 QualType BeforeToType;
1105 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001106 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001107
1108 // If the user-defined conversion is specified by a conversion function,
1109 // the initial standard conversion sequence converts the source type to
1110 // the implicit object parameter of the conversion function.
1111 BeforeToType = Context.getTagDeclType(Conv->getParent());
1112 } else if (const CXXConstructorDecl *Ctor =
1113 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001114 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001115
1116 // If the user-defined conversion is specified by a constructor, the
1117 // initial standard conversion sequence converts the source type to the
1118 // type required by the argument of the constructor
1119 BeforeToType = Ctor->getParamDecl(0)->getType();
1120 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001121 else
1122 assert(0 && "Unknown conversion function kind!");
1123
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001124 if (PerformImplicitConversion(From, BeforeToType,
1125 ICS.UserDefined.Before, "converting"))
1126 return true;
1127
Anders Carlsson0aebc812009-09-09 21:33:21 +00001128 OwningExprResult CastArg
1129 = BuildCXXCastArgument(From->getLocStart(),
1130 ToType.getNonReferenceType(),
1131 CastKind, cast<CXXMethodDecl>(FD),
1132 Owned(From));
1133
1134 if (CastArg.isInvalid())
1135 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001136
1137 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1138 ICS.UserDefined.After.CopyConstructor) {
1139 From = CastArg.takeAs<Expr>();
1140 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1141 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001142
1143 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1144 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1145 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001146
Anders Carlsson626c2d62009-09-15 05:49:31 +00001147 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001148 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001149 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001150 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001151 }
1152
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001153 case ImplicitConversionSequence::EllipsisConversion:
1154 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001156
1157 case ImplicitConversionSequence::BadConversion:
1158 return true;
1159 }
1160
1161 // Everything went well.
1162 return false;
1163}
1164
1165/// PerformImplicitConversion - Perform an implicit conversion of the
1166/// expression From to the type ToType by following the standard
1167/// conversion sequence SCS. Returns true if there was an error, false
1168/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001169/// expression. Flavor is the context in which we're performing this
1170/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001171bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001172Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001173 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001174 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001175 // Overall FIXME: we are recomputing too many types here and doing far too
1176 // much extra work. What this means is that we need to keep track of more
1177 // information that is computed when we try the implicit conversion initially,
1178 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001179 QualType FromType = From->getType();
1180
Douglas Gregor225c41e2008-11-03 19:09:14 +00001181 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001182 // FIXME: When can ToType be a reference type?
1183 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001184 if (SCS.Second == ICK_Derived_To_Base) {
1185 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1186 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1187 MultiExprArg(*this, (void **)&From, 1),
1188 /*FIXME:ConstructLoc*/SourceLocation(),
1189 ConstructorArgs))
1190 return true;
1191 OwningExprResult FromResult =
1192 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1193 ToType, SCS.CopyConstructor,
1194 move_arg(ConstructorArgs));
1195 if (FromResult.isInvalid())
1196 return true;
1197 From = FromResult.takeAs<Expr>();
1198 return false;
1199 }
Mike Stump1eb44332009-09-09 15:08:12 +00001200 OwningExprResult FromResult =
1201 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1202 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001203 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001205 if (FromResult.isInvalid())
1206 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001208 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001209 return false;
1210 }
1211
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001212 // Perform the first implicit conversion.
1213 switch (SCS.First) {
1214 case ICK_Identity:
1215 case ICK_Lvalue_To_Rvalue:
1216 // Nothing to do.
1217 break;
1218
1219 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001220 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001221 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001222 break;
1223
1224 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001225 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001226 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1227 if (!Fn)
1228 return true;
1229
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001230 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1231 return true;
1232
Anders Carlsson96ad5332009-10-21 17:16:23 +00001233 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001234 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001235
Sebastian Redl759986e2009-10-17 20:50:27 +00001236 // If there's already an address-of operator in the expression, we have
1237 // the right type already, and the code below would just introduce an
1238 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001239 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001240 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001241 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001242 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001243 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001244 break;
1245
1246 default:
1247 assert(false && "Improper first standard conversion");
1248 break;
1249 }
1250
1251 // Perform the second implicit conversion
1252 switch (SCS.Second) {
1253 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001254 // If both sides are functions (or pointers/references to them), there could
1255 // be incompatible exception declarations.
1256 if (CheckExceptionSpecCompatibility(From, ToType))
1257 return true;
1258 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001259 break;
1260
1261 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001262 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001263 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1264 break;
1265
1266 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001267 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001268 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1269 break;
1270
1271 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001272 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001273 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1274 break;
1275
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001276 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001277 if (ToType->isFloatingType())
1278 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1279 else
1280 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1281 break;
1282
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001283 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001284 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1285 break;
1286
Douglas Gregorf9201e02009-02-11 23:02:49 +00001287 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001288 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001289 break;
1290
Anders Carlsson61faec12009-09-12 04:46:44 +00001291 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001292 if (SCS.IncompatibleObjC) {
1293 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001294 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001295 diag::ext_typecheck_convert_incompatible_pointer)
1296 << From->getType() << ToType << Flavor
1297 << From->getSourceRange();
1298 }
1299
Anders Carlsson61faec12009-09-12 04:46:44 +00001300
1301 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1302 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001303 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001304 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001305 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001306 }
1307
1308 case ICK_Pointer_Member: {
1309 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1310 if (CheckMemberPointerConversion(From, ToType, Kind))
1311 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001312 if (CheckExceptionSpecCompatibility(From, ToType))
1313 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001314 ImpCastExprToType(From, ToType, Kind);
1315 break;
1316 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001317 case ICK_Boolean_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001318 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001319 break;
1320
1321 default:
1322 assert(false && "Improper second standard conversion");
1323 break;
1324 }
1325
1326 switch (SCS.Third) {
1327 case ICK_Identity:
1328 // Nothing to do.
1329 break;
1330
1331 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001332 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1333 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001334 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001335 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001336 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001337 break;
1338
1339 default:
1340 assert(false && "Improper second standard conversion");
1341 break;
1342 }
1343
1344 return false;
1345}
1346
Sebastian Redl64b45f72009-01-05 20:52:13 +00001347Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1348 SourceLocation KWLoc,
1349 SourceLocation LParen,
1350 TypeTy *Ty,
1351 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001352 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001354 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1355 // all traits except __is_class, __is_enum and __is_union require a the type
1356 // to be complete.
1357 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001358 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001359 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001360 return ExprError();
1361 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001362
1363 // There is no point in eagerly computing the value. The traits are designed
1364 // to be used from type trait templates, so Ty will be a template parameter
1365 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001366 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1367 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001368}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001369
1370QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001371 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001372 const char *OpSpelling = isIndirect ? "->*" : ".*";
1373 // C++ 5.5p2
1374 // The binary operator .* [p3: ->*] binds its second operand, which shall
1375 // be of type "pointer to member of T" (where T is a completely-defined
1376 // class type) [...]
1377 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001378 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001379 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001380 Diag(Loc, diag::err_bad_memptr_rhs)
1381 << OpSpelling << RType << rex->getSourceRange();
1382 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001383 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001384
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001385 QualType Class(MemPtr->getClass(), 0);
1386
1387 // C++ 5.5p2
1388 // [...] to its first operand, which shall be of class T or of a class of
1389 // which T is an unambiguous and accessible base class. [p3: a pointer to
1390 // such a class]
1391 QualType LType = lex->getType();
1392 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001393 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001394 LType = Ptr->getPointeeType().getNonReferenceType();
1395 else {
1396 Diag(Loc, diag::err_bad_memptr_lhs)
1397 << OpSpelling << 1 << LType << lex->getSourceRange();
1398 return QualType();
1399 }
1400 }
1401
1402 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1403 Context.getCanonicalType(LType).getUnqualifiedType()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001404 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1405 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001406 // FIXME: Would it be useful to print full ambiguity paths, or is that
1407 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001408 if (!IsDerivedFrom(LType, Class, Paths) ||
1409 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1410 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1411 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1412 return QualType();
1413 }
1414 }
1415
1416 // C++ 5.5p2
1417 // The result is an object or a function of the type specified by the
1418 // second operand.
1419 // The cv qualifiers are the union of those in the pointer and the left side,
1420 // in accordance with 5.5p5 and 5.2.5.
1421 // FIXME: This returns a dereferenced member function pointer as a normal
1422 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001423 // calling them. There's also a GCC extension to get a function pointer to the
1424 // thing, which is another complication, because this type - unlike the type
1425 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001426 // argument.
1427 // We probably need a "MemberFunctionClosureType" or something like that.
1428 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001429 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001430 return Result;
1431}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001432
1433/// \brief Get the target type of a standard or user-defined conversion.
1434static QualType TargetType(const ImplicitConversionSequence &ICS) {
1435 assert((ICS.ConversionKind ==
1436 ImplicitConversionSequence::StandardConversion ||
1437 ICS.ConversionKind ==
1438 ImplicitConversionSequence::UserDefinedConversion) &&
1439 "function only valid for standard or user-defined conversions");
1440 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1441 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1442 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1443}
1444
1445/// \brief Try to convert a type to another according to C++0x 5.16p3.
1446///
1447/// This is part of the parameter validation for the ? operator. If either
1448/// value operand is a class type, the two operands are attempted to be
1449/// converted to each other. This function does the conversion in one direction.
1450/// It emits a diagnostic and returns true only if it finds an ambiguous
1451/// conversion.
1452static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1453 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001454 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001455 // C++0x 5.16p3
1456 // The process for determining whether an operand expression E1 of type T1
1457 // can be converted to match an operand expression E2 of type T2 is defined
1458 // as follows:
1459 // -- If E2 is an lvalue:
1460 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1461 // E1 can be converted to match E2 if E1 can be implicitly converted to
1462 // type "lvalue reference to T2", subject to the constraint that in the
1463 // conversion the reference must bind directly to E1.
1464 if (!Self.CheckReferenceInit(From,
1465 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001466 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001467 /*SuppressUserConversions=*/false,
1468 /*AllowExplicit=*/false,
1469 /*ForceRValue=*/false,
1470 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001471 {
1472 assert((ICS.ConversionKind ==
1473 ImplicitConversionSequence::StandardConversion ||
1474 ICS.ConversionKind ==
1475 ImplicitConversionSequence::UserDefinedConversion) &&
1476 "expected a definite conversion");
1477 bool DirectBinding =
1478 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1479 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1480 if (DirectBinding)
1481 return false;
1482 }
1483 }
1484 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1485 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1486 // -- if E1 and E2 have class type, and the underlying class types are
1487 // the same or one is a base class of the other:
1488 QualType FTy = From->getType();
1489 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001490 const RecordType *FRec = FTy->getAs<RecordType>();
1491 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001492 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1493 if (FRec && TRec && (FRec == TRec ||
1494 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1495 // E1 can be converted to match E2 if the class of T2 is the
1496 // same type as, or a base class of, the class of T1, and
1497 // [cv2 > cv1].
1498 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1499 // Could still fail if there's no copy constructor.
1500 // FIXME: Is this a hard error then, or just a conversion failure? The
1501 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001502 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001503 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001504 /*ForceRValue=*/false,
1505 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001506 }
1507 } else {
1508 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1509 // implicitly converted to the type that expression E2 would have
1510 // if E2 were converted to an rvalue.
1511 // First find the decayed type.
1512 if (TTy->isFunctionType())
1513 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001514 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001515 TTy = Self.Context.getArrayDecayedType(TTy);
1516
1517 // Now try the implicit conversion.
1518 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001519 ICS = Self.TryImplicitConversion(From, TTy,
1520 /*SuppressUserConversions=*/false,
1521 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001522 /*ForceRValue=*/false,
1523 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001524 }
1525 return false;
1526}
1527
1528/// \brief Try to find a common type for two according to C++0x 5.16p5.
1529///
1530/// This is part of the parameter validation for the ? operator. If either
1531/// value operand is a class type, overload resolution is used to find a
1532/// conversion to a common type.
1533static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1534 SourceLocation Loc) {
1535 Expr *Args[2] = { LHS, RHS };
1536 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001537 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001538
1539 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001540 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001541 case Sema::OR_Success:
1542 // We found a match. Perform the conversions on the arguments and move on.
1543 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1544 Best->Conversions[0], "converting") ||
1545 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1546 Best->Conversions[1], "converting"))
1547 break;
1548 return false;
1549
1550 case Sema::OR_No_Viable_Function:
1551 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1552 << LHS->getType() << RHS->getType()
1553 << LHS->getSourceRange() << RHS->getSourceRange();
1554 return true;
1555
1556 case Sema::OR_Ambiguous:
1557 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1558 << LHS->getType() << RHS->getType()
1559 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001560 // FIXME: Print the possible common types by printing the return types of
1561 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001562 break;
1563
1564 case Sema::OR_Deleted:
1565 assert(false && "Conditional operator has only built-in overloads");
1566 break;
1567 }
1568 return true;
1569}
1570
Sebastian Redl76458502009-04-17 16:30:52 +00001571/// \brief Perform an "extended" implicit conversion as returned by
1572/// TryClassUnification.
1573///
1574/// TryClassUnification generates ICSs that include reference bindings.
1575/// PerformImplicitConversion is not suitable for this; it chokes if the
1576/// second part of a standard conversion is ICK_DerivedToBase. This function
1577/// handles the reference binding specially.
1578static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001579 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001580 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1581 ICS.Standard.ReferenceBinding) {
1582 assert(ICS.Standard.DirectBinding &&
1583 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001584 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1585 // redoing all the work.
1586 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001587 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001588 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001589 /*SuppressUserConversions=*/false,
1590 /*AllowExplicit=*/false,
1591 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001592 }
1593 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1594 ICS.UserDefined.After.ReferenceBinding) {
1595 assert(ICS.UserDefined.After.DirectBinding &&
1596 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001597 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001598 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001599 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001600 /*SuppressUserConversions=*/false,
1601 /*AllowExplicit=*/false,
1602 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001603 }
1604 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1605 return true;
1606 return false;
1607}
1608
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001609/// \brief Check the operands of ?: under C++ semantics.
1610///
1611/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1612/// extension. In this case, LHS == Cond. (But they're not aliases.)
1613QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1614 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001615 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1616 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001617
1618 // C++0x 5.16p1
1619 // The first expression is contextually converted to bool.
1620 if (!Cond->isTypeDependent()) {
1621 if (CheckCXXBooleanCondition(Cond))
1622 return QualType();
1623 }
1624
1625 // Either of the arguments dependent?
1626 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1627 return Context.DependentTy;
1628
1629 // C++0x 5.16p2
1630 // If either the second or the third operand has type (cv) void, ...
1631 QualType LTy = LHS->getType();
1632 QualType RTy = RHS->getType();
1633 bool LVoid = LTy->isVoidType();
1634 bool RVoid = RTy->isVoidType();
1635 if (LVoid || RVoid) {
1636 // ... then the [l2r] conversions are performed on the second and third
1637 // operands ...
1638 DefaultFunctionArrayConversion(LHS);
1639 DefaultFunctionArrayConversion(RHS);
1640 LTy = LHS->getType();
1641 RTy = RHS->getType();
1642
1643 // ... and one of the following shall hold:
1644 // -- The second or the third operand (but not both) is a throw-
1645 // expression; the result is of the type of the other and is an rvalue.
1646 bool LThrow = isa<CXXThrowExpr>(LHS);
1647 bool RThrow = isa<CXXThrowExpr>(RHS);
1648 if (LThrow && !RThrow)
1649 return RTy;
1650 if (RThrow && !LThrow)
1651 return LTy;
1652
1653 // -- Both the second and third operands have type void; the result is of
1654 // type void and is an rvalue.
1655 if (LVoid && RVoid)
1656 return Context.VoidTy;
1657
1658 // Neither holds, error.
1659 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1660 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1661 << LHS->getSourceRange() << RHS->getSourceRange();
1662 return QualType();
1663 }
1664
1665 // Neither is void.
1666
1667 // C++0x 5.16p3
1668 // Otherwise, if the second and third operand have different types, and
1669 // either has (cv) class type, and attempt is made to convert each of those
1670 // operands to the other.
1671 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1672 (LTy->isRecordType() || RTy->isRecordType())) {
1673 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1674 // These return true if a single direction is already ambiguous.
1675 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1676 return QualType();
1677 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1678 return QualType();
1679
1680 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1681 ImplicitConversionSequence::BadConversion;
1682 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1683 ImplicitConversionSequence::BadConversion;
1684 // If both can be converted, [...] the program is ill-formed.
1685 if (HaveL2R && HaveR2L) {
1686 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1687 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1688 return QualType();
1689 }
1690
1691 // If exactly one conversion is possible, that conversion is applied to
1692 // the chosen operand and the converted operands are used in place of the
1693 // original operands for the remainder of this section.
1694 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001695 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001696 return QualType();
1697 LTy = LHS->getType();
1698 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001699 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001700 return QualType();
1701 RTy = RHS->getType();
1702 }
1703 }
1704
1705 // C++0x 5.16p4
1706 // If the second and third operands are lvalues and have the same type,
1707 // the result is of that type [...]
1708 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1709 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1710 RHS->isLvalue(Context) == Expr::LV_Valid)
1711 return LTy;
1712
1713 // C++0x 5.16p5
1714 // Otherwise, the result is an rvalue. If the second and third operands
1715 // do not have the same type, and either has (cv) class type, ...
1716 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1717 // ... overload resolution is used to determine the conversions (if any)
1718 // to be applied to the operands. If the overload resolution fails, the
1719 // program is ill-formed.
1720 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1721 return QualType();
1722 }
1723
1724 // C++0x 5.16p6
1725 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1726 // conversions are performed on the second and third operands.
1727 DefaultFunctionArrayConversion(LHS);
1728 DefaultFunctionArrayConversion(RHS);
1729 LTy = LHS->getType();
1730 RTy = RHS->getType();
1731
1732 // After those conversions, one of the following shall hold:
1733 // -- The second and third operands have the same type; the result
1734 // is of that type.
1735 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1736 return LTy;
1737
1738 // -- The second and third operands have arithmetic or enumeration type;
1739 // the usual arithmetic conversions are performed to bring them to a
1740 // common type, and the result is of that type.
1741 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1742 UsualArithmeticConversions(LHS, RHS);
1743 return LHS->getType();
1744 }
1745
1746 // -- The second and third operands have pointer type, or one has pointer
1747 // type and the other is a null pointer constant; pointer conversions
1748 // and qualification conversions are performed to bring them to their
1749 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001750 QualType Composite = FindCompositePointerType(LHS, RHS);
1751 if (!Composite.isNull())
1752 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001753
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001754 // Fourth bullet is same for pointers-to-member. However, the possible
1755 // conversions are far more limited: we have null-to-pointer, upcast of
1756 // containing class, and second-level cv-ness.
1757 // cv-ness is not a union, but must match one of the two operands. (Which,
1758 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001759 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1760 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001761 if (LMemPtr &&
1762 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001763 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001764 return LTy;
1765 }
Douglas Gregorce940492009-09-25 04:25:58 +00001766 if (RMemPtr &&
1767 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001768 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001769 return RTy;
1770 }
1771 if (LMemPtr && RMemPtr) {
1772 QualType LPointee = LMemPtr->getPointeeType();
1773 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001774
1775 QualifierCollector LPQuals, RPQuals;
1776 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1777 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1778
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001779 // First, we check that the unqualified pointee type is the same. If it's
1780 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001781 if (LPCan == RPCan) {
1782
1783 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001784 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001785
1786 Qualifiers MergedQuals = LPQuals + RPQuals;
1787
1788 bool CompatibleQuals = true;
1789 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1790 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1791 CompatibleQuals = false;
1792 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1793 // FIXME:
1794 // C99 6.5.15 as modified by TR 18037:
1795 // If the second and third operands are pointers into different
1796 // address spaces, the address spaces must overlap.
1797 CompatibleQuals = false;
1798 // FIXME: GC qualifiers?
1799
1800 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001801 // Third, we check if either of the container classes is derived from
1802 // the other.
1803 QualType LContainer(LMemPtr->getClass(), 0);
1804 QualType RContainer(RMemPtr->getClass(), 0);
1805 QualType MoreDerived;
1806 if (Context.getCanonicalType(LContainer) ==
1807 Context.getCanonicalType(RContainer))
1808 MoreDerived = LContainer;
1809 else if (IsDerivedFrom(LContainer, RContainer))
1810 MoreDerived = LContainer;
1811 else if (IsDerivedFrom(RContainer, LContainer))
1812 MoreDerived = RContainer;
1813
1814 if (!MoreDerived.isNull()) {
1815 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1816 // We don't use ImpCastExprToType here because this could still fail
1817 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001818 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1819 QualType Common
1820 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001821 if (PerformImplicitConversion(LHS, Common, "converting"))
1822 return QualType();
1823 if (PerformImplicitConversion(RHS, Common, "converting"))
1824 return QualType();
1825 return Common;
1826 }
1827 }
1828 }
1829 }
1830
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001831 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1832 << LHS->getType() << RHS->getType()
1833 << LHS->getSourceRange() << RHS->getSourceRange();
1834 return QualType();
1835}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001836
1837/// \brief Find a merged pointer type and convert the two expressions to it.
1838///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001839/// This finds the composite pointer type (or member pointer type) for @p E1
1840/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1841/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001842/// It does not emit diagnostics.
1843QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1844 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1845 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Douglas Gregor20b3e992009-08-24 17:42:35 +00001847 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1848 !T2->isPointerType() && !T2->isMemberPointerType())
1849 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001850
Douglas Gregor20b3e992009-08-24 17:42:35 +00001851 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001853 // C++0x 5.9p2
1854 // Pointer conversions and qualification conversions are performed on
1855 // pointer operands to bring them to their composite pointer type. If
1856 // one operand is a null pointer constant, the composite pointer type is
1857 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001858 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001859 if (T2->isMemberPointerType())
1860 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1861 else
1862 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001863 return T2;
1864 }
Douglas Gregorce940492009-09-25 04:25:58 +00001865 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001866 if (T1->isMemberPointerType())
1867 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1868 else
1869 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001870 return T1;
1871 }
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Douglas Gregor20b3e992009-08-24 17:42:35 +00001873 // Now both have to be pointers or member pointers.
1874 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1875 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001876 return QualType();
1877
1878 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1879 // the other has type "pointer to cv2 T" and the composite pointer type is
1880 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1881 // Otherwise, the composite pointer type is a pointer type similar to the
1882 // type of one of the operands, with a cv-qualification signature that is
1883 // the union of the cv-qualification signatures of the operand types.
1884 // In practice, the first part here is redundant; it's subsumed by the second.
1885 // What we do here is, we build the two possible composite types, and try the
1886 // conversions in both directions. If only one works, or if the two composite
1887 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001888 // FIXME: extended qualifiers?
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001889 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001890 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001891 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001892 do {
1893 const PointerType *Ptr1, *Ptr2;
1894 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1895 (Ptr2 = Composite2->getAs<PointerType>())) {
1896 Composite1 = Ptr1->getPointeeType();
1897 Composite2 = Ptr2->getPointeeType();
1898 QualifierUnion.push_back(
1899 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1900 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1901 continue;
1902 }
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Douglas Gregor20b3e992009-08-24 17:42:35 +00001904 const MemberPointerType *MemPtr1, *MemPtr2;
1905 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1906 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1907 Composite1 = MemPtr1->getPointeeType();
1908 Composite2 = MemPtr2->getPointeeType();
1909 QualifierUnion.push_back(
1910 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1911 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1912 MemPtr2->getClass()));
1913 continue;
1914 }
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Douglas Gregor20b3e992009-08-24 17:42:35 +00001916 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Douglas Gregor20b3e992009-08-24 17:42:35 +00001918 // Cannot unwrap any more types.
1919 break;
1920 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Douglas Gregor20b3e992009-08-24 17:42:35 +00001922 // Rewrap the composites as pointers or member pointers with the union CVRs.
1923 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1924 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001925 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001926 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001927 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001928 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001929 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001930 if (MOC->first && MOC->second) {
1931 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001932 Composite1 = Context.getMemberPointerType(
1933 Context.getQualifiedType(Composite1, Quals),
1934 MOC->first);
1935 Composite2 = Context.getMemberPointerType(
1936 Context.getQualifiedType(Composite2, Quals),
1937 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001938 } else {
1939 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001940 Composite1
1941 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1942 Composite2
1943 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001944 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001945 }
1946
Mike Stump1eb44332009-09-09 15:08:12 +00001947 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001948 TryImplicitConversion(E1, Composite1,
1949 /*SuppressUserConversions=*/false,
1950 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001951 /*ForceRValue=*/false,
1952 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001953 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001954 TryImplicitConversion(E2, Composite1,
1955 /*SuppressUserConversions=*/false,
1956 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001957 /*ForceRValue=*/false,
1958 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001960 ImplicitConversionSequence E1ToC2, E2ToC2;
1961 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1962 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1963 if (Context.getCanonicalType(Composite1) !=
1964 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001965 E1ToC2 = TryImplicitConversion(E1, Composite2,
1966 /*SuppressUserConversions=*/false,
1967 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001968 /*ForceRValue=*/false,
1969 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001970 E2ToC2 = TryImplicitConversion(E2, Composite2,
1971 /*SuppressUserConversions=*/false,
1972 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001973 /*ForceRValue=*/false,
1974 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001975 }
1976
1977 bool ToC1Viable = E1ToC1.ConversionKind !=
1978 ImplicitConversionSequence::BadConversion
1979 && E2ToC1.ConversionKind !=
1980 ImplicitConversionSequence::BadConversion;
1981 bool ToC2Viable = E1ToC2.ConversionKind !=
1982 ImplicitConversionSequence::BadConversion
1983 && E2ToC2.ConversionKind !=
1984 ImplicitConversionSequence::BadConversion;
1985 if (ToC1Viable && !ToC2Viable) {
1986 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1987 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1988 return Composite1;
1989 }
1990 if (ToC2Viable && !ToC1Viable) {
1991 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1992 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1993 return Composite2;
1994 }
1995 return QualType();
1996}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001997
Anders Carlssondef11992009-05-30 20:36:53 +00001998Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001999 if (!Context.getLangOptions().CPlusPlus)
2000 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Ted Kremenek6217b802009-07-29 21:53:49 +00002002 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002003 if (!RT)
2004 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlssondef11992009-05-30 20:36:53 +00002006 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2007 if (RD->hasTrivialDestructor())
2008 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Anders Carlsson283e4d52009-09-14 01:30:44 +00002010 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2011 QualType Ty = CE->getCallee()->getType();
2012 if (const PointerType *PT = Ty->getAs<PointerType>())
2013 Ty = PT->getPointeeType();
2014
John McCall183700f2009-09-21 23:43:11 +00002015 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002016 if (FTy->getResultType()->isReferenceType())
2017 return Owned(E);
2018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002020 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002021 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002022 if (CXXDestructorDecl *Destructor =
2023 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2024 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002025 // FIXME: Add the temporary to the temporaries vector.
2026 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2027}
2028
Mike Stump1eb44332009-09-09 15:08:12 +00002029Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002030 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002031 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002033 if (ExprTemporaries.empty())
2034 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002036 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002037 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002038 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002039 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002040 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002042 return E;
2043}
2044
Mike Stump1eb44332009-09-09 15:08:12 +00002045Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002046Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2047 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2048 // Since this might be a postfix expression, get rid of ParenListExprs.
2049 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002051 Expr *BaseExpr = (Expr*)Base.get();
2052 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002054 QualType BaseType = BaseExpr->getType();
2055 if (BaseType->isDependentType()) {
2056 // FIXME: member of the current instantiation
2057 ObjectType = BaseType.getAsOpaquePtr();
2058 return move(Base);
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002061 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002062 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002063 // returned, with the original second operand.
2064 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002065 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002066 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002067 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002068 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002069
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002070 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002071 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002072 BaseExpr = (Expr*)Base.get();
2073 if (BaseExpr == NULL)
2074 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002075 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002076 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002077 BaseType = BaseExpr->getType();
2078 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002079 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002080 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002081 for (unsigned i = 0; i < Locations.size(); i++)
2082 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002083 return ExprError();
2084 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002085 }
2086 }
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002088 if (BaseType->isPointerType())
2089 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002090
2091 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002092 // vector types or Objective-C interfaces. Just return early and let
2093 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002094 if (!BaseType->isRecordType()) {
2095 // C++ [basic.lookup.classref]p2:
2096 // [...] If the type of the object expression is of pointer to scalar
2097 // type, the unqualified-id is looked up in the context of the complete
2098 // postfix-expression.
2099 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002100 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Douglas Gregorc68afe22009-09-03 21:38:09 +00002103 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002104 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00002105 // unqualified-id, and the type of the object expres- sion is of a class
2106 // type C (or of pointer to a class type C), the unqualified-id is looked
2107 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002108 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002109 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002110}
2111
Anders Carlssonec773872009-08-25 23:46:41 +00002112Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00002113Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00002114 SourceLocation OpLoc,
2115 tok::TokenKind OpKind,
2116 SourceLocation ClassNameLoc,
2117 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002118 const CXXScopeSpec &SS,
2119 bool HasTrailingLParen) {
2120 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00002121 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002122
Douglas Gregora71d8192009-09-04 17:36:40 +00002123 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00002124 if (isUnknownSpecialization(SS))
2125 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002126 ClassName);
2127 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00002128 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregordd62b152009-10-19 22:04:39 +00002129
2130 // FIXME: If Base is dependent, we might not be able to resolve it here.
Douglas Gregora71d8192009-09-04 17:36:40 +00002131 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00002132 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00002133 << ClassName;
2134 return ExprError();
2135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Douglas Gregora71d8192009-09-04 17:36:40 +00002137 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002138 }
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Douglas Gregordd62b152009-10-19 22:04:39 +00002140 return ActOnDestructorReferenceExpr(S, move(Base), OpLoc, OpKind,
2141 SourceRange(ClassNameLoc),
2142 BaseType.getAsOpaquePtr(),
2143 SS, HasTrailingLParen);
2144}
Anders Carlsson2cf738f2009-08-26 19:22:42 +00002145
Douglas Gregordd62b152009-10-19 22:04:39 +00002146Sema::OwningExprResult
2147Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
2148 SourceLocation OpLoc,
2149 tok::TokenKind OpKind,
2150 SourceRange TypeRange,
2151 TypeTy *T,
2152 const CXXScopeSpec &SS,
2153 bool HasTrailingLParen) {
2154 QualType Type = QualType::getFromOpaquePtr(T);
2155 CanQualType CanType = Context.getCanonicalType(Type);
2156 DeclarationName DtorName =
2157 Context.DeclarationNames.getCXXDestructorName(CanType);
2158
Douglas Gregora78c5c32009-09-04 18:29:40 +00002159 OwningExprResult Result
Douglas Gregordd62b152009-10-19 22:04:39 +00002160 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2161 TypeRange.getBegin(), DtorName, DeclPtrTy(),
2162 &SS);
Douglas Gregora78c5c32009-09-04 18:29:40 +00002163 if (Result.isInvalid() || HasTrailingLParen)
2164 return move(Result);
Douglas Gregordd62b152009-10-19 22:04:39 +00002165
Mike Stump1eb44332009-09-09 15:08:12 +00002166 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00002167 // immediately call them. Since the next token is not a '(', produce a
2168 // diagnostic and build the call now.
2169 Expr *E = (Expr *)Result.get();
Douglas Gregordd62b152009-10-19 22:04:39 +00002170 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(TypeRange.getEnd());
Douglas Gregora78c5c32009-09-04 18:29:40 +00002171 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2172 << isa<CXXPseudoDestructorExpr>(E)
2173 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregordd62b152009-10-19 22:04:39 +00002174
Mike Stump1eb44332009-09-09 15:08:12 +00002175 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002176 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00002177}
2178
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00002179Sema::OwningExprResult
2180Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2181 SourceLocation OpLoc,
2182 tok::TokenKind OpKind,
2183 SourceLocation ClassNameLoc,
2184 OverloadedOperatorKind OverOpKind,
2185 const CXXScopeSpec *SS) {
2186 if (SS && SS->isInvalid())
2187 return ExprError();
2188
2189 DeclarationName Name =
2190 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2191
2192 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2193 Name, DeclPtrTy(), SS);
2194}
2195
2196Sema::OwningExprResult
2197Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2198 SourceLocation OpLoc,
2199 tok::TokenKind OpKind,
2200 SourceLocation ClassNameLoc,
2201 TypeTy *Ty,
2202 const CXXScopeSpec *SS) {
2203 if (SS && SS->isInvalid())
2204 return ExprError();
2205
2206 //FIXME: Preserve type source info.
2207 QualType ConvType = GetTypeFromParser(Ty);
2208 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2209 DeclarationName ConvName =
2210 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2211
2212 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2213 ConvName, DeclPtrTy(), SS);
2214}
2215
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002216CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2217 CXXMethodDecl *Method) {
2218 MemberExpr *ME =
2219 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2220 SourceLocation(), Method->getType());
2221 QualType ResultType;
2222 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2223 ResultType = Conv->getConversionType().getNonReferenceType();
2224 else
2225 ResultType = Method->getResultType().getNonReferenceType();
2226
2227 CXXMemberCallExpr *CE =
2228 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2229 ResultType,
2230 SourceLocation());
2231 return CE;
2232}
2233
Anders Carlsson0aebc812009-09-09 21:33:21 +00002234Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2235 QualType Ty,
2236 CastExpr::CastKind Kind,
2237 CXXMethodDecl *Method,
2238 ExprArg Arg) {
2239 Expr *From = Arg.takeAs<Expr>();
2240
2241 switch (Kind) {
2242 default: assert(0 && "Unhandled cast kind!");
2243 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002244 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2245
2246 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2247 MultiExprArg(*this, (void **)&From, 1),
2248 CastLoc, ConstructorArgs))
2249 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002250
2251 OwningExprResult Result =
2252 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2253 move_arg(ConstructorArgs));
2254 if (Result.isInvalid())
2255 return ExprError();
2256
2257 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002258 }
2259
2260 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002261 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2262
2263 // Cast to base if needed.
2264 if (PerformObjectArgumentInitialization(From, Method))
2265 return ExprError();
2266
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002267 // Create an implicit call expr that calls it.
2268 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002269 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002270 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002271 }
2272}
2273
Anders Carlsson165a0a02009-05-17 18:41:29 +00002274Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2275 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002276 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002277 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002278 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002279
Anders Carlssonec773872009-08-25 23:46:41 +00002280
Anders Carlsson165a0a02009-05-17 18:41:29 +00002281 return Owned(FullExpr);
2282}
Douglas Gregore961afb2009-10-22 07:08:30 +00002283
2284/// \brief Determine whether a reference to the given declaration in the
2285/// current context is an implicit member access
2286/// (C++ [class.mfct.non-static]p2).
2287///
2288/// FIXME: Should Objective-C also use this approach?
2289///
2290/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2291/// name of the declaration referenced.
2292///
2293/// \param D the declaration being referenced from the current scope.
2294///
2295/// \param NameLoc the location of the name in the source.
2296///
2297/// \param ThisType if the reference to this declaration is an implicit member
2298/// access, will be set to the type of the "this" pointer to be used when
2299/// building that implicit member access.
2300///
2301/// \param MemberType if the reference to this declaration is an implicit
2302/// member access, will be set to the type of the member being referenced
2303/// (for use at the type of the resulting member access expression).
2304///
2305/// \returns true if this is an implicit member reference (in which case
2306/// \p ThisType and \p MemberType will be set), or false if it is not an
2307/// implicit member reference.
2308bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2309 SourceLocation NameLoc, QualType &ThisType,
2310 QualType &MemberType) {
2311 // If this isn't a C++ method, then it isn't an implicit member reference.
2312 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2313 if (!MD || MD->isStatic())
2314 return false;
2315
2316 // C++ [class.mfct.nonstatic]p2:
2317 // [...] if name lookup (3.4.1) resolves the name in the
2318 // id-expression to a nonstatic nontype member of class X or of
2319 // a base class of X, the id-expression is transformed into a
2320 // class member access expression (5.2.5) using (*this) (9.3.2)
2321 // as the postfix-expression to the left of the '.' operator.
2322 DeclContext *Ctx = 0;
2323 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2324 Ctx = FD->getDeclContext();
2325 MemberType = FD->getType();
2326
2327 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2328 MemberType = RefType->getPointeeType();
2329 else if (!FD->isMutable())
2330 MemberType
2331 = Context.getQualifiedType(MemberType,
2332 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2333 } else {
2334 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2335 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2336 FunctionTemplateDecl *FunTmpl = 0;
2337 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2338 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2339
2340 if (Method && !Method->isStatic()) {
2341 Ctx = Method->getParent();
2342 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2343 MemberType = Method->getType();
2344 else
2345 MemberType = Context.OverloadTy;
2346 break;
2347 }
2348 }
2349 }
2350
2351 if (!Ctx || !Ctx->isRecord())
2352 return false;
2353
2354 // Determine whether the declaration(s) we found are actually in a base
2355 // class. If not, this isn't an implicit member reference.
2356 ThisType = MD->getThisType(Context);
2357 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2358 QualType ClassType
2359 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2360 return Context.hasSameType(CtxType, ClassType) ||
2361 IsDerivedFrom(ClassType, CtxType);
2362}
2363