blob: 3943ce103eafe23450531f9b477360e2dc40b53c [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
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.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 Gregor4c921ae2009-01-30 01:04:22 +000064 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000065 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000066 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000067
68 if (isType)
69 // FIXME: Preserve type source info.
70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
Chris Lattner572af492008-11-20 05:51:55 +000072 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000073 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000074 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000075 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000076 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077
78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
Douglas Gregorac7610d2009-06-22 20:57:11 +000080 if (!isType) {
81 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000082 // When typeid is applied to an expression other than an lvalue of a
83 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000084 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000085
Douglas Gregorac7610d2009-06-22 20:57:11 +000086 // FIXME: if the type of the expression is a class type, the class
87 // shall be completely defined.
88 bool isUnevaluatedOperand = true;
89 Expr *E = static_cast<Expr *>(TyOrExpr);
90 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
91 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000092 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000093 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
94 if (RecordD->isPolymorphic())
95 isUnevaluatedOperand = false;
96 }
97 }
Mike Stump1eb44332009-09-09 15:08:12 +000098
Douglas Gregorac7610d2009-06-22 20:57:11 +000099 // If this is an unevaluated operand, clear out the set of declaration
100 // references we have been computing.
101 if (isUnevaluatedOperand)
102 PotentiallyReferencedDeclStack.back().clear();
103 }
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Sebastian Redlf53597f2009-03-15 17:47:39 +0000105 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106 TypeInfoType.withConst(),
107 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000108}
109
Steve Naroff1b273c42007-09-16 14:56:35 +0000110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000111Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000113 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000117}
Chris Lattner50dd2892008-02-26 00:51:44 +0000118
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
120Action::OwningExprResult
121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
122 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
123}
124
Chris Lattner50dd2892008-02-26 00:51:44 +0000125/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000128 Expr *Ex = E.takeAs<Expr>();
129 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
130 return ExprError();
131 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
132}
133
134/// CheckCXXThrowOperand - Validate the operand of a throw.
135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
136 // C++ [except.throw]p3:
137 // [...] adjusting the type from "array of T" or "function returning T"
138 // to "pointer to T" or "pointer to function returning T", [...]
139 DefaultFunctionArrayConversion(E);
140
141 // If the type of the exception would be an incomplete type or a pointer
142 // to an incomplete type other than (cv) void the program is ill-formed.
143 QualType Ty = E->getType();
144 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000145 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000146 Ty = Ptr->getPointeeType();
147 isPointer = 1;
148 }
149 if (!isPointer || !Ty->isVoidType()) {
150 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000151 PDiag(isPointer ? diag::err_throw_incomplete_ptr
152 : diag::err_throw_incomplete)
153 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000154 return true;
155 }
156
157 // FIXME: Construct a temporary here.
158 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000159}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000160
Sebastian Redlf53597f2009-03-15 17:47:39 +0000161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000162 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
163 /// is a non-lvalue expression whose value is the address of the object for
164 /// which the function is called.
165
Sebastian Redlf53597f2009-03-15 17:47:39 +0000166 if (!isa<FunctionDecl>(CurContext))
167 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000168
169 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 return Owned(new (Context) CXXThisExpr(ThisLoc,
172 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000173
Sebastian Redlf53597f2009-03-15 17:47:39 +0000174 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000175}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000181Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000185 SourceLocation *CommaLocs,
186 SourceLocation RParenLoc) {
187 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000188 // FIXME: Preserve type source info.
189 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000190 unsigned NumExprs = exprs.size();
191 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000192 SourceLocation TyBeginLoc = TypeRange.getBegin();
193 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
Sebastian Redlf53597f2009-03-15 17:47:39 +0000195 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000196 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000197 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
199 return Owned(CXXUnresolvedConstructExpr::Create(Context,
200 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000201 LParenLoc,
202 Exprs, NumExprs,
203 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000204 }
205
Anders Carlssonbb60a502009-08-27 03:53:50 +0000206 if (Ty->isArrayType())
207 return ExprError(Diag(TyBeginLoc,
208 diag::err_value_init_for_array_type) << FullRange);
209 if (!Ty->isVoidType() &&
210 RequireCompleteType(TyBeginLoc, Ty,
211 PDiag(diag::err_invalid_incomplete_type_use)
212 << FullRange))
213 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Anders Carlssonbb60a502009-08-27 03:53:50 +0000215 if (RequireNonAbstractType(TyBeginLoc, Ty,
216 diag::err_allocation_of_abstract_type))
217 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000218
219
Douglas Gregor506ae412009-01-16 18:33:17 +0000220 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000221 // If the expression list is a single expression, the type conversion
222 // expression is equivalent (in definedness, and if defined in meaning) to the
223 // corresponding cast expression.
224 //
225 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000226 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000227 CXXMethodDecl *ConversionDecl = 0;
228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, ConversionDecl,
229 /*functional-style*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 return ExprError();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000231 // We done't build this AST for X(i) where we are constructing an object.
232 if (!ConversionDecl || !isa<CXXConstructorDecl>(ConversionDecl)) {
233 exprs.release();
234 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000235 Ty, TyBeginLoc,
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000236 CastExpr::CK_UserDefinedConversion,
Mike Stump1eb44332009-09-09 15:08:12 +0000237 Exprs[0], ConversionDecl,
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000238 RParenLoc));
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000239 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000240 }
241
Ted Kremenek6217b802009-07-29 21:53:49 +0000242 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000243 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000244
Mike Stump1eb44332009-09-09 15:08:12 +0000245 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000246 !Record->hasTrivialDestructor()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000247 CXXConstructorDecl *Constructor
248 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
249 TypeRange.getBegin(),
250 SourceRange(TypeRange.getBegin(),
251 RParenLoc),
252 DeclarationName(),
253 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000254
Sebastian Redlf53597f2009-03-15 17:47:39 +0000255 if (!Constructor)
256 return ExprError();
257
Mike Stump1eb44332009-09-09 15:08:12 +0000258 OwningExprResult Result =
259 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +0000260 move(exprs), RParenLoc);
261 if (Result.isInvalid())
262 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Anders Carlssone7624a72009-08-27 05:08:22 +0000264 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000265 }
266
267 // Fall through to value-initialize an object of class type that
268 // doesn't have a user-declared default constructor.
269 }
270
271 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000272 // If the expression list specifies more than a single value, the type shall
273 // be a class with a suitably declared constructor.
274 //
275 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000276 return ExprError(Diag(CommaLocs[0],
277 diag::err_builtin_func_cast_more_than_one_arg)
278 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000279
280 assert(NumExprs == 0 && "Expected 0 expressions");
281
Douglas Gregor506ae412009-01-16 18:33:17 +0000282 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000283 // The expression T(), where T is a simple-type-specifier for a non-array
284 // complete object type or the (possibly cv-qualified) void type, creates an
285 // rvalue of the specified type, which is value-initialized.
286 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000287 exprs.release();
288 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000289}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000290
291
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000292/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
293/// @code new (memory) int[size][4] @endcode
294/// or
295/// @code ::new Foo(23, "hello") @endcode
296/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000297Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000298Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000299 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000300 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000301 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000302 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000303 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 Expr *ArraySize = 0;
305 unsigned Skip = 0;
306 // If the specified type is an array, unwrap it and save the expression.
307 if (D.getNumTypeObjects() > 0 &&
308 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
309 DeclaratorChunk &Chunk = D.getTypeObject(0);
310 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000311 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
312 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000313 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000314 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
315 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000316 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
317 Skip = 1;
318 }
319
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000320 //FIXME: Store DeclaratorInfo in CXXNew expression.
321 DeclaratorInfo *DInfo = 0;
322 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000323 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000324 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000325
Douglas Gregor3433cf72009-05-21 00:00:09 +0000326 // Every dimension shall be of constant size.
327 unsigned i = 1;
328 QualType ElementType = AllocType;
329 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
330 if (!Array->isConstantArrayType()) {
331 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
332 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
333 return ExprError();
334 }
335 ElementType = Array->getElementType();
336 ++i;
337 }
338
Mike Stump1eb44332009-09-09 15:08:12 +0000339 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000340 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000341 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000342 PlacementRParen,
343 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000344 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000345 D.getSourceRange().getBegin(),
346 D.getSourceRange(),
347 Owned(ArraySize),
348 ConstructorLParen,
349 move(ConstructorArgs),
350 ConstructorRParen);
351}
352
Mike Stump1eb44332009-09-09 15:08:12 +0000353Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000354Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
355 SourceLocation PlacementLParen,
356 MultiExprArg PlacementArgs,
357 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000359 QualType AllocType,
360 SourceLocation TypeLoc,
361 SourceRange TypeRange,
362 ExprArg ArraySizeE,
363 SourceLocation ConstructorLParen,
364 MultiExprArg ConstructorArgs,
365 SourceLocation ConstructorRParen) {
366 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000367 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000368
Douglas Gregor3433cf72009-05-21 00:00:09 +0000369 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000370
371 // That every array dimension except the first is constant was already
372 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000373
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000374 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
375 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000376 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000377 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000378 QualType SizeType = ArraySize->getType();
379 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000380 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
381 diag::err_array_size_not_integral)
382 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000383 // Let's see if this is a constant < 0. If so, we reject it out of hand.
384 // We don't care about special rules, so we tell the machinery it's not
385 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000386 if (!ArraySize->isValueDependent()) {
387 llvm::APSInt Value;
388 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
389 if (Value < llvm::APSInt(
390 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
392 diag::err_typecheck_negative_array_size)
393 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000394 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000395 }
396 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000397
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000398 FunctionDecl *OperatorNew = 0;
399 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000400 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
401 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000402 if (!AllocType->isDependentType() &&
403 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
404 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000405 SourceRange(PlacementLParen, PlacementRParen),
406 UseGlobal, AllocType, ArraySize, PlaceArgs,
407 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000408 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000409
410 bool Init = ConstructorLParen.isValid();
411 // --- Choosing a constructor ---
412 // C++ 5.3.4p15
413 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
414 // the object is not initialized. If the object, or any part of it, is
415 // const-qualified, it's an error.
416 // 2) If T is a POD and there's an empty initializer, the object is value-
417 // initialized.
418 // 3) If T is a POD and there's one initializer argument, the object is copy-
419 // constructed.
420 // 4) If T is a POD and there's more initializer arguments, it's an error.
421 // 5) If T is not a POD, the initializer arguments are used as constructor
422 // arguments.
423 //
424 // Or by the C++0x formulation:
425 // 1) If there's no initializer, the object is default-initialized according
426 // to C++0x rules.
427 // 2) Otherwise, the object is direct-initialized.
428 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000430 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000431 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000432 if (AllocType->isDependentType()) {
433 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000434 } else if ((RT = AllocType->getAs<RecordType>()) &&
435 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000436 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000437 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000438 TypeLoc,
439 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000440 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000441 NumConsArgs != 0 ? IK_Direct : IK_Default);
442 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000443 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000444 } else {
445 if (!Init) {
446 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000447 if (AllocType.isConstQualified())
448 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000449 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000450 } else if (NumConsArgs == 0) {
451 // Object is value-initialized. Do nothing.
452 } else if (NumConsArgs == 1) {
453 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000454 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000455 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000456 DeclarationName() /*AllocType.getAsString()*/,
457 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000459 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000460 return ExprError(Diag(StartLoc,
461 diag::err_builtin_direct_init_more_than_one_arg)
462 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000463 }
464 }
465
466 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
467
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 PlacementArgs.release();
469 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000470 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000472 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000473 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000474 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000475}
476
477/// CheckAllocatedType - Checks that a type is suitable as the allocated type
478/// in a new-expression.
479/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000480bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000481 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000482 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
483 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000484 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000485 return Diag(Loc, diag::err_bad_new_type)
486 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000487 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000488 return Diag(Loc, diag::err_bad_new_type)
489 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000490 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000491 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000492 PDiag(diag::err_new_incomplete_type)
493 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000494 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000495 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000496 diag::err_allocation_of_abstract_type))
497 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000498
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 return false;
500}
501
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000502/// FindAllocationFunctions - Finds the overloads of operator new and delete
503/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000504bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
505 bool UseGlobal, QualType AllocType,
506 bool IsArray, Expr **PlaceArgs,
507 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000508 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000509 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000510 // --- Choosing an allocation function ---
511 // C++ 5.3.4p8 - 14 & 18
512 // 1) If UseGlobal is true, only look in the global scope. Else, also look
513 // in the scope of the allocated class.
514 // 2) If an array size is given, look for operator new[], else look for
515 // operator new.
516 // 3) The first argument is always size_t. Append the arguments from the
517 // placement form.
518 // FIXME: Also find the appropriate delete operator.
519
520 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
521 // We don't care about the actual value of this argument.
522 // FIXME: Should the Sema create the expression and embed it in the syntax
523 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000524 IntegerLiteral Size(llvm::APInt::getNullValue(
525 Context.Target.getPointerWidth(0)),
526 Context.getSizeType(),
527 SourceLocation());
528 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000529 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
530
531 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
532 IsArray ? OO_Array_New : OO_New);
533 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000534 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000535 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000536 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000537 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000538 AllocArgs.size(), Record, /*AllowMissing=*/true,
539 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000540 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000541 }
542 if (!OperatorNew) {
543 // Didn't find a member overload. Look for a global one.
544 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000545 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000546 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000547 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
548 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000549 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000550 }
551
Anders Carlssond9583892009-05-31 20:26:12 +0000552 // FindAllocationOverload can change the passed in arguments, so we need to
553 // copy them back.
554 if (NumPlaceArgs > 0)
555 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000557 return false;
558}
559
Sebastian Redl7f662392008-12-04 22:20:51 +0000560/// FindAllocationOverload - Find an fitting overload for the allocation
561/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000562bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
563 DeclarationName Name, Expr** Args,
564 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000565 bool AllowMissing, FunctionDecl *&Operator) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000566 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000567 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000568 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000569 if (AllowMissing)
570 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000571 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000572 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 }
574
575 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000576 for (; Alloc != AllocEnd; ++Alloc) {
577 // Even member operator new/delete are implicitly treated as
578 // static, so don't use AddMemberCandidate.
579 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
580 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
581 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000582 }
583
584 // Do the resolution.
585 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000586 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000587 case OR_Success: {
588 // Got one!
589 FunctionDecl *FnDecl = Best->Function;
590 // The first argument is size_t, and the first parameter must be size_t,
591 // too. This is checked on declaration and can be assumed. (It can't be
592 // asserted on, though, since invalid decls are left in there.)
593 for (unsigned i = 1; i < NumArgs; ++i) {
594 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000595 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000596 FnDecl->getParamDecl(i)->getType(),
597 "passing"))
598 return true;
599 }
600 Operator = FnDecl;
601 return false;
602 }
603
604 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000605 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000606 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
608 return true;
609
610 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000611 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000612 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000613 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
614 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000615
616 case OR_Deleted:
617 Diag(StartLoc, diag::err_ovl_deleted_call)
618 << Best->Function->isDeleted()
619 << Name << Range;
620 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
621 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 }
623 assert(false && "Unreachable, bad result from BestViableFunction");
624 return true;
625}
626
627
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000628/// DeclareGlobalNewDelete - Declare the global forms of operator new and
629/// delete. These are:
630/// @code
631/// void* operator new(std::size_t) throw(std::bad_alloc);
632/// void* operator new[](std::size_t) throw(std::bad_alloc);
633/// void operator delete(void *) throw();
634/// void operator delete[](void *) throw();
635/// @endcode
636/// Note that the placement and nothrow forms of new are *not* implicitly
637/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000638void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000639 if (GlobalNewDeleteDeclared)
640 return;
641 GlobalNewDeleteDeclared = true;
642
643 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
644 QualType SizeT = Context.getSizeType();
645
646 // FIXME: Exception specifications are not added.
647 DeclareGlobalAllocationFunction(
648 Context.DeclarationNames.getCXXOperatorName(OO_New),
649 VoidPtr, SizeT);
650 DeclareGlobalAllocationFunction(
651 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
652 VoidPtr, SizeT);
653 DeclareGlobalAllocationFunction(
654 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
655 Context.VoidTy, VoidPtr);
656 DeclareGlobalAllocationFunction(
657 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
658 Context.VoidTy, VoidPtr);
659}
660
661/// DeclareGlobalAllocationFunction - Declares a single implicit global
662/// allocation function if it doesn't already exist.
663void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000664 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000665 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
666
667 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000668 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000669 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000670 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000671 Alloc != AllocEnd; ++Alloc) {
672 // FIXME: Do we need to check for default arguments here?
673 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
674 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000675 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000676 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000677 }
678 }
679
680 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
681 FunctionDecl *Alloc =
682 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000683 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000684 Alloc->setImplicit();
685 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000686 0, Argument, /*DInfo=*/0,
687 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000688 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000689
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000690 // FIXME: Also add this declaration to the IdentifierResolver, but
691 // make sure it is at the end of the chain to coincide with the
692 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000693 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000694}
695
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000696/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
697/// @code ::delete ptr; @endcode
698/// or
699/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000700Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000701Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000702 bool ArrayForm, ExprArg Operand) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000703 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
704 // having a single conversion function to a pointer type. The result has
705 // type void."
706 // DR599 amends "pointer type" to "pointer to object type" in both cases.
707
Anders Carlssond67c4c32009-08-16 20:29:29 +0000708 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Sebastian Redlf53597f2009-03-15 17:47:39 +0000710 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000711 if (!Ex->isTypeDependent()) {
712 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000713
Sebastian Redl28507842009-02-26 14:39:58 +0000714 if (Type->isRecordType()) {
715 // FIXME: Find that one conversion function and amend the type.
716 }
717
Sebastian Redlf53597f2009-03-15 17:47:39 +0000718 if (!Type->isPointerType())
719 return ExprError(Diag(StartLoc, diag::err_delete_operand)
720 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000721
Ted Kremenek6217b802009-07-29 21:53:49 +0000722 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000723 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000724 return ExprError(Diag(StartLoc, diag::err_delete_operand)
725 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000726 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000727 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000728 PDiag(diag::warn_delete_incomplete)
729 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000730 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000731
Mike Stump1eb44332009-09-09 15:08:12 +0000732 // FIXME: This should be shared with the code for finding the delete
Anders Carlssond67c4c32009-08-16 20:29:29 +0000733 // operator in ActOnCXXNew.
734 IntegerLiteral Size(llvm::APInt::getNullValue(
735 Context.Target.getPointerWidth(0)),
736 Context.getSizeType(),
737 SourceLocation());
738 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
739 CastExpr::CK_Unknown, &Size, false);
740 Expr *DeleteArg = &Cast;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anders Carlssond67c4c32009-08-16 20:29:29 +0000742 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
743 ArrayForm ? OO_Array_Delete : OO_Delete);
744
745 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000746 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000747 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
748 // FIXME: We fail to find inherited overloads.
749 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
750 &DeleteArg, 1, Record, /*AllowMissing=*/true,
751 OperatorDelete))
752 return ExprError();
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000753 if (!Record->hasTrivialDestructor())
754 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000755 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000756 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000757 }
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Anders Carlssond67c4c32009-08-16 20:29:29 +0000759 if (!OperatorDelete) {
760 // Didn't find a member overload. Look for a global one.
761 DeclareGlobalNewDelete();
762 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000763 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000764 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
765 OperatorDelete))
766 return ExprError();
767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Sebastian Redl28507842009-02-26 14:39:58 +0000769 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000770 }
771
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 Operand.release();
773 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000774 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000775}
776
777
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000778/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
779/// C++ if/switch/while/for statement.
780/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000781Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000782Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
783 Declarator &D,
784 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000785 ExprArg AssignExprVal) {
786 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000787
788 // C++ 6.4p2:
789 // The declarator shall not specify a function or an array.
790 // The type-specifier-seq shall not contain typedef and shall not declare a
791 // new class or enumeration.
792
793 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
794 "Parser allowed 'typedef' as storage class of condition decl.");
795
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000796 // FIXME: Store DeclaratorInfo in the expression.
797 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000798 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000799 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000801 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
802 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
803 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000804 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
805 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000806 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000807 Diag(StartLoc, diag::err_invalid_use_of_array_type)
808 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000809 } else if (OwnedTag && OwnedTag->isDefinition()) {
810 // The type-specifier-seq shall not declare a new class or enumeration.
811 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000812 }
813
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000814 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000815 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000816 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000817 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000818
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000819 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000820 // We know that the decl had to be a VarDecl because that is the only type of
821 // decl that can be assigned and the grammar requires an '='.
822 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
823 VD->setDeclaredInCondition(true);
824 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000825}
826
827/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
828bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
829 // C++ 6.4p4:
830 // The value of a condition that is an initialized declaration in a statement
831 // other than a switch statement is the value of the declared variable
832 // implicitly converted to type bool. If that conversion is ill-formed, the
833 // program is ill-formed.
834 // The value of a condition that is an expression is the value of the
835 // expression, implicitly converted to bool.
836 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000837 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000838}
Douglas Gregor77a52232008-09-12 00:47:35 +0000839
840/// Helper function to determine whether this is the (deprecated) C++
841/// conversion from a string literal to a pointer to non-const char or
842/// non-const wchar_t (for narrow and wide string literals,
843/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000844bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000845Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
846 // Look inside the implicit cast, if it exists.
847 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
848 From = Cast->getSubExpr();
849
850 // A string literal (2.13.4) that is not a wide string literal can
851 // be converted to an rvalue of type "pointer to char"; a wide
852 // string literal can be converted to an rvalue of type "pointer
853 // to wchar_t" (C++ 4.2p2).
854 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000855 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000856 if (const BuiltinType *ToPointeeType
Douglas Gregor77a52232008-09-12 00:47:35 +0000857 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
858 // This conversion is considered only when there is an
859 // explicit appropriate pointer target type (C++ 4.2p2).
860 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
861 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
862 (!StrLit->isWide() &&
863 (ToPointeeType->getKind() == BuiltinType::Char_U ||
864 ToPointeeType->getKind() == BuiltinType::Char_S))))
865 return true;
866 }
867
868 return false;
869}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000870
871/// PerformImplicitConversion - Perform an implicit conversion of the
872/// expression From to the type ToType. Returns true if there was an
873/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000874/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000875/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000876/// explicit user-defined conversions are permitted. @p Elidable should be true
877/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
878/// resolution works differently in that case.
879bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000880Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000881 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +0000882 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +0000883 ImplicitConversionSequence ICS;
884 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
885 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +0000886 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000887 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000888 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000889 /*ForceRValue=*/true,
890 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000891 }
892 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000893 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000894 /*SuppressUserConversions=*/false,
895 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +0000896 /*ForceRValue=*/false,
897 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000898 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000899 return PerformImplicitConversion(From, ToType, ICS, Flavor);
900}
901
902/// PerformImplicitConversion - Perform an implicit conversion of the
903/// expression From to the type ToType using the pre-computed implicit
904/// conversion sequence ICS. Returns true if there was an error, false
905/// otherwise. The expression From is replaced with the converted
906/// expression. Flavor is the kind of conversion we're performing,
907/// used in the error message.
908bool
909Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
910 const ImplicitConversionSequence &ICS,
911 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000912 switch (ICS.ConversionKind) {
913 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000914 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000915 return true;
916 break;
917
918 case ImplicitConversionSequence::UserDefinedConversion:
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000919 {
920 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
921 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
922 if (CXXConversionDecl *CV = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000923 // FIXME. Get actual Source Location.
Mike Stump1eb44332009-09-09 15:08:12 +0000924 From =
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000925 new (Context) CXXFunctionalCastExpr(ToType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000926 ToType, SourceLocation(),
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000927 CastExpr::CK_UserDefinedConversion,
928 From, CV,
929 SourceLocation());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000930 CastKind = CastExpr::CK_UserDefinedConversion;
931 }
932 else if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
933 // FIXME. Do we need to check for isLValueReferenceType?
934 DefaultFunctionArrayConversion(From);
Mike Stump1eb44332009-09-09 15:08:12 +0000935 OwningExprResult InitResult =
Anders Carlssonec8e5ea2009-09-05 07:40:38 +0000936 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000937 ToType.getNonReferenceType(), CD,
Anders Carlssonf47511a2009-09-07 22:23:31 +0000938 MultiExprArg(*this, (void**)&From, 1));
Fariborz Jahanian31976592009-08-29 19:15:16 +0000939 // Take ownership of this expression.
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +0000940 From = InitResult.takeAs<Expr>();
941 CastKind = CastExpr::CK_ConstructorConversion ;
942 }
943 ImpCastExprToType(From, ToType.getNonReferenceType(),
944 CastKind,
945 ToType->isLValueReferenceType());
946 return false;
947 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000948
949 case ImplicitConversionSequence::EllipsisConversion:
950 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000951 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000952
953 case ImplicitConversionSequence::BadConversion:
954 return true;
955 }
956
957 // Everything went well.
958 return false;
959}
960
961/// PerformImplicitConversion - Perform an implicit conversion of the
962/// expression From to the type ToType by following the standard
963/// conversion sequence SCS. Returns true if there was an error, false
964/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000965/// expression. Flavor is the context in which we're performing this
966/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +0000967bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000968Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000969 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000970 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000971 // Overall FIXME: we are recomputing too many types here and doing far too
972 // much extra work. What this means is that we need to keep track of more
973 // information that is computed when we try the implicit conversion initially,
974 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000975 QualType FromType = From->getType();
976
Douglas Gregor225c41e2008-11-03 19:09:14 +0000977 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000978 // FIXME: When can ToType be a reference type?
979 assert(!ToType->isReferenceType());
Mike Stump1eb44332009-09-09 15:08:12 +0000980
981 OwningExprResult FromResult =
982 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
983 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +0000984 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000986 if (FromResult.isInvalid())
987 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000989 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000990 return false;
991 }
992
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000993 // Perform the first implicit conversion.
994 switch (SCS.First) {
995 case ICK_Identity:
996 case ICK_Lvalue_To_Rvalue:
997 // Nothing to do.
998 break;
999
1000 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001001 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001002 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001003 break;
1004
1005 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001006 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001007 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1008 if (!Fn)
1009 return true;
1010
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001011 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1012 return true;
1013
Douglas Gregor904eed32008-11-10 20:40:00 +00001014 FixOverloadedFunctionReference(From, Fn);
1015 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +00001016 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001017 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001018 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001019 break;
1020
1021 default:
1022 assert(false && "Improper first standard conversion");
1023 break;
1024 }
1025
1026 // Perform the second implicit conversion
1027 switch (SCS.Second) {
1028 case ICK_Identity:
1029 // Nothing to do.
1030 break;
1031
1032 case ICK_Integral_Promotion:
1033 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001034 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001035 case ICK_Integral_Conversion:
1036 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001037 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001038 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001039 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001040 case ICK_Compatible_Conversion:
1041 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001042 FromType = ToType.getUnqualifiedType();
1043 ImpCastExprToType(From, FromType);
1044 break;
1045
1046 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001047 if (SCS.IncompatibleObjC) {
1048 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001049 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001050 diag::ext_typecheck_convert_incompatible_pointer)
1051 << From->getType() << ToType << Flavor
1052 << From->getSourceRange();
1053 }
1054
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001055 if (CheckPointerConversion(From, ToType))
1056 return true;
1057 ImpCastExprToType(From, ToType);
1058 break;
1059
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001060 case ICK_Pointer_Member: {
1061 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1062 if (CheckMemberPointerConversion(From, ToType, Kind))
1063 return true;
1064 ImpCastExprToType(From, ToType, Kind);
1065 break;
1066 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001067 case ICK_Boolean_Conversion:
1068 FromType = Context.BoolTy;
1069 ImpCastExprToType(From, FromType);
1070 break;
1071
1072 default:
1073 assert(false && "Improper second standard conversion");
1074 break;
1075 }
1076
1077 switch (SCS.Third) {
1078 case ICK_Identity:
1079 // Nothing to do.
1080 break;
1081
1082 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001083 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1084 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001085 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001086 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001087 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001088 break;
1089
1090 default:
1091 assert(false && "Improper second standard conversion");
1092 break;
1093 }
1094
1095 return false;
1096}
1097
Sebastian Redl64b45f72009-01-05 20:52:13 +00001098Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1099 SourceLocation KWLoc,
1100 SourceLocation LParen,
1101 TypeTy *Ty,
1102 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001103 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001105 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1106 // all traits except __is_class, __is_enum and __is_union require a the type
1107 // to be complete.
1108 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001109 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001110 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001111 return ExprError();
1112 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001113
1114 // There is no point in eagerly computing the value. The traits are designed
1115 // to be used from type trait templates, so Ty will be a template parameter
1116 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001117 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1118 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001119}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001120
1121QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001122 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001123 const char *OpSpelling = isIndirect ? "->*" : ".*";
1124 // C++ 5.5p2
1125 // The binary operator .* [p3: ->*] binds its second operand, which shall
1126 // be of type "pointer to member of T" (where T is a completely-defined
1127 // class type) [...]
1128 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001129 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001130 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001131 Diag(Loc, diag::err_bad_memptr_rhs)
1132 << OpSpelling << RType << rex->getSourceRange();
1133 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001134 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001135
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001136 QualType Class(MemPtr->getClass(), 0);
1137
1138 // C++ 5.5p2
1139 // [...] to its first operand, which shall be of class T or of a class of
1140 // which T is an unambiguous and accessible base class. [p3: a pointer to
1141 // such a class]
1142 QualType LType = lex->getType();
1143 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001144 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001145 LType = Ptr->getPointeeType().getNonReferenceType();
1146 else {
1147 Diag(Loc, diag::err_bad_memptr_lhs)
1148 << OpSpelling << 1 << LType << lex->getSourceRange();
1149 return QualType();
1150 }
1151 }
1152
1153 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1154 Context.getCanonicalType(LType).getUnqualifiedType()) {
1155 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1156 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001157 // FIXME: Would it be useful to print full ambiguity paths, or is that
1158 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001159 if (!IsDerivedFrom(LType, Class, Paths) ||
1160 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1161 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1162 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1163 return QualType();
1164 }
1165 }
1166
1167 // C++ 5.5p2
1168 // The result is an object or a function of the type specified by the
1169 // second operand.
1170 // The cv qualifiers are the union of those in the pointer and the left side,
1171 // in accordance with 5.5p5 and 5.2.5.
1172 // FIXME: This returns a dereferenced member function pointer as a normal
1173 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001174 // calling them. There's also a GCC extension to get a function pointer to the
1175 // thing, which is another complication, because this type - unlike the type
1176 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001177 // argument.
1178 // We probably need a "MemberFunctionClosureType" or something like that.
1179 QualType Result = MemPtr->getPointeeType();
1180 if (LType.isConstQualified())
1181 Result.addConst();
1182 if (LType.isVolatileQualified())
1183 Result.addVolatile();
1184 return Result;
1185}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001186
1187/// \brief Get the target type of a standard or user-defined conversion.
1188static QualType TargetType(const ImplicitConversionSequence &ICS) {
1189 assert((ICS.ConversionKind ==
1190 ImplicitConversionSequence::StandardConversion ||
1191 ICS.ConversionKind ==
1192 ImplicitConversionSequence::UserDefinedConversion) &&
1193 "function only valid for standard or user-defined conversions");
1194 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1195 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1196 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1197}
1198
1199/// \brief Try to convert a type to another according to C++0x 5.16p3.
1200///
1201/// This is part of the parameter validation for the ? operator. If either
1202/// value operand is a class type, the two operands are attempted to be
1203/// converted to each other. This function does the conversion in one direction.
1204/// It emits a diagnostic and returns true only if it finds an ambiguous
1205/// conversion.
1206static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1207 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001208 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001209 // C++0x 5.16p3
1210 // The process for determining whether an operand expression E1 of type T1
1211 // can be converted to match an operand expression E2 of type T2 is defined
1212 // as follows:
1213 // -- If E2 is an lvalue:
1214 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1215 // E1 can be converted to match E2 if E1 can be implicitly converted to
1216 // type "lvalue reference to T2", subject to the constraint that in the
1217 // conversion the reference must bind directly to E1.
1218 if (!Self.CheckReferenceInit(From,
1219 Self.Context.getLValueReferenceType(To->getType()),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001220 /*SuppressUserConversions=*/false,
1221 /*AllowExplicit=*/false,
1222 /*ForceRValue=*/false,
1223 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001224 {
1225 assert((ICS.ConversionKind ==
1226 ImplicitConversionSequence::StandardConversion ||
1227 ICS.ConversionKind ==
1228 ImplicitConversionSequence::UserDefinedConversion) &&
1229 "expected a definite conversion");
1230 bool DirectBinding =
1231 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1232 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1233 if (DirectBinding)
1234 return false;
1235 }
1236 }
1237 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1238 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1239 // -- if E1 and E2 have class type, and the underlying class types are
1240 // the same or one is a base class of the other:
1241 QualType FTy = From->getType();
1242 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001243 const RecordType *FRec = FTy->getAs<RecordType>();
1244 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001245 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1246 if (FRec && TRec && (FRec == TRec ||
1247 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1248 // E1 can be converted to match E2 if the class of T2 is the
1249 // same type as, or a base class of, the class of T1, and
1250 // [cv2 > cv1].
1251 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1252 // Could still fail if there's no copy constructor.
1253 // FIXME: Is this a hard error then, or just a conversion failure? The
1254 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001255 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001256 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001257 /*ForceRValue=*/false,
1258 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001259 }
1260 } else {
1261 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1262 // implicitly converted to the type that expression E2 would have
1263 // if E2 were converted to an rvalue.
1264 // First find the decayed type.
1265 if (TTy->isFunctionType())
1266 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001267 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001268 TTy = Self.Context.getArrayDecayedType(TTy);
1269
1270 // Now try the implicit conversion.
1271 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001272 ICS = Self.TryImplicitConversion(From, TTy,
1273 /*SuppressUserConversions=*/false,
1274 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001275 /*ForceRValue=*/false,
1276 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001277 }
1278 return false;
1279}
1280
1281/// \brief Try to find a common type for two according to C++0x 5.16p5.
1282///
1283/// This is part of the parameter validation for the ? operator. If either
1284/// value operand is a class type, overload resolution is used to find a
1285/// conversion to a common type.
1286static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1287 SourceLocation Loc) {
1288 Expr *Args[2] = { LHS, RHS };
1289 OverloadCandidateSet CandidateSet;
1290 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1291
1292 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001293 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001294 case Sema::OR_Success:
1295 // We found a match. Perform the conversions on the arguments and move on.
1296 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1297 Best->Conversions[0], "converting") ||
1298 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1299 Best->Conversions[1], "converting"))
1300 break;
1301 return false;
1302
1303 case Sema::OR_No_Viable_Function:
1304 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1305 << LHS->getType() << RHS->getType()
1306 << LHS->getSourceRange() << RHS->getSourceRange();
1307 return true;
1308
1309 case Sema::OR_Ambiguous:
1310 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1311 << LHS->getType() << RHS->getType()
1312 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001313 // FIXME: Print the possible common types by printing the return types of
1314 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001315 break;
1316
1317 case Sema::OR_Deleted:
1318 assert(false && "Conditional operator has only built-in overloads");
1319 break;
1320 }
1321 return true;
1322}
1323
Sebastian Redl76458502009-04-17 16:30:52 +00001324/// \brief Perform an "extended" implicit conversion as returned by
1325/// TryClassUnification.
1326///
1327/// TryClassUnification generates ICSs that include reference bindings.
1328/// PerformImplicitConversion is not suitable for this; it chokes if the
1329/// second part of a standard conversion is ICK_DerivedToBase. This function
1330/// handles the reference binding specially.
1331static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001332 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001333 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1334 ICS.Standard.ReferenceBinding) {
1335 assert(ICS.Standard.DirectBinding &&
1336 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001337 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1338 // redoing all the work.
1339 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001340 TargetType(ICS)),
1341 /*SuppressUserConversions=*/false,
1342 /*AllowExplicit=*/false,
1343 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001344 }
1345 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1346 ICS.UserDefined.After.ReferenceBinding) {
1347 assert(ICS.UserDefined.After.DirectBinding &&
1348 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001349 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001350 TargetType(ICS)),
1351 /*SuppressUserConversions=*/false,
1352 /*AllowExplicit=*/false,
1353 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001354 }
1355 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1356 return true;
1357 return false;
1358}
1359
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001360/// \brief Check the operands of ?: under C++ semantics.
1361///
1362/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1363/// extension. In this case, LHS == Cond. (But they're not aliases.)
1364QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1365 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001366 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1367 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001368
1369 // C++0x 5.16p1
1370 // The first expression is contextually converted to bool.
1371 if (!Cond->isTypeDependent()) {
1372 if (CheckCXXBooleanCondition(Cond))
1373 return QualType();
1374 }
1375
1376 // Either of the arguments dependent?
1377 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1378 return Context.DependentTy;
1379
1380 // C++0x 5.16p2
1381 // If either the second or the third operand has type (cv) void, ...
1382 QualType LTy = LHS->getType();
1383 QualType RTy = RHS->getType();
1384 bool LVoid = LTy->isVoidType();
1385 bool RVoid = RTy->isVoidType();
1386 if (LVoid || RVoid) {
1387 // ... then the [l2r] conversions are performed on the second and third
1388 // operands ...
1389 DefaultFunctionArrayConversion(LHS);
1390 DefaultFunctionArrayConversion(RHS);
1391 LTy = LHS->getType();
1392 RTy = RHS->getType();
1393
1394 // ... and one of the following shall hold:
1395 // -- The second or the third operand (but not both) is a throw-
1396 // expression; the result is of the type of the other and is an rvalue.
1397 bool LThrow = isa<CXXThrowExpr>(LHS);
1398 bool RThrow = isa<CXXThrowExpr>(RHS);
1399 if (LThrow && !RThrow)
1400 return RTy;
1401 if (RThrow && !LThrow)
1402 return LTy;
1403
1404 // -- Both the second and third operands have type void; the result is of
1405 // type void and is an rvalue.
1406 if (LVoid && RVoid)
1407 return Context.VoidTy;
1408
1409 // Neither holds, error.
1410 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1411 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1412 << LHS->getSourceRange() << RHS->getSourceRange();
1413 return QualType();
1414 }
1415
1416 // Neither is void.
1417
1418 // C++0x 5.16p3
1419 // Otherwise, if the second and third operand have different types, and
1420 // either has (cv) class type, and attempt is made to convert each of those
1421 // operands to the other.
1422 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1423 (LTy->isRecordType() || RTy->isRecordType())) {
1424 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1425 // These return true if a single direction is already ambiguous.
1426 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1427 return QualType();
1428 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1429 return QualType();
1430
1431 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1432 ImplicitConversionSequence::BadConversion;
1433 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1434 ImplicitConversionSequence::BadConversion;
1435 // If both can be converted, [...] the program is ill-formed.
1436 if (HaveL2R && HaveR2L) {
1437 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1438 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1439 return QualType();
1440 }
1441
1442 // If exactly one conversion is possible, that conversion is applied to
1443 // the chosen operand and the converted operands are used in place of the
1444 // original operands for the remainder of this section.
1445 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001446 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001447 return QualType();
1448 LTy = LHS->getType();
1449 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001450 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001451 return QualType();
1452 RTy = RHS->getType();
1453 }
1454 }
1455
1456 // C++0x 5.16p4
1457 // If the second and third operands are lvalues and have the same type,
1458 // the result is of that type [...]
1459 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1460 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1461 RHS->isLvalue(Context) == Expr::LV_Valid)
1462 return LTy;
1463
1464 // C++0x 5.16p5
1465 // Otherwise, the result is an rvalue. If the second and third operands
1466 // do not have the same type, and either has (cv) class type, ...
1467 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1468 // ... overload resolution is used to determine the conversions (if any)
1469 // to be applied to the operands. If the overload resolution fails, the
1470 // program is ill-formed.
1471 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1472 return QualType();
1473 }
1474
1475 // C++0x 5.16p6
1476 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1477 // conversions are performed on the second and third operands.
1478 DefaultFunctionArrayConversion(LHS);
1479 DefaultFunctionArrayConversion(RHS);
1480 LTy = LHS->getType();
1481 RTy = RHS->getType();
1482
1483 // After those conversions, one of the following shall hold:
1484 // -- The second and third operands have the same type; the result
1485 // is of that type.
1486 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1487 return LTy;
1488
1489 // -- The second and third operands have arithmetic or enumeration type;
1490 // the usual arithmetic conversions are performed to bring them to a
1491 // common type, and the result is of that type.
1492 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1493 UsualArithmeticConversions(LHS, RHS);
1494 return LHS->getType();
1495 }
1496
1497 // -- The second and third operands have pointer type, or one has pointer
1498 // type and the other is a null pointer constant; pointer conversions
1499 // and qualification conversions are performed to bring them to their
1500 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001501 QualType Composite = FindCompositePointerType(LHS, RHS);
1502 if (!Composite.isNull())
1503 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001504
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001505 // Fourth bullet is same for pointers-to-member. However, the possible
1506 // conversions are far more limited: we have null-to-pointer, upcast of
1507 // containing class, and second-level cv-ness.
1508 // cv-ness is not a union, but must match one of the two operands. (Which,
1509 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001510 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1511 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001512 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1513 ImpCastExprToType(RHS, LTy);
1514 return LTy;
1515 }
1516 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1517 ImpCastExprToType(LHS, RTy);
1518 return RTy;
1519 }
1520 if (LMemPtr && RMemPtr) {
1521 QualType LPointee = LMemPtr->getPointeeType();
1522 QualType RPointee = RMemPtr->getPointeeType();
1523 // First, we check that the unqualified pointee type is the same. If it's
1524 // not, there's no conversion that will unify the two pointers.
1525 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1526 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1527 // Second, we take the greater of the two cv qualifications. If neither
1528 // is greater than the other, the conversion is not possible.
1529 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1530 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1531 // Third, we check if either of the container classes is derived from
1532 // the other.
1533 QualType LContainer(LMemPtr->getClass(), 0);
1534 QualType RContainer(RMemPtr->getClass(), 0);
1535 QualType MoreDerived;
1536 if (Context.getCanonicalType(LContainer) ==
1537 Context.getCanonicalType(RContainer))
1538 MoreDerived = LContainer;
1539 else if (IsDerivedFrom(LContainer, RContainer))
1540 MoreDerived = LContainer;
1541 else if (IsDerivedFrom(RContainer, LContainer))
1542 MoreDerived = RContainer;
1543
1544 if (!MoreDerived.isNull()) {
1545 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1546 // We don't use ImpCastExprToType here because this could still fail
1547 // for ambiguous or inaccessible conversions.
1548 QualType Common = Context.getMemberPointerType(
1549 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1550 if (PerformImplicitConversion(LHS, Common, "converting"))
1551 return QualType();
1552 if (PerformImplicitConversion(RHS, Common, "converting"))
1553 return QualType();
1554 return Common;
1555 }
1556 }
1557 }
1558 }
1559
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001560 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1561 << LHS->getType() << RHS->getType()
1562 << LHS->getSourceRange() << RHS->getSourceRange();
1563 return QualType();
1564}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001565
1566/// \brief Find a merged pointer type and convert the two expressions to it.
1567///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001568/// This finds the composite pointer type (or member pointer type) for @p E1
1569/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1570/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001571/// It does not emit diagnostics.
1572QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1573 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1574 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregor20b3e992009-08-24 17:42:35 +00001576 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1577 !T2->isPointerType() && !T2->isMemberPointerType())
1578 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001579
Douglas Gregor20b3e992009-08-24 17:42:35 +00001580 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001582 // C++0x 5.9p2
1583 // Pointer conversions and qualification conversions are performed on
1584 // pointer operands to bring them to their composite pointer type. If
1585 // one operand is a null pointer constant, the composite pointer type is
1586 // the type of the other operand.
1587 if (E1->isNullPointerConstant(Context)) {
1588 ImpCastExprToType(E1, T2);
1589 return T2;
1590 }
1591 if (E2->isNullPointerConstant(Context)) {
1592 ImpCastExprToType(E2, T1);
1593 return T1;
1594 }
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Douglas Gregor20b3e992009-08-24 17:42:35 +00001596 // Now both have to be pointers or member pointers.
1597 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1598 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001599 return QualType();
1600
1601 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1602 // the other has type "pointer to cv2 T" and the composite pointer type is
1603 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1604 // Otherwise, the composite pointer type is a pointer type similar to the
1605 // type of one of the operands, with a cv-qualification signature that is
1606 // the union of the cv-qualification signatures of the operand types.
1607 // In practice, the first part here is redundant; it's subsumed by the second.
1608 // What we do here is, we build the two possible composite types, and try the
1609 // conversions in both directions. If only one works, or if the two composite
1610 // types are the same, we have succeeded.
1611 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001612 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001613 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001614 do {
1615 const PointerType *Ptr1, *Ptr2;
1616 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1617 (Ptr2 = Composite2->getAs<PointerType>())) {
1618 Composite1 = Ptr1->getPointeeType();
1619 Composite2 = Ptr2->getPointeeType();
1620 QualifierUnion.push_back(
1621 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1622 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1623 continue;
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor20b3e992009-08-24 17:42:35 +00001626 const MemberPointerType *MemPtr1, *MemPtr2;
1627 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1628 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1629 Composite1 = MemPtr1->getPointeeType();
1630 Composite2 = MemPtr2->getPointeeType();
1631 QualifierUnion.push_back(
1632 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1633 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1634 MemPtr2->getClass()));
1635 continue;
1636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor20b3e992009-08-24 17:42:35 +00001638 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Douglas Gregor20b3e992009-08-24 17:42:35 +00001640 // Cannot unwrap any more types.
1641 break;
1642 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregor20b3e992009-08-24 17:42:35 +00001644 // Rewrap the composites as pointers or member pointers with the union CVRs.
1645 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1646 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001647 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001648 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001649 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001650 I != E; (void)++I, ++MOC) {
1651 if (MOC->first && MOC->second) {
1652 // Rebuild member pointer type
1653 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1654 MOC->first);
1655 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1656 MOC->second);
1657 } else {
1658 // Rebuild pointer type
1659 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1660 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1661 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001662 }
1663
Mike Stump1eb44332009-09-09 15:08:12 +00001664 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001665 TryImplicitConversion(E1, Composite1,
1666 /*SuppressUserConversions=*/false,
1667 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001668 /*ForceRValue=*/false,
1669 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001670 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001671 TryImplicitConversion(E2, Composite1,
1672 /*SuppressUserConversions=*/false,
1673 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001674 /*ForceRValue=*/false,
1675 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001677 ImplicitConversionSequence E1ToC2, E2ToC2;
1678 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1679 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1680 if (Context.getCanonicalType(Composite1) !=
1681 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001682 E1ToC2 = TryImplicitConversion(E1, Composite2,
1683 /*SuppressUserConversions=*/false,
1684 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001685 /*ForceRValue=*/false,
1686 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001687 E2ToC2 = TryImplicitConversion(E2, Composite2,
1688 /*SuppressUserConversions=*/false,
1689 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001690 /*ForceRValue=*/false,
1691 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001692 }
1693
1694 bool ToC1Viable = E1ToC1.ConversionKind !=
1695 ImplicitConversionSequence::BadConversion
1696 && E2ToC1.ConversionKind !=
1697 ImplicitConversionSequence::BadConversion;
1698 bool ToC2Viable = E1ToC2.ConversionKind !=
1699 ImplicitConversionSequence::BadConversion
1700 && E2ToC2.ConversionKind !=
1701 ImplicitConversionSequence::BadConversion;
1702 if (ToC1Viable && !ToC2Viable) {
1703 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1704 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1705 return Composite1;
1706 }
1707 if (ToC2Viable && !ToC1Viable) {
1708 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1709 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1710 return Composite2;
1711 }
1712 return QualType();
1713}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001714
Anders Carlssondef11992009-05-30 20:36:53 +00001715Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001716 if (!Context.getLangOptions().CPlusPlus)
1717 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Ted Kremenek6217b802009-07-29 21:53:49 +00001719 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001720 if (!RT)
1721 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Anders Carlssondef11992009-05-30 20:36:53 +00001723 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1724 if (RD->hasTrivialDestructor())
1725 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
1727 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001728 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001729 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001730 if (CXXDestructorDecl *Destructor =
1731 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1732 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001733 // FIXME: Add the temporary to the temporaries vector.
1734 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1735}
1736
Mike Stump1eb44332009-09-09 15:08:12 +00001737Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001738 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001739 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001741 if (ExprTemporaries.empty())
1742 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001744 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00001745 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001746 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001747 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001748 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001750 return E;
1751}
1752
Mike Stump1eb44332009-09-09 15:08:12 +00001753Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001754Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1755 tok::TokenKind OpKind, TypeTy *&ObjectType) {
1756 // Since this might be a postfix expression, get rid of ParenListExprs.
1757 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001759 Expr *BaseExpr = (Expr*)Base.get();
1760 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001762 QualType BaseType = BaseExpr->getType();
1763 if (BaseType->isDependentType()) {
1764 // FIXME: member of the current instantiation
1765 ObjectType = BaseType.getAsOpaquePtr();
1766 return move(Base);
1767 }
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001769 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001771 // returned, with the original second operand.
1772 if (OpKind == tok::arrow) {
1773 while (BaseType->isRecordType()) {
1774 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1775 BaseExpr = (Expr*)Base.get();
1776 if (BaseExpr == NULL)
1777 return ExprError();
1778 BaseType = BaseExpr->getType();
1779 }
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001782 if (BaseType->isPointerType())
1783 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001784
1785 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001786 // vector types or Objective-C interfaces. Just return early and let
1787 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00001788 if (!BaseType->isRecordType()) {
1789 // C++ [basic.lookup.classref]p2:
1790 // [...] If the type of the object expression is of pointer to scalar
1791 // type, the unqualified-id is looked up in the context of the complete
1792 // postfix-expression.
1793 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001794 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00001795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Douglas Gregorc68afe22009-09-03 21:38:09 +00001797 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001798 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00001799 // unqualified-id, and the type of the object expres- sion is of a class
1800 // type C (or of pointer to a class type C), the unqualified-id is looked
1801 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001802 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00001803 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001804}
1805
Anders Carlssonec773872009-08-25 23:46:41 +00001806Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001807Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001808 SourceLocation OpLoc,
1809 tok::TokenKind OpKind,
1810 SourceLocation ClassNameLoc,
1811 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001812 const CXXScopeSpec &SS,
1813 bool HasTrailingLParen) {
1814 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00001815 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001816
Douglas Gregora71d8192009-09-04 17:36:40 +00001817 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00001818 if (isUnknownSpecialization(SS))
1819 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00001820 ClassName);
1821 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00001822 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregora71d8192009-09-04 17:36:40 +00001823 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00001824 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00001825 << ClassName;
1826 return ExprError();
1827 }
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Douglas Gregora71d8192009-09-04 17:36:40 +00001829 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001832 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00001833 DeclarationName DtorName =
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001834 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1835
Douglas Gregora78c5c32009-09-04 18:29:40 +00001836 OwningExprResult Result
1837 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1838 DtorName, DeclPtrTy(), &SS);
1839 if (Result.isInvalid() || HasTrailingLParen)
1840 return move(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
1842 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00001843 // immediately call them. Since the next token is not a '(', produce a
1844 // diagnostic and build the call now.
1845 Expr *E = (Expr *)Result.get();
1846 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1847 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1848 << isa<CXXPseudoDestructorExpr>(E)
1849 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Mike Stump1eb44332009-09-09 15:08:12 +00001850
1851 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001852 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00001853}
1854
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00001855Sema::OwningExprResult
1856Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
1857 SourceLocation OpLoc,
1858 tok::TokenKind OpKind,
1859 SourceLocation ClassNameLoc,
1860 OverloadedOperatorKind OverOpKind,
1861 const CXXScopeSpec *SS) {
1862 if (SS && SS->isInvalid())
1863 return ExprError();
1864
1865 DeclarationName Name =
1866 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
1867
1868 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1869 Name, DeclPtrTy(), SS);
1870}
1871
1872Sema::OwningExprResult
1873Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
1874 SourceLocation OpLoc,
1875 tok::TokenKind OpKind,
1876 SourceLocation ClassNameLoc,
1877 TypeTy *Ty,
1878 const CXXScopeSpec *SS) {
1879 if (SS && SS->isInvalid())
1880 return ExprError();
1881
1882 //FIXME: Preserve type source info.
1883 QualType ConvType = GetTypeFromParser(Ty);
1884 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
1885 DeclarationName ConvName =
1886 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
1887
1888 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1889 ConvName, DeclPtrTy(), SS);
1890}
1891
Anders Carlsson165a0a02009-05-17 18:41:29 +00001892Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1893 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001894 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00001895 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001896 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001897
Anders Carlssonec773872009-08-25 23:46:41 +00001898
Anders Carlsson165a0a02009-05-17 18:41:29 +00001899 return Owned(FullExpr);
1900}