blob: f500e132de096e8ae066fffb0818a2b5d9a53665 [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 Gregor7adb10f2009-09-15 22:30:29 +000064 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000065 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000066
67 if (isType)
68 // FIXME: Preserve type source info.
69 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
Chris Lattner572af492008-11-20 05:51:55 +000071 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor7adb10f2009-09-15 22:30:29 +000072 Decl *TypeInfoDecl = LookupQualifiedName(StdNamespace, TypeInfoII,
73 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;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000227 CXXMethodDecl *Method = 0;
228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
229 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000231
232 exprs.release();
233 if (Method) {
234 OwningExprResult CastArg
235 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
236 Kind, Method, Owned(Exprs[0]));
237 if (CastArg.isInvalid())
238 return ExprError();
239
240 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000241 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000242
243 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
244 Ty, TyBeginLoc, Kind,
245 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000246 }
247
Ted Kremenek6217b802009-07-29 21:53:49 +0000248 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000249 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000250
Mike Stump1eb44332009-09-09 15:08:12 +0000251 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000252 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000253 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
254
Douglas Gregor506ae412009-01-16 18:33:17 +0000255 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000256 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000257 TypeRange.getBegin(),
258 SourceRange(TypeRange.getBegin(),
259 RParenLoc),
260 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000261 IK_Direct,
262 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000263
Sebastian Redlf53597f2009-03-15 17:47:39 +0000264 if (!Constructor)
265 return ExprError();
266
Mike Stump1eb44332009-09-09 15:08:12 +0000267 OwningExprResult Result =
268 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000269 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000270 if (Result.isInvalid())
271 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Anders Carlssone7624a72009-08-27 05:08:22 +0000273 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000274 }
275
276 // Fall through to value-initialize an object of class type that
277 // doesn't have a user-declared default constructor.
278 }
279
280 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000281 // If the expression list specifies more than a single value, the type shall
282 // be a class with a suitably declared constructor.
283 //
284 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError(Diag(CommaLocs[0],
286 diag::err_builtin_func_cast_more_than_one_arg)
287 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000288
289 assert(NumExprs == 0 && "Expected 0 expressions");
290
Douglas Gregor506ae412009-01-16 18:33:17 +0000291 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000292 // The expression T(), where T is a simple-type-specifier for a non-array
293 // complete object type or the (possibly cv-qualified) void type, creates an
294 // rvalue of the specified type, which is value-initialized.
295 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000296 exprs.release();
297 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000298}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000299
300
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000301/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
302/// @code new (memory) int[size][4] @endcode
303/// or
304/// @code ::new Foo(23, "hello") @endcode
305/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000306Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000307Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000308 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000309 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000310 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000311 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000312 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000313 Expr *ArraySize = 0;
314 unsigned Skip = 0;
315 // If the specified type is an array, unwrap it and save the expression.
316 if (D.getNumTypeObjects() > 0 &&
317 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
318 DeclaratorChunk &Chunk = D.getTypeObject(0);
319 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000320 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
321 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000322 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000323 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
324 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
326 Skip = 1;
327 }
328
Douglas Gregor043cad22009-09-11 00:18:58 +0000329 // Every dimension shall be of constant size.
330 if (D.getNumTypeObjects() > 0 &&
331 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
332 for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
333 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
334 break;
335
336 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
337 if (Expr *NumElts = (Expr *)Array.NumElts) {
338 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
339 !NumElts->isIntegerConstantExpr(Context)) {
340 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
341 << NumElts->getSourceRange();
342 return ExprError();
343 }
344 }
345 }
346 }
347
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000348 //FIXME: Store DeclaratorInfo in CXXNew expression.
349 DeclaratorInfo *DInfo = 0;
350 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000351 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000352 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000353
Mike Stump1eb44332009-09-09 15:08:12 +0000354 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000355 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000356 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000357 PlacementRParen,
358 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000359 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000360 D.getSourceRange().getBegin(),
361 D.getSourceRange(),
362 Owned(ArraySize),
363 ConstructorLParen,
364 move(ConstructorArgs),
365 ConstructorRParen);
366}
367
Mike Stump1eb44332009-09-09 15:08:12 +0000368Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000369Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
370 SourceLocation PlacementLParen,
371 MultiExprArg PlacementArgs,
372 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000373 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000374 QualType AllocType,
375 SourceLocation TypeLoc,
376 SourceRange TypeRange,
377 ExprArg ArraySizeE,
378 SourceLocation ConstructorLParen,
379 MultiExprArg ConstructorArgs,
380 SourceLocation ConstructorRParen) {
381 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000383
Douglas Gregor3433cf72009-05-21 00:00:09 +0000384 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000385
386 // That every array dimension except the first is constant was already
387 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000388
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000389 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
390 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000391 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000392 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000393 QualType SizeType = ArraySize->getType();
394 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
396 diag::err_array_size_not_integral)
397 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000398 // Let's see if this is a constant < 0. If so, we reject it out of hand.
399 // We don't care about special rules, so we tell the machinery it's not
400 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000401 if (!ArraySize->isValueDependent()) {
402 llvm::APSInt Value;
403 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
404 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000405 llvm::APInt::getNullValue(Value.getBitWidth()),
406 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000407 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
408 diag::err_typecheck_negative_array_size)
409 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000410 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000411 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000412
413 ImpCastExprToType(ArraySize, Context.getSizeType());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000414 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000415
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000416 FunctionDecl *OperatorNew = 0;
417 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000418 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
419 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000420 if (!AllocType->isDependentType() &&
421 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
422 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000423 SourceRange(PlacementLParen, PlacementRParen),
424 UseGlobal, AllocType, ArraySize, PlaceArgs,
425 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000426 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000427
428 bool Init = ConstructorLParen.isValid();
429 // --- Choosing a constructor ---
430 // C++ 5.3.4p15
431 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
432 // the object is not initialized. If the object, or any part of it, is
433 // const-qualified, it's an error.
434 // 2) If T is a POD and there's an empty initializer, the object is value-
435 // initialized.
436 // 3) If T is a POD and there's one initializer argument, the object is copy-
437 // constructed.
438 // 4) If T is a POD and there's more initializer arguments, it's an error.
439 // 5) If T is not a POD, the initializer arguments are used as constructor
440 // arguments.
441 //
442 // Or by the C++0x formulation:
443 // 1) If there's no initializer, the object is default-initialized according
444 // to C++0x rules.
445 // 2) Otherwise, the object is direct-initialized.
446 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000447 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000448 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000449 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000450 if (AllocType->isDependentType()) {
451 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000452 } else if ((RT = AllocType->getAs<RecordType>()) &&
453 !AllocType->isAggregateType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000454 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
455
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000456 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000457 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000458 TypeLoc,
459 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000460 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000461 NumConsArgs != 0 ? IK_Direct : IK_Default,
462 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000463 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000464 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000465
466 // Take the converted constructor arguments and use them for the new
467 // expression.
468 NumConsArgs = ConvertedConstructorArgs.size();
469 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000470 } else {
471 if (!Init) {
472 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000473 if (AllocType.isConstQualified())
474 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000475 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000476 } else if (NumConsArgs == 0) {
477 // Object is value-initialized. Do nothing.
478 } else if (NumConsArgs == 1) {
479 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000480 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000481 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000482 DeclarationName() /*AllocType.getAsString()*/,
483 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000484 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000485 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000486 return ExprError(Diag(StartLoc,
487 diag::err_builtin_direct_init_more_than_one_arg)
488 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000489 }
490 }
491
492 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
493
Sebastian Redlf53597f2009-03-15 17:47:39 +0000494 PlacementArgs.release();
495 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000496 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000497 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000498 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000501}
502
503/// CheckAllocatedType - Checks that a type is suitable as the allocated type
504/// in a new-expression.
505/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000506bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000507 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000508 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
509 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000510 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000511 return Diag(Loc, diag::err_bad_new_type)
512 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000513 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000514 return Diag(Loc, diag::err_bad_new_type)
515 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000516 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000517 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000518 PDiag(diag::err_new_incomplete_type)
519 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000520 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000522 diag::err_allocation_of_abstract_type))
523 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000524
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000525 return false;
526}
527
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000528/// FindAllocationFunctions - Finds the overloads of operator new and delete
529/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000530bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
531 bool UseGlobal, QualType AllocType,
532 bool IsArray, Expr **PlaceArgs,
533 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000534 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000535 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000536 // --- Choosing an allocation function ---
537 // C++ 5.3.4p8 - 14 & 18
538 // 1) If UseGlobal is true, only look in the global scope. Else, also look
539 // in the scope of the allocated class.
540 // 2) If an array size is given, look for operator new[], else look for
541 // operator new.
542 // 3) The first argument is always size_t. Append the arguments from the
543 // placement form.
544 // FIXME: Also find the appropriate delete operator.
545
546 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
547 // We don't care about the actual value of this argument.
548 // FIXME: Should the Sema create the expression and embed it in the syntax
549 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000550 IntegerLiteral Size(llvm::APInt::getNullValue(
551 Context.Target.getPointerWidth(0)),
552 Context.getSizeType(),
553 SourceLocation());
554 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000555 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
556
557 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
558 IsArray ? OO_Array_New : OO_New);
559 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000560 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000561 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000562 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000563 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000564 AllocArgs.size(), Record, /*AllowMissing=*/true,
565 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000566 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000567 }
568 if (!OperatorNew) {
569 // Didn't find a member overload. Look for a global one.
570 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000571 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000572 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
574 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000575 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000576 }
577
Anders Carlssond9583892009-05-31 20:26:12 +0000578 // FindAllocationOverload can change the passed in arguments, so we need to
579 // copy them back.
580 if (NumPlaceArgs > 0)
581 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000583 return false;
584}
585
Sebastian Redl7f662392008-12-04 22:20:51 +0000586/// FindAllocationOverload - Find an fitting overload for the allocation
587/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000588bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
589 DeclarationName Name, Expr** Args,
590 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000591 bool AllowMissing, FunctionDecl *&Operator) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000592 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000593 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000594 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000595 if (AllowMissing)
596 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000598 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 }
600
601 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000602 for (; Alloc != AllocEnd; ++Alloc) {
603 // Even member operator new/delete are implicitly treated as
604 // static, so don't use AddMemberCandidate.
605 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
606 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
607 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000608 }
609
610 // Do the resolution.
611 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000612 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000613 case OR_Success: {
614 // Got one!
615 FunctionDecl *FnDecl = Best->Function;
616 // The first argument is size_t, and the first parameter must be size_t,
617 // too. This is checked on declaration and can be assumed. (It can't be
618 // asserted on, though, since invalid decls are left in there.)
619 for (unsigned i = 1; i < NumArgs; ++i) {
620 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000621 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 FnDecl->getParamDecl(i)->getType(),
623 "passing"))
624 return true;
625 }
626 Operator = FnDecl;
627 return false;
628 }
629
630 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000631 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000632 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000633 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
634 return true;
635
636 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000637 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000638 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000639 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
640 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000641
642 case OR_Deleted:
643 Diag(StartLoc, diag::err_ovl_deleted_call)
644 << Best->Function->isDeleted()
645 << Name << Range;
646 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
647 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000648 }
649 assert(false && "Unreachable, bad result from BestViableFunction");
650 return true;
651}
652
653
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000654/// DeclareGlobalNewDelete - Declare the global forms of operator new and
655/// delete. These are:
656/// @code
657/// void* operator new(std::size_t) throw(std::bad_alloc);
658/// void* operator new[](std::size_t) throw(std::bad_alloc);
659/// void operator delete(void *) throw();
660/// void operator delete[](void *) throw();
661/// @endcode
662/// Note that the placement and nothrow forms of new are *not* implicitly
663/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000664void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000665 if (GlobalNewDeleteDeclared)
666 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000667
668 // C++ [basic.std.dynamic]p2:
669 // [...] The following allocation and deallocation functions (18.4) are
670 // implicitly declared in global scope in each translation unit of a
671 // program
672 //
673 // void* operator new(std::size_t) throw(std::bad_alloc);
674 // void* operator new[](std::size_t) throw(std::bad_alloc);
675 // void operator delete(void*) throw();
676 // void operator delete[](void*) throw();
677 //
678 // These implicit declarations introduce only the function names operator
679 // new, operator new[], operator delete, operator delete[].
680 //
681 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
682 // "std" or "bad_alloc" as necessary to form the exception specification.
683 // However, we do not make these implicit declarations visible to name
684 // lookup.
685 if (!StdNamespace) {
686 // The "std" namespace has not yet been defined, so build one implicitly.
687 StdNamespace = NamespaceDecl::Create(Context,
688 Context.getTranslationUnitDecl(),
689 SourceLocation(),
690 &PP.getIdentifierTable().get("std"));
691 StdNamespace->setImplicit(true);
692 }
693
694 if (!StdBadAlloc) {
695 // The "std::bad_alloc" class has not yet been declared, so build it
696 // implicitly.
697 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
698 StdNamespace,
699 SourceLocation(),
700 &PP.getIdentifierTable().get("bad_alloc"),
701 SourceLocation(), 0);
702 StdBadAlloc->setImplicit(true);
703 }
704
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000705 GlobalNewDeleteDeclared = true;
706
707 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
708 QualType SizeT = Context.getSizeType();
709
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000710 DeclareGlobalAllocationFunction(
711 Context.DeclarationNames.getCXXOperatorName(OO_New),
712 VoidPtr, SizeT);
713 DeclareGlobalAllocationFunction(
714 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
715 VoidPtr, SizeT);
716 DeclareGlobalAllocationFunction(
717 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
718 Context.VoidTy, VoidPtr);
719 DeclareGlobalAllocationFunction(
720 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
721 Context.VoidTy, VoidPtr);
722}
723
724/// DeclareGlobalAllocationFunction - Declares a single implicit global
725/// allocation function if it doesn't already exist.
726void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000727 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000728 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
729
730 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000731 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000732 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000733 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000734 Alloc != AllocEnd; ++Alloc) {
735 // FIXME: Do we need to check for default arguments here?
736 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
737 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000738 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000739 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000740 }
741 }
742
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000743 QualType BadAllocType;
744 bool HasBadAllocExceptionSpec
745 = (Name.getCXXOverloadedOperator() == OO_New ||
746 Name.getCXXOverloadedOperator() == OO_Array_New);
747 if (HasBadAllocExceptionSpec) {
748 assert(StdBadAlloc && "Must have std::bad_alloc declared");
749 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
750 }
751
752 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
753 true, false,
754 HasBadAllocExceptionSpec? 1 : 0,
755 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000756 FunctionDecl *Alloc =
757 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000758 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000759 Alloc->setImplicit();
760 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000761 0, Argument, /*DInfo=*/0,
762 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000763 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000764
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000765 // FIXME: Also add this declaration to the IdentifierResolver, but
766 // make sure it is at the end of the chain to coincide with the
767 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000768 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000769}
770
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000771/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
772/// @code ::delete ptr; @endcode
773/// or
774/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000775Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000776Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000777 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000778 // C++ [expr.delete]p1:
779 // The operand shall have a pointer type, or a class type having a single
780 // conversion function to a pointer type. The result has type void.
781 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000782 // DR599 amends "pointer type" to "pointer to object type" in both cases.
783
Anders Carlssond67c4c32009-08-16 20:29:29 +0000784 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Sebastian Redlf53597f2009-03-15 17:47:39 +0000786 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000787 if (!Ex->isTypeDependent()) {
788 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000789
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000790 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000791 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000792 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
793 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000794 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000795
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000796 for (OverloadedFunctionDecl::function_iterator
797 Func = Conversions->function_begin(),
798 FuncEnd = Conversions->function_end();
799 Func != FuncEnd; ++Func) {
800 // Skip over templated conversion functions; they aren't considered.
801 if (isa<FunctionTemplateDecl>(*Func))
802 continue;
803
804 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
805
806 QualType ConvType = Conv->getConversionType().getNonReferenceType();
807 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
808 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000809 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000810 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000811 if (ObjectPtrConversions.size() == 1) {
812 // We have a single conversion to a pointer-to-object type. Perform
813 // that conversion.
814 Operand.release();
815 if (!PerformImplicitConversion(Ex,
816 ObjectPtrConversions.front()->getConversionType(),
817 "converting")) {
818 Operand = Owned(Ex);
819 Type = Ex->getType();
820 }
821 }
822 else if (ObjectPtrConversions.size() > 1) {
823 Diag(StartLoc, diag::err_ambiguous_delete_operand)
824 << Type << Ex->getSourceRange();
825 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
826 CXXConversionDecl *Conv = ObjectPtrConversions[i];
827 Diag(Conv->getLocation(), diag::err_ovl_candidate);
828 }
829 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000830 }
Sebastian Redl28507842009-02-26 14:39:58 +0000831 }
832
Sebastian Redlf53597f2009-03-15 17:47:39 +0000833 if (!Type->isPointerType())
834 return ExprError(Diag(StartLoc, diag::err_delete_operand)
835 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000836
Ted Kremenek6217b802009-07-29 21:53:49 +0000837 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000838 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000839 return ExprError(Diag(StartLoc, diag::err_delete_operand)
840 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000841 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000842 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000843 PDiag(diag::warn_delete_incomplete)
844 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000845 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000846
Mike Stump1eb44332009-09-09 15:08:12 +0000847 // FIXME: This should be shared with the code for finding the delete
Anders Carlssond67c4c32009-08-16 20:29:29 +0000848 // operator in ActOnCXXNew.
849 IntegerLiteral Size(llvm::APInt::getNullValue(
850 Context.Target.getPointerWidth(0)),
851 Context.getSizeType(),
852 SourceLocation());
853 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
854 CastExpr::CK_Unknown, &Size, false);
855 Expr *DeleteArg = &Cast;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Anders Carlssond67c4c32009-08-16 20:29:29 +0000857 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
858 ArrayForm ? OO_Array_Delete : OO_Delete);
859
860 if (Pointee->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000861 CXXRecordDecl *Record
Anders Carlssond67c4c32009-08-16 20:29:29 +0000862 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
863 // FIXME: We fail to find inherited overloads.
864 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
865 &DeleteArg, 1, Record, /*AllowMissing=*/true,
866 OperatorDelete))
867 return ExprError();
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000868 if (!Record->hasTrivialDestructor())
869 if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000870 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000871 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000872 }
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Anders Carlssond67c4c32009-08-16 20:29:29 +0000874 if (!OperatorDelete) {
875 // Didn't find a member overload. Look for a global one.
876 DeclareGlobalNewDelete();
877 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000878 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000879 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
880 OperatorDelete))
881 return ExprError();
882 }
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Sebastian Redl28507842009-02-26 14:39:58 +0000884 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000885 }
886
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 Operand.release();
888 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000889 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000890}
891
892
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000893/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
894/// C++ if/switch/while/for statement.
895/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000896Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000897Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
898 Declarator &D,
899 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000900 ExprArg AssignExprVal) {
901 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000902
903 // C++ 6.4p2:
904 // The declarator shall not specify a function or an array.
905 // The type-specifier-seq shall not contain typedef and shall not declare a
906 // new class or enumeration.
907
908 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
909 "Parser allowed 'typedef' as storage class of condition decl.");
910
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000911 // FIXME: Store DeclaratorInfo in the expression.
912 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000913 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000914 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000916 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
917 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
918 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000919 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
920 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000921 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000922 Diag(StartLoc, diag::err_invalid_use_of_array_type)
923 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000924 } else if (OwnedTag && OwnedTag->isDefinition()) {
925 // The type-specifier-seq shall not declare a new class or enumeration.
926 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000927 }
928
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000929 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000930 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000931 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000932 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000933
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000934 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000935 // We know that the decl had to be a VarDecl because that is the only type of
936 // decl that can be assigned and the grammar requires an '='.
937 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
938 VD->setDeclaredInCondition(true);
939 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000940}
941
942/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
943bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
944 // C++ 6.4p4:
945 // The value of a condition that is an initialized declaration in a statement
946 // other than a switch statement is the value of the declared variable
947 // implicitly converted to type bool. If that conversion is ill-formed, the
948 // program is ill-formed.
949 // The value of a condition that is an expression is the value of the
950 // expression, implicitly converted to bool.
951 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000952 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000953}
Douglas Gregor77a52232008-09-12 00:47:35 +0000954
955/// Helper function to determine whether this is the (deprecated) C++
956/// conversion from a string literal to a pointer to non-const char or
957/// non-const wchar_t (for narrow and wide string literals,
958/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000959bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000960Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
961 // Look inside the implicit cast, if it exists.
962 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
963 From = Cast->getSubExpr();
964
965 // A string literal (2.13.4) that is not a wide string literal can
966 // be converted to an rvalue of type "pointer to char"; a wide
967 // string literal can be converted to an rvalue of type "pointer
968 // to wchar_t" (C++ 4.2p2).
969 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000970 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000971 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000972 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000973 // This conversion is considered only when there is an
974 // explicit appropriate pointer target type (C++ 4.2p2).
975 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
976 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
977 (!StrLit->isWide() &&
978 (ToPointeeType->getKind() == BuiltinType::Char_U ||
979 ToPointeeType->getKind() == BuiltinType::Char_S))))
980 return true;
981 }
982
983 return false;
984}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000985
986/// PerformImplicitConversion - Perform an implicit conversion of the
987/// expression From to the type ToType. Returns true if there was an
988/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000989/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000990/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000991/// explicit user-defined conversions are permitted. @p Elidable should be true
992/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
993/// resolution works differently in that case.
994bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000995Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000996 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +0000997 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +0000998 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +0000999 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1000 Elidable, ICS);
1001}
1002
1003bool
1004Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1005 const char *Flavor, bool AllowExplicit,
1006 bool Elidable,
1007 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001008 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1009 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001010 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001011 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001012 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001013 /*ForceRValue=*/true,
1014 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001015 }
1016 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001017 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001018 /*SuppressUserConversions=*/false,
1019 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001020 /*ForceRValue=*/false,
1021 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001022 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001023 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1024}
1025
1026/// PerformImplicitConversion - Perform an implicit conversion of the
1027/// expression From to the type ToType using the pre-computed implicit
1028/// conversion sequence ICS. Returns true if there was an error, false
1029/// otherwise. The expression From is replaced with the converted
1030/// expression. Flavor is the kind of conversion we're performing,
1031/// used in the error message.
1032bool
1033Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1034 const ImplicitConversionSequence &ICS,
1035 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001036 switch (ICS.ConversionKind) {
1037 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001038 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001039 return true;
1040 break;
1041
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001042 case ImplicitConversionSequence::UserDefinedConversion: {
1043
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001044 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1045 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001046 QualType BeforeToType;
1047 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001048 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001049
1050 // If the user-defined conversion is specified by a conversion function,
1051 // the initial standard conversion sequence converts the source type to
1052 // the implicit object parameter of the conversion function.
1053 BeforeToType = Context.getTagDeclType(Conv->getParent());
1054 } else if (const CXXConstructorDecl *Ctor =
1055 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001056 CastKind = CastExpr::CK_ConstructorConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001057
1058 // If the user-defined conversion is specified by a constructor, the
1059 // initial standard conversion sequence converts the source type to the
1060 // type required by the argument of the constructor
1061 BeforeToType = Ctor->getParamDecl(0)->getType();
1062 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001063 else
1064 assert(0 && "Unknown conversion function kind!");
1065
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001066 if (PerformImplicitConversion(From, BeforeToType,
1067 ICS.UserDefined.Before, "converting"))
1068 return true;
1069
Anders Carlsson0aebc812009-09-09 21:33:21 +00001070 OwningExprResult CastArg
1071 = BuildCXXCastArgument(From->getLocStart(),
1072 ToType.getNonReferenceType(),
1073 CastKind, cast<CXXMethodDecl>(FD),
1074 Owned(From));
1075
1076 if (CastArg.isInvalid())
1077 return true;
1078
Anders Carlsson626c2d62009-09-15 05:49:31 +00001079 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1080 CastKind, CastArg.takeAs<Expr>(),
1081 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001082 return false;
1083 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001084
1085 case ImplicitConversionSequence::EllipsisConversion:
1086 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001087 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001088
1089 case ImplicitConversionSequence::BadConversion:
1090 return true;
1091 }
1092
1093 // Everything went well.
1094 return false;
1095}
1096
1097/// PerformImplicitConversion - Perform an implicit conversion of the
1098/// expression From to the type ToType by following the standard
1099/// conversion sequence SCS. Returns true if there was an error, false
1100/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001101/// expression. Flavor is the context in which we're performing this
1102/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001103bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001104Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001105 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001106 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001107 // Overall FIXME: we are recomputing too many types here and doing far too
1108 // much extra work. What this means is that we need to keep track of more
1109 // information that is computed when we try the implicit conversion initially,
1110 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001111 QualType FromType = From->getType();
1112
Douglas Gregor225c41e2008-11-03 19:09:14 +00001113 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001114 // FIXME: When can ToType be a reference type?
1115 assert(!ToType->isReferenceType());
Mike Stump1eb44332009-09-09 15:08:12 +00001116
1117 OwningExprResult FromResult =
1118 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1119 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001120 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001122 if (FromResult.isInvalid())
1123 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001125 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001126 return false;
1127 }
1128
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001129 // Perform the first implicit conversion.
1130 switch (SCS.First) {
1131 case ICK_Identity:
1132 case ICK_Lvalue_To_Rvalue:
1133 // Nothing to do.
1134 break;
1135
1136 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001137 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001138 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001139 break;
1140
1141 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001142 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001143 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1144 if (!Fn)
1145 return true;
1146
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001147 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1148 return true;
1149
Douglas Gregor904eed32008-11-10 20:40:00 +00001150 FixOverloadedFunctionReference(From, Fn);
1151 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +00001152 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001153 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001154 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001155 break;
1156
1157 default:
1158 assert(false && "Improper first standard conversion");
1159 break;
1160 }
1161
1162 // Perform the second implicit conversion
1163 switch (SCS.Second) {
1164 case ICK_Identity:
1165 // Nothing to do.
1166 break;
1167
1168 case ICK_Integral_Promotion:
1169 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001170 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001171 case ICK_Integral_Conversion:
1172 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001173 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001174 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001175 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001176 case ICK_Compatible_Conversion:
1177 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001178 FromType = ToType.getUnqualifiedType();
1179 ImpCastExprToType(From, FromType);
1180 break;
1181
Anders Carlsson61faec12009-09-12 04:46:44 +00001182 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001183 if (SCS.IncompatibleObjC) {
1184 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001185 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001186 diag::ext_typecheck_convert_incompatible_pointer)
1187 << From->getType() << ToType << Flavor
1188 << From->getSourceRange();
1189 }
1190
Anders Carlsson61faec12009-09-12 04:46:44 +00001191
1192 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1193 if (CheckPointerConversion(From, ToType, Kind))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001194 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001195 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001196 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001197 }
1198
1199 case ICK_Pointer_Member: {
1200 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1201 if (CheckMemberPointerConversion(From, ToType, Kind))
1202 return true;
1203 ImpCastExprToType(From, ToType, Kind);
1204 break;
1205 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001206 case ICK_Boolean_Conversion:
1207 FromType = Context.BoolTy;
1208 ImpCastExprToType(From, FromType);
1209 break;
1210
1211 default:
1212 assert(false && "Improper second standard conversion");
1213 break;
1214 }
1215
1216 switch (SCS.Third) {
1217 case ICK_Identity:
1218 // Nothing to do.
1219 break;
1220
1221 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001222 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1223 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001224 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001225 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001226 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001227 break;
1228
1229 default:
1230 assert(false && "Improper second standard conversion");
1231 break;
1232 }
1233
1234 return false;
1235}
1236
Sebastian Redl64b45f72009-01-05 20:52:13 +00001237Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1238 SourceLocation KWLoc,
1239 SourceLocation LParen,
1240 TypeTy *Ty,
1241 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001242 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001244 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1245 // all traits except __is_class, __is_enum and __is_union require a the type
1246 // to be complete.
1247 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001248 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001249 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001250 return ExprError();
1251 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001252
1253 // There is no point in eagerly computing the value. The traits are designed
1254 // to be used from type trait templates, so Ty will be a template parameter
1255 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001256 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1257 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001258}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001259
1260QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001261 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001262 const char *OpSpelling = isIndirect ? "->*" : ".*";
1263 // C++ 5.5p2
1264 // The binary operator .* [p3: ->*] binds its second operand, which shall
1265 // be of type "pointer to member of T" (where T is a completely-defined
1266 // class type) [...]
1267 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001268 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001269 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001270 Diag(Loc, diag::err_bad_memptr_rhs)
1271 << OpSpelling << RType << rex->getSourceRange();
1272 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001273 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001274
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001275 QualType Class(MemPtr->getClass(), 0);
1276
1277 // C++ 5.5p2
1278 // [...] to its first operand, which shall be of class T or of a class of
1279 // which T is an unambiguous and accessible base class. [p3: a pointer to
1280 // such a class]
1281 QualType LType = lex->getType();
1282 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001283 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001284 LType = Ptr->getPointeeType().getNonReferenceType();
1285 else {
1286 Diag(Loc, diag::err_bad_memptr_lhs)
1287 << OpSpelling << 1 << LType << lex->getSourceRange();
1288 return QualType();
1289 }
1290 }
1291
1292 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1293 Context.getCanonicalType(LType).getUnqualifiedType()) {
1294 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1295 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001296 // FIXME: Would it be useful to print full ambiguity paths, or is that
1297 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001298 if (!IsDerivedFrom(LType, Class, Paths) ||
1299 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1300 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1301 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1302 return QualType();
1303 }
1304 }
1305
1306 // C++ 5.5p2
1307 // The result is an object or a function of the type specified by the
1308 // second operand.
1309 // The cv qualifiers are the union of those in the pointer and the left side,
1310 // in accordance with 5.5p5 and 5.2.5.
1311 // FIXME: This returns a dereferenced member function pointer as a normal
1312 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001313 // calling them. There's also a GCC extension to get a function pointer to the
1314 // thing, which is another complication, because this type - unlike the type
1315 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001316 // argument.
1317 // We probably need a "MemberFunctionClosureType" or something like that.
1318 QualType Result = MemPtr->getPointeeType();
1319 if (LType.isConstQualified())
1320 Result.addConst();
1321 if (LType.isVolatileQualified())
1322 Result.addVolatile();
1323 return Result;
1324}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001325
1326/// \brief Get the target type of a standard or user-defined conversion.
1327static QualType TargetType(const ImplicitConversionSequence &ICS) {
1328 assert((ICS.ConversionKind ==
1329 ImplicitConversionSequence::StandardConversion ||
1330 ICS.ConversionKind ==
1331 ImplicitConversionSequence::UserDefinedConversion) &&
1332 "function only valid for standard or user-defined conversions");
1333 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1334 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1335 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1336}
1337
1338/// \brief Try to convert a type to another according to C++0x 5.16p3.
1339///
1340/// This is part of the parameter validation for the ? operator. If either
1341/// value operand is a class type, the two operands are attempted to be
1342/// converted to each other. This function does the conversion in one direction.
1343/// It emits a diagnostic and returns true only if it finds an ambiguous
1344/// conversion.
1345static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1346 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001347 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001348 // C++0x 5.16p3
1349 // The process for determining whether an operand expression E1 of type T1
1350 // can be converted to match an operand expression E2 of type T2 is defined
1351 // as follows:
1352 // -- If E2 is an lvalue:
1353 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1354 // E1 can be converted to match E2 if E1 can be implicitly converted to
1355 // type "lvalue reference to T2", subject to the constraint that in the
1356 // conversion the reference must bind directly to E1.
1357 if (!Self.CheckReferenceInit(From,
1358 Self.Context.getLValueReferenceType(To->getType()),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001359 /*SuppressUserConversions=*/false,
1360 /*AllowExplicit=*/false,
1361 /*ForceRValue=*/false,
1362 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001363 {
1364 assert((ICS.ConversionKind ==
1365 ImplicitConversionSequence::StandardConversion ||
1366 ICS.ConversionKind ==
1367 ImplicitConversionSequence::UserDefinedConversion) &&
1368 "expected a definite conversion");
1369 bool DirectBinding =
1370 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1371 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1372 if (DirectBinding)
1373 return false;
1374 }
1375 }
1376 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1377 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1378 // -- if E1 and E2 have class type, and the underlying class types are
1379 // the same or one is a base class of the other:
1380 QualType FTy = From->getType();
1381 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001382 const RecordType *FRec = FTy->getAs<RecordType>();
1383 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001384 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1385 if (FRec && TRec && (FRec == TRec ||
1386 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1387 // E1 can be converted to match E2 if the class of T2 is the
1388 // same type as, or a base class of, the class of T1, and
1389 // [cv2 > cv1].
1390 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1391 // Could still fail if there's no copy constructor.
1392 // FIXME: Is this a hard error then, or just a conversion failure? The
1393 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001394 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001395 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001396 /*ForceRValue=*/false,
1397 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001398 }
1399 } else {
1400 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1401 // implicitly converted to the type that expression E2 would have
1402 // if E2 were converted to an rvalue.
1403 // First find the decayed type.
1404 if (TTy->isFunctionType())
1405 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001406 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001407 TTy = Self.Context.getArrayDecayedType(TTy);
1408
1409 // Now try the implicit conversion.
1410 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001411 ICS = Self.TryImplicitConversion(From, TTy,
1412 /*SuppressUserConversions=*/false,
1413 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001414 /*ForceRValue=*/false,
1415 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001416 }
1417 return false;
1418}
1419
1420/// \brief Try to find a common type for two according to C++0x 5.16p5.
1421///
1422/// This is part of the parameter validation for the ? operator. If either
1423/// value operand is a class type, overload resolution is used to find a
1424/// conversion to a common type.
1425static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1426 SourceLocation Loc) {
1427 Expr *Args[2] = { LHS, RHS };
1428 OverloadCandidateSet CandidateSet;
1429 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1430
1431 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001432 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001433 case Sema::OR_Success:
1434 // We found a match. Perform the conversions on the arguments and move on.
1435 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1436 Best->Conversions[0], "converting") ||
1437 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1438 Best->Conversions[1], "converting"))
1439 break;
1440 return false;
1441
1442 case Sema::OR_No_Viable_Function:
1443 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1444 << LHS->getType() << RHS->getType()
1445 << LHS->getSourceRange() << RHS->getSourceRange();
1446 return true;
1447
1448 case Sema::OR_Ambiguous:
1449 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1450 << LHS->getType() << RHS->getType()
1451 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001452 // FIXME: Print the possible common types by printing the return types of
1453 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001454 break;
1455
1456 case Sema::OR_Deleted:
1457 assert(false && "Conditional operator has only built-in overloads");
1458 break;
1459 }
1460 return true;
1461}
1462
Sebastian Redl76458502009-04-17 16:30:52 +00001463/// \brief Perform an "extended" implicit conversion as returned by
1464/// TryClassUnification.
1465///
1466/// TryClassUnification generates ICSs that include reference bindings.
1467/// PerformImplicitConversion is not suitable for this; it chokes if the
1468/// second part of a standard conversion is ICK_DerivedToBase. This function
1469/// handles the reference binding specially.
1470static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001471 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001472 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1473 ICS.Standard.ReferenceBinding) {
1474 assert(ICS.Standard.DirectBinding &&
1475 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001476 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1477 // redoing all the work.
1478 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001479 TargetType(ICS)),
1480 /*SuppressUserConversions=*/false,
1481 /*AllowExplicit=*/false,
1482 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001483 }
1484 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1485 ICS.UserDefined.After.ReferenceBinding) {
1486 assert(ICS.UserDefined.After.DirectBinding &&
1487 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001488 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001489 TargetType(ICS)),
1490 /*SuppressUserConversions=*/false,
1491 /*AllowExplicit=*/false,
1492 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001493 }
1494 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1495 return true;
1496 return false;
1497}
1498
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001499/// \brief Check the operands of ?: under C++ semantics.
1500///
1501/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1502/// extension. In this case, LHS == Cond. (But they're not aliases.)
1503QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1504 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001505 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1506 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001507
1508 // C++0x 5.16p1
1509 // The first expression is contextually converted to bool.
1510 if (!Cond->isTypeDependent()) {
1511 if (CheckCXXBooleanCondition(Cond))
1512 return QualType();
1513 }
1514
1515 // Either of the arguments dependent?
1516 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1517 return Context.DependentTy;
1518
1519 // C++0x 5.16p2
1520 // If either the second or the third operand has type (cv) void, ...
1521 QualType LTy = LHS->getType();
1522 QualType RTy = RHS->getType();
1523 bool LVoid = LTy->isVoidType();
1524 bool RVoid = RTy->isVoidType();
1525 if (LVoid || RVoid) {
1526 // ... then the [l2r] conversions are performed on the second and third
1527 // operands ...
1528 DefaultFunctionArrayConversion(LHS);
1529 DefaultFunctionArrayConversion(RHS);
1530 LTy = LHS->getType();
1531 RTy = RHS->getType();
1532
1533 // ... and one of the following shall hold:
1534 // -- The second or the third operand (but not both) is a throw-
1535 // expression; the result is of the type of the other and is an rvalue.
1536 bool LThrow = isa<CXXThrowExpr>(LHS);
1537 bool RThrow = isa<CXXThrowExpr>(RHS);
1538 if (LThrow && !RThrow)
1539 return RTy;
1540 if (RThrow && !LThrow)
1541 return LTy;
1542
1543 // -- Both the second and third operands have type void; the result is of
1544 // type void and is an rvalue.
1545 if (LVoid && RVoid)
1546 return Context.VoidTy;
1547
1548 // Neither holds, error.
1549 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1550 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1551 << LHS->getSourceRange() << RHS->getSourceRange();
1552 return QualType();
1553 }
1554
1555 // Neither is void.
1556
1557 // C++0x 5.16p3
1558 // Otherwise, if the second and third operand have different types, and
1559 // either has (cv) class type, and attempt is made to convert each of those
1560 // operands to the other.
1561 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1562 (LTy->isRecordType() || RTy->isRecordType())) {
1563 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1564 // These return true if a single direction is already ambiguous.
1565 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1566 return QualType();
1567 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1568 return QualType();
1569
1570 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1571 ImplicitConversionSequence::BadConversion;
1572 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1573 ImplicitConversionSequence::BadConversion;
1574 // If both can be converted, [...] the program is ill-formed.
1575 if (HaveL2R && HaveR2L) {
1576 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1577 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1578 return QualType();
1579 }
1580
1581 // If exactly one conversion is possible, that conversion is applied to
1582 // the chosen operand and the converted operands are used in place of the
1583 // original operands for the remainder of this section.
1584 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001585 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001586 return QualType();
1587 LTy = LHS->getType();
1588 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001589 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001590 return QualType();
1591 RTy = RHS->getType();
1592 }
1593 }
1594
1595 // C++0x 5.16p4
1596 // If the second and third operands are lvalues and have the same type,
1597 // the result is of that type [...]
1598 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1599 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1600 RHS->isLvalue(Context) == Expr::LV_Valid)
1601 return LTy;
1602
1603 // C++0x 5.16p5
1604 // Otherwise, the result is an rvalue. If the second and third operands
1605 // do not have the same type, and either has (cv) class type, ...
1606 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1607 // ... overload resolution is used to determine the conversions (if any)
1608 // to be applied to the operands. If the overload resolution fails, the
1609 // program is ill-formed.
1610 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1611 return QualType();
1612 }
1613
1614 // C++0x 5.16p6
1615 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1616 // conversions are performed on the second and third operands.
1617 DefaultFunctionArrayConversion(LHS);
1618 DefaultFunctionArrayConversion(RHS);
1619 LTy = LHS->getType();
1620 RTy = RHS->getType();
1621
1622 // After those conversions, one of the following shall hold:
1623 // -- The second and third operands have the same type; the result
1624 // is of that type.
1625 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1626 return LTy;
1627
1628 // -- The second and third operands have arithmetic or enumeration type;
1629 // the usual arithmetic conversions are performed to bring them to a
1630 // common type, and the result is of that type.
1631 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1632 UsualArithmeticConversions(LHS, RHS);
1633 return LHS->getType();
1634 }
1635
1636 // -- The second and third operands have pointer type, or one has pointer
1637 // type and the other is a null pointer constant; pointer conversions
1638 // and qualification conversions are performed to bring them to their
1639 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001640 QualType Composite = FindCompositePointerType(LHS, RHS);
1641 if (!Composite.isNull())
1642 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001643
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001644 // Fourth bullet is same for pointers-to-member. However, the possible
1645 // conversions are far more limited: we have null-to-pointer, upcast of
1646 // containing class, and second-level cv-ness.
1647 // cv-ness is not a union, but must match one of the two operands. (Which,
1648 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001649 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1650 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001651 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1652 ImpCastExprToType(RHS, LTy);
1653 return LTy;
1654 }
1655 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1656 ImpCastExprToType(LHS, RTy);
1657 return RTy;
1658 }
1659 if (LMemPtr && RMemPtr) {
1660 QualType LPointee = LMemPtr->getPointeeType();
1661 QualType RPointee = RMemPtr->getPointeeType();
1662 // First, we check that the unqualified pointee type is the same. If it's
1663 // not, there's no conversion that will unify the two pointers.
1664 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1665 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1666 // Second, we take the greater of the two cv qualifications. If neither
1667 // is greater than the other, the conversion is not possible.
1668 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1669 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1670 // Third, we check if either of the container classes is derived from
1671 // the other.
1672 QualType LContainer(LMemPtr->getClass(), 0);
1673 QualType RContainer(RMemPtr->getClass(), 0);
1674 QualType MoreDerived;
1675 if (Context.getCanonicalType(LContainer) ==
1676 Context.getCanonicalType(RContainer))
1677 MoreDerived = LContainer;
1678 else if (IsDerivedFrom(LContainer, RContainer))
1679 MoreDerived = LContainer;
1680 else if (IsDerivedFrom(RContainer, LContainer))
1681 MoreDerived = RContainer;
1682
1683 if (!MoreDerived.isNull()) {
1684 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1685 // We don't use ImpCastExprToType here because this could still fail
1686 // for ambiguous or inaccessible conversions.
1687 QualType Common = Context.getMemberPointerType(
1688 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1689 if (PerformImplicitConversion(LHS, Common, "converting"))
1690 return QualType();
1691 if (PerformImplicitConversion(RHS, Common, "converting"))
1692 return QualType();
1693 return Common;
1694 }
1695 }
1696 }
1697 }
1698
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001699 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1700 << LHS->getType() << RHS->getType()
1701 << LHS->getSourceRange() << RHS->getSourceRange();
1702 return QualType();
1703}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001704
1705/// \brief Find a merged pointer type and convert the two expressions to it.
1706///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001707/// This finds the composite pointer type (or member pointer type) for @p E1
1708/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1709/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001710/// It does not emit diagnostics.
1711QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1712 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1713 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor20b3e992009-08-24 17:42:35 +00001715 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1716 !T2->isPointerType() && !T2->isMemberPointerType())
1717 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001718
Douglas Gregor20b3e992009-08-24 17:42:35 +00001719 // FIXME: Do we need to work on the canonical types?
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001721 // C++0x 5.9p2
1722 // Pointer conversions and qualification conversions are performed on
1723 // pointer operands to bring them to their composite pointer type. If
1724 // one operand is a null pointer constant, the composite pointer type is
1725 // the type of the other operand.
1726 if (E1->isNullPointerConstant(Context)) {
1727 ImpCastExprToType(E1, T2);
1728 return T2;
1729 }
1730 if (E2->isNullPointerConstant(Context)) {
1731 ImpCastExprToType(E2, T1);
1732 return T1;
1733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregor20b3e992009-08-24 17:42:35 +00001735 // Now both have to be pointers or member pointers.
1736 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1737 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001738 return QualType();
1739
1740 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1741 // the other has type "pointer to cv2 T" and the composite pointer type is
1742 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1743 // Otherwise, the composite pointer type is a pointer type similar to the
1744 // type of one of the operands, with a cv-qualification signature that is
1745 // the union of the cv-qualification signatures of the operand types.
1746 // In practice, the first part here is redundant; it's subsumed by the second.
1747 // What we do here is, we build the two possible composite types, and try the
1748 // conversions in both directions. If only one works, or if the two composite
1749 // types are the same, we have succeeded.
1750 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001751 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001752 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001753 do {
1754 const PointerType *Ptr1, *Ptr2;
1755 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1756 (Ptr2 = Composite2->getAs<PointerType>())) {
1757 Composite1 = Ptr1->getPointeeType();
1758 Composite2 = Ptr2->getPointeeType();
1759 QualifierUnion.push_back(
1760 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1761 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1762 continue;
1763 }
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Douglas Gregor20b3e992009-08-24 17:42:35 +00001765 const MemberPointerType *MemPtr1, *MemPtr2;
1766 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1767 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1768 Composite1 = MemPtr1->getPointeeType();
1769 Composite2 = MemPtr2->getPointeeType();
1770 QualifierUnion.push_back(
1771 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1772 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1773 MemPtr2->getClass()));
1774 continue;
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Douglas Gregor20b3e992009-08-24 17:42:35 +00001777 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Douglas Gregor20b3e992009-08-24 17:42:35 +00001779 // Cannot unwrap any more types.
1780 break;
1781 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregor20b3e992009-08-24 17:42:35 +00001783 // Rewrap the composites as pointers or member pointers with the union CVRs.
1784 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1785 = MemberOfClass.begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001786 for (llvm::SmallVector<unsigned, 4>::iterator
Douglas Gregor20b3e992009-08-24 17:42:35 +00001787 I = QualifierUnion.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001788 E = QualifierUnion.end();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001789 I != E; (void)++I, ++MOC) {
1790 if (MOC->first && MOC->second) {
1791 // Rebuild member pointer type
1792 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1793 MOC->first);
1794 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1795 MOC->second);
1796 } else {
1797 // Rebuild pointer type
1798 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1799 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1800 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001801 }
1802
Mike Stump1eb44332009-09-09 15:08:12 +00001803 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001804 TryImplicitConversion(E1, Composite1,
1805 /*SuppressUserConversions=*/false,
1806 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001807 /*ForceRValue=*/false,
1808 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001809 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001810 TryImplicitConversion(E2, Composite1,
1811 /*SuppressUserConversions=*/false,
1812 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001813 /*ForceRValue=*/false,
1814 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001816 ImplicitConversionSequence E1ToC2, E2ToC2;
1817 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1818 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1819 if (Context.getCanonicalType(Composite1) !=
1820 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001821 E1ToC2 = TryImplicitConversion(E1, Composite2,
1822 /*SuppressUserConversions=*/false,
1823 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001824 /*ForceRValue=*/false,
1825 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001826 E2ToC2 = TryImplicitConversion(E2, Composite2,
1827 /*SuppressUserConversions=*/false,
1828 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001829 /*ForceRValue=*/false,
1830 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001831 }
1832
1833 bool ToC1Viable = E1ToC1.ConversionKind !=
1834 ImplicitConversionSequence::BadConversion
1835 && E2ToC1.ConversionKind !=
1836 ImplicitConversionSequence::BadConversion;
1837 bool ToC2Viable = E1ToC2.ConversionKind !=
1838 ImplicitConversionSequence::BadConversion
1839 && E2ToC2.ConversionKind !=
1840 ImplicitConversionSequence::BadConversion;
1841 if (ToC1Viable && !ToC2Viable) {
1842 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1843 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1844 return Composite1;
1845 }
1846 if (ToC2Viable && !ToC1Viable) {
1847 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1848 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1849 return Composite2;
1850 }
1851 return QualType();
1852}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001853
Anders Carlssondef11992009-05-30 20:36:53 +00001854Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001855 if (!Context.getLangOptions().CPlusPlus)
1856 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Ted Kremenek6217b802009-07-29 21:53:49 +00001858 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001859 if (!RT)
1860 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Anders Carlssondef11992009-05-30 20:36:53 +00001862 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1863 if (RD->hasTrivialDestructor())
1864 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Anders Carlsson283e4d52009-09-14 01:30:44 +00001866 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1867 QualType Ty = CE->getCallee()->getType();
1868 if (const PointerType *PT = Ty->getAs<PointerType>())
1869 Ty = PT->getPointeeType();
1870
John McCall183700f2009-09-21 23:43:11 +00001871 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00001872 if (FTy->getResultType()->isReferenceType())
1873 return Owned(E);
1874 }
Mike Stump1eb44332009-09-09 15:08:12 +00001875 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00001876 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001877 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001878 if (CXXDestructorDecl *Destructor =
1879 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1880 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001881 // FIXME: Add the temporary to the temporaries vector.
1882 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1883}
1884
Mike Stump1eb44332009-09-09 15:08:12 +00001885Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001886 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001887 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001889 if (ExprTemporaries.empty())
1890 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001892 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00001893 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001894 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001895 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001896 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001898 return E;
1899}
1900
Mike Stump1eb44332009-09-09 15:08:12 +00001901Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001902Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1903 tok::TokenKind OpKind, TypeTy *&ObjectType) {
1904 // Since this might be a postfix expression, get rid of ParenListExprs.
1905 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001907 Expr *BaseExpr = (Expr*)Base.get();
1908 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001910 QualType BaseType = BaseExpr->getType();
1911 if (BaseType->isDependentType()) {
1912 // FIXME: member of the current instantiation
1913 ObjectType = BaseType.getAsOpaquePtr();
1914 return move(Base);
1915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001917 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00001918 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001919 // returned, with the original second operand.
1920 if (OpKind == tok::arrow) {
1921 while (BaseType->isRecordType()) {
1922 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
1923 BaseExpr = (Expr*)Base.get();
1924 if (BaseExpr == NULL)
1925 return ExprError();
1926 BaseType = BaseExpr->getType();
1927 }
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001930 if (BaseType->isPointerType())
1931 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001932
1933 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001934 // vector types or Objective-C interfaces. Just return early and let
1935 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00001936 if (!BaseType->isRecordType()) {
1937 // C++ [basic.lookup.classref]p2:
1938 // [...] If the type of the object expression is of pointer to scalar
1939 // type, the unqualified-id is looked up in the context of the complete
1940 // postfix-expression.
1941 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001942 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00001943 }
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Douglas Gregorc68afe22009-09-03 21:38:09 +00001945 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001946 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregorc68afe22009-09-03 21:38:09 +00001947 // unqualified-id, and the type of the object expres- sion is of a class
1948 // type C (or of pointer to a class type C), the unqualified-id is looked
1949 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001950 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00001951 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001952}
1953
Anders Carlssonec773872009-08-25 23:46:41 +00001954Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001955Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001956 SourceLocation OpLoc,
1957 tok::TokenKind OpKind,
1958 SourceLocation ClassNameLoc,
1959 IdentifierInfo *ClassName,
Douglas Gregora78c5c32009-09-04 18:29:40 +00001960 const CXXScopeSpec &SS,
1961 bool HasTrailingLParen) {
1962 if (SS.isInvalid())
Anders Carlssonec773872009-08-25 23:46:41 +00001963 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001964
Douglas Gregora71d8192009-09-04 17:36:40 +00001965 QualType BaseType;
Douglas Gregora78c5c32009-09-04 18:29:40 +00001966 if (isUnknownSpecialization(SS))
1967 BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora71d8192009-09-04 17:36:40 +00001968 ClassName);
1969 else {
Douglas Gregora78c5c32009-09-04 18:29:40 +00001970 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
Douglas Gregora71d8192009-09-04 17:36:40 +00001971 if (!BaseTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00001972 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
Douglas Gregora71d8192009-09-04 17:36:40 +00001973 << ClassName;
1974 return ExprError();
1975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregora71d8192009-09-04 17:36:40 +00001977 BaseType = GetTypeFromParser(BaseTy);
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001978 }
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001980 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00001981 DeclarationName DtorName =
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001982 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1983
Douglas Gregora78c5c32009-09-04 18:29:40 +00001984 OwningExprResult Result
1985 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1986 DtorName, DeclPtrTy(), &SS);
1987 if (Result.isInvalid() || HasTrailingLParen)
1988 return move(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
1990 // The only way a reference to a destructor can be used is to
Douglas Gregora78c5c32009-09-04 18:29:40 +00001991 // immediately call them. Since the next token is not a '(', produce a
1992 // diagnostic and build the call now.
1993 Expr *E = (Expr *)Result.get();
1994 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
1995 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
1996 << isa<CXXPseudoDestructorExpr>(E)
1997 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
Mike Stump1eb44332009-09-09 15:08:12 +00001998
1999 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
Douglas Gregora78c5c32009-09-04 18:29:40 +00002000 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlssonec773872009-08-25 23:46:41 +00002001}
2002
Douglas Gregora6f0f9d2009-08-31 19:52:13 +00002003Sema::OwningExprResult
2004Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2005 SourceLocation OpLoc,
2006 tok::TokenKind OpKind,
2007 SourceLocation ClassNameLoc,
2008 OverloadedOperatorKind OverOpKind,
2009 const CXXScopeSpec *SS) {
2010 if (SS && SS->isInvalid())
2011 return ExprError();
2012
2013 DeclarationName Name =
2014 Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2015
2016 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2017 Name, DeclPtrTy(), SS);
2018}
2019
2020Sema::OwningExprResult
2021Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2022 SourceLocation OpLoc,
2023 tok::TokenKind OpKind,
2024 SourceLocation ClassNameLoc,
2025 TypeTy *Ty,
2026 const CXXScopeSpec *SS) {
2027 if (SS && SS->isInvalid())
2028 return ExprError();
2029
2030 //FIXME: Preserve type source info.
2031 QualType ConvType = GetTypeFromParser(Ty);
2032 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2033 DeclarationName ConvName =
2034 Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2035
2036 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2037 ConvName, DeclPtrTy(), SS);
2038}
2039
Anders Carlsson0aebc812009-09-09 21:33:21 +00002040Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2041 QualType Ty,
2042 CastExpr::CastKind Kind,
2043 CXXMethodDecl *Method,
2044 ExprArg Arg) {
2045 Expr *From = Arg.takeAs<Expr>();
2046
2047 switch (Kind) {
2048 default: assert(0 && "Unhandled cast kind!");
2049 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002050 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2051
2052 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2053 MultiExprArg(*this, (void **)&From, 1),
2054 CastLoc, ConstructorArgs))
2055 return ExprError();
2056
Anders Carlsson0aebc812009-09-09 21:33:21 +00002057 return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Douglas Gregor39da0b82009-09-09 23:08:42 +00002058 move_arg(ConstructorArgs));
Anders Carlsson0aebc812009-09-09 21:33:21 +00002059 }
2060
2061 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002062 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2063
2064 // Cast to base if needed.
2065 if (PerformObjectArgumentInitialization(From, Method))
2066 return ExprError();
2067
Anders Carlsson0aebc812009-09-09 21:33:21 +00002068 // Create an implicit member expr to refer to the conversion operator.
2069 MemberExpr *ME =
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002070 new (Context) MemberExpr(From, /*IsArrow=*/false, Method,
Anders Carlsson0aebc812009-09-09 21:33:21 +00002071 SourceLocation(), Method->getType());
2072
2073
2074 // And an implicit call expr that calls it.
2075 QualType ResultType = Method->getResultType().getNonReferenceType();
2076 CXXMemberCallExpr *CE =
2077 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2078 ResultType,
2079 SourceLocation());
2080
2081 return Owned(CE);
2082 }
2083
2084 }
2085}
2086
Anders Carlsson165a0a02009-05-17 18:41:29 +00002087Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2088 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002089 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002090 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002091 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002092
Anders Carlssonec773872009-08-25 23:46:41 +00002093
Anders Carlsson165a0a02009-05-17 18:41:29 +00002094 return Owned(FullExpr);
2095}