blob: 98b3d29e531631fea20d50a95f89db3929dbcdcf [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);
Douglas Gregor2def4832008-11-17 20:34:05 +000038 DeclarationName ConvName
39 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000040 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000041 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000042}
Sebastian Redlc42e1182008-11-11 11:37:55 +000043
Douglas Gregor487a75a2008-11-19 19:09:45 +000044/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000045/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000049Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000050Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51 OverloadedOperatorKind Op,
52 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000053 const CXXScopeSpec &SS,
54 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000055 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000056 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000057 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000058}
59
Sebastian Redlc42e1182008-11-11 11:37:55 +000060/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000061Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000062Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000064 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000065 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000066 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000067
68 if (isType)
69 // FIXME: Preserve type source info.
70 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
Chris Lattner572af492008-11-20 05:51:55 +000072 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000073 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000074 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000075 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000076 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000077
78 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
Douglas Gregorac7610d2009-06-22 20:57:11 +000080 if (!isType) {
81 // C++0x [expr.typeid]p3:
82 // When typeid is applied to an expression other than an lvalue of a
83 // polymorphic class type [...] [the] expression is an unevaluated
84 // operand.
85
86 // 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 }
98
99 // 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 }
104
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();
Anders Carlsson26de5492009-04-24 05:23:13 +0000198
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000199 return Owned(CXXUnresolvedConstructExpr::Create(Context,
200 TypeRange.getBegin(), Ty,
201 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();
214
215 if (RequireNonAbstractType(TyBeginLoc, Ty,
216 diag::err_allocation_of_abstract_type))
217 return ExprError();
218
219
Douglas Gregor506ae412009-01-16 18:33:17 +0000220 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000221 // If the expression list is a single expression, the type conversion
222 // expression is equivalent (in definedness, and if defined in meaning) to the
223 // corresponding cast expression.
224 //
225 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000226 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000227 CXXMethodDecl *ConversionDecl = 0;
228 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, ConversionDecl,
229 /*functional-style*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000230 return ExprError();
231 exprs.release();
232 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000233 Ty, TyBeginLoc,
234 CastExpr::CK_UserDefinedConversion,
235 Exprs[0], ConversionDecl,
236 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000237 }
238
Ted Kremenek6217b802009-07-29 21:53:49 +0000239 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000240 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000241
Anders Carlssone7624a72009-08-27 05:08:22 +0000242 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
243 !Record->hasTrivialDestructor()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000244 CXXConstructorDecl *Constructor
245 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
246 TypeRange.getBegin(),
247 SourceRange(TypeRange.getBegin(),
248 RParenLoc),
249 DeclarationName(),
250 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000251
Sebastian Redlf53597f2009-03-15 17:47:39 +0000252 if (!Constructor)
253 return ExprError();
254
Anders Carlssone7624a72009-08-27 05:08:22 +0000255 OwningExprResult Result =
256 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
257 move(exprs), RParenLoc);
258 if (Result.isInvalid())
259 return ExprError();
260
261 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000262 }
263
264 // Fall through to value-initialize an object of class type that
265 // doesn't have a user-declared default constructor.
266 }
267
268 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000269 // If the expression list specifies more than a single value, the type shall
270 // be a class with a suitably declared constructor.
271 //
272 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000273 return ExprError(Diag(CommaLocs[0],
274 diag::err_builtin_func_cast_more_than_one_arg)
275 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000276
277 assert(NumExprs == 0 && "Expected 0 expressions");
278
Douglas Gregor506ae412009-01-16 18:33:17 +0000279 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000280 // The expression T(), where T is a simple-type-specifier for a non-array
281 // complete object type or the (possibly cv-qualified) void type, creates an
282 // rvalue of the specified type, which is value-initialized.
283 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000284 exprs.release();
285 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000286}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000287
288
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000289/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
290/// @code new (memory) int[size][4] @endcode
291/// or
292/// @code ::new Foo(23, "hello") @endcode
293/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000294Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000295Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000296 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000297 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000298 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000299 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000300 SourceLocation ConstructorRParen)
301{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000302 Expr *ArraySize = 0;
303 unsigned Skip = 0;
304 // If the specified type is an array, unwrap it and save the expression.
305 if (D.getNumTypeObjects() > 0 &&
306 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
307 DeclaratorChunk &Chunk = D.getTypeObject(0);
308 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000309 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
310 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000311 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
313 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000314 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
315 Skip = 1;
316 }
317
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000318 //FIXME: Store DeclaratorInfo in CXXNew expression.
319 DeclaratorInfo *DInfo = 0;
320 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000321 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000322 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000323
Douglas Gregor3433cf72009-05-21 00:00:09 +0000324 // Every dimension shall be of constant size.
325 unsigned i = 1;
326 QualType ElementType = AllocType;
327 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
328 if (!Array->isConstantArrayType()) {
329 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
330 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
331 return ExprError();
332 }
333 ElementType = Array->getElementType();
334 ++i;
335 }
336
337 return BuildCXXNew(StartLoc, UseGlobal,
338 PlacementLParen,
339 move(PlacementArgs),
340 PlacementRParen,
341 ParenTypeId,
342 AllocType,
343 D.getSourceRange().getBegin(),
344 D.getSourceRange(),
345 Owned(ArraySize),
346 ConstructorLParen,
347 move(ConstructorArgs),
348 ConstructorRParen);
349}
350
351Sema::OwningExprResult
352Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
353 SourceLocation PlacementLParen,
354 MultiExprArg PlacementArgs,
355 SourceLocation PlacementRParen,
356 bool ParenTypeId,
357 QualType AllocType,
358 SourceLocation TypeLoc,
359 SourceRange TypeRange,
360 ExprArg ArraySizeE,
361 SourceLocation ConstructorLParen,
362 MultiExprArg ConstructorArgs,
363 SourceLocation ConstructorRParen) {
364 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000365 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000366
Douglas Gregor3433cf72009-05-21 00:00:09 +0000367 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000368
369 // That every array dimension except the first is constant was already
370 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000371
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000372 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
373 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000374 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000375 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000376 QualType SizeType = ArraySize->getType();
377 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000378 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
379 diag::err_array_size_not_integral)
380 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000381 // Let's see if this is a constant < 0. If so, we reject it out of hand.
382 // We don't care about special rules, so we tell the machinery it's not
383 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000384 if (!ArraySize->isValueDependent()) {
385 llvm::APSInt Value;
386 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
387 if (Value < llvm::APSInt(
388 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000389 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
390 diag::err_typecheck_negative_array_size)
391 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000392 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000393 }
394 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000396 FunctionDecl *OperatorNew = 0;
397 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000398 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
399 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000400 if (!AllocType->isDependentType() &&
401 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
402 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000403 SourceRange(PlacementLParen, PlacementRParen),
404 UseGlobal, AllocType, ArraySize, PlaceArgs,
405 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000406 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000407
408 bool Init = ConstructorLParen.isValid();
409 // --- Choosing a constructor ---
410 // C++ 5.3.4p15
411 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
412 // the object is not initialized. If the object, or any part of it, is
413 // const-qualified, it's an error.
414 // 2) If T is a POD and there's an empty initializer, the object is value-
415 // initialized.
416 // 3) If T is a POD and there's one initializer argument, the object is copy-
417 // constructed.
418 // 4) If T is a POD and there's more initializer arguments, it's an error.
419 // 5) If T is not a POD, the initializer arguments are used as constructor
420 // arguments.
421 //
422 // Or by the C++0x formulation:
423 // 1) If there's no initializer, the object is default-initialized according
424 // to C++0x rules.
425 // 2) Otherwise, the object is direct-initialized.
426 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000427 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000428 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000430 if (AllocType->isDependentType()) {
431 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000432 } else if ((RT = AllocType->getAs<RecordType>()) &&
433 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000434 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000435 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000436 TypeLoc,
437 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000438 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000439 NumConsArgs != 0 ? IK_Direct : IK_Default);
440 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000441 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000442 } else {
443 if (!Init) {
444 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000445 if (AllocType.isConstQualified())
446 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000447 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000448 } else if (NumConsArgs == 0) {
449 // Object is value-initialized. Do nothing.
450 } else if (NumConsArgs == 1) {
451 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000452 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000453 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000454 DeclarationName() /*AllocType.getAsString()*/,
455 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000456 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000457 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000458 return ExprError(Diag(StartLoc,
459 diag::err_builtin_direct_init_more_than_one_arg)
460 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000461 }
462 }
463
464 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
465
Sebastian Redlf53597f2009-03-15 17:47:39 +0000466 PlacementArgs.release();
467 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000468 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000469 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000470 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000471 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000472 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000473}
474
475/// CheckAllocatedType - Checks that a type is suitable as the allocated type
476/// in a new-expression.
477/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000478bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
479 SourceRange R)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000480{
481 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
482 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000483 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000484 return Diag(Loc, diag::err_bad_new_type)
485 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000486 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000487 return Diag(Loc, diag::err_bad_new_type)
488 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000489 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000490 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000491 PDiag(diag::err_new_incomplete_type)
492 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000493 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000494 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000495 diag::err_allocation_of_abstract_type))
496 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000497
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000498 return false;
499}
500
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000501/// FindAllocationFunctions - Finds the overloads of operator new and delete
502/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000503bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
504 bool UseGlobal, QualType AllocType,
505 bool IsArray, Expr **PlaceArgs,
506 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000507 FunctionDecl *&OperatorNew,
508 FunctionDecl *&OperatorDelete)
509{
510 // --- Choosing an allocation function ---
511 // C++ 5.3.4p8 - 14 & 18
512 // 1) If UseGlobal is true, only look in the global scope. Else, also look
513 // in the scope of the allocated class.
514 // 2) If an array size is given, look for operator new[], else look for
515 // operator new.
516 // 3) The first argument is always size_t. Append the arguments from the
517 // placement form.
518 // FIXME: Also find the appropriate delete operator.
519
520 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
521 // We don't care about the actual value of this argument.
522 // FIXME: Should the Sema create the expression and embed it in the syntax
523 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000524 IntegerLiteral Size(llvm::APInt::getNullValue(
525 Context.Target.getPointerWidth(0)),
526 Context.getSizeType(),
527 SourceLocation());
528 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000529 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
530
531 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
532 IsArray ? OO_Array_New : OO_New);
533 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000534 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000535 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000536 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000537 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000538 AllocArgs.size(), Record, /*AllowMissing=*/true,
539 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000540 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000541 }
542 if (!OperatorNew) {
543 // Didn't find a member overload. Look for a global one.
544 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000545 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000546 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000547 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
548 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000549 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000550 }
551
Anders Carlssond9583892009-05-31 20:26:12 +0000552 // FindAllocationOverload can change the passed in arguments, so we need to
553 // copy them back.
554 if (NumPlaceArgs > 0)
555 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
556
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000557 return false;
558}
559
Sebastian Redl7f662392008-12-04 22:20:51 +0000560/// FindAllocationOverload - Find an fitting overload for the allocation
561/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000562bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
563 DeclarationName Name, Expr** Args,
564 unsigned NumArgs, DeclContext *Ctx,
565 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000566{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000567 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000568 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000569 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000570 if (AllowMissing)
571 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000572 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000573 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000574 }
575
576 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000577 for (; Alloc != AllocEnd; ++Alloc) {
578 // Even member operator new/delete are implicitly treated as
579 // static, so don't use AddMemberCandidate.
580 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
581 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
582 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000583 }
584
585 // Do the resolution.
586 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000587 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000588 case OR_Success: {
589 // Got one!
590 FunctionDecl *FnDecl = Best->Function;
591 // The first argument is size_t, and the first parameter must be size_t,
592 // too. This is checked on declaration and can be assumed. (It can't be
593 // asserted on, though, since invalid decls are left in there.)
594 for (unsigned i = 1; i < NumArgs; ++i) {
595 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000596 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000597 FnDecl->getParamDecl(i)->getType(),
598 "passing"))
599 return true;
600 }
601 Operator = FnDecl;
602 return false;
603 }
604
605 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000606 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000607 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000608 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
609 return true;
610
611 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000612 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000613 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000614 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
615 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000616
617 case OR_Deleted:
618 Diag(StartLoc, diag::err_ovl_deleted_call)
619 << Best->Function->isDeleted()
620 << Name << Range;
621 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
622 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000623 }
624 assert(false && "Unreachable, bad result from BestViableFunction");
625 return true;
626}
627
628
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000629/// DeclareGlobalNewDelete - Declare the global forms of operator new and
630/// delete. These are:
631/// @code
632/// void* operator new(std::size_t) throw(std::bad_alloc);
633/// void* operator new[](std::size_t) throw(std::bad_alloc);
634/// void operator delete(void *) throw();
635/// void operator delete[](void *) throw();
636/// @endcode
637/// Note that the placement and nothrow forms of new are *not* implicitly
638/// declared. Their use requires including \<new\>.
639void Sema::DeclareGlobalNewDelete()
640{
641 if (GlobalNewDeleteDeclared)
642 return;
643 GlobalNewDeleteDeclared = true;
644
645 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
646 QualType SizeT = Context.getSizeType();
647
648 // FIXME: Exception specifications are not added.
649 DeclareGlobalAllocationFunction(
650 Context.DeclarationNames.getCXXOperatorName(OO_New),
651 VoidPtr, SizeT);
652 DeclareGlobalAllocationFunction(
653 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
654 VoidPtr, SizeT);
655 DeclareGlobalAllocationFunction(
656 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
657 Context.VoidTy, VoidPtr);
658 DeclareGlobalAllocationFunction(
659 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
660 Context.VoidTy, VoidPtr);
661}
662
663/// DeclareGlobalAllocationFunction - Declares a single implicit global
664/// allocation function if it doesn't already exist.
665void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
666 QualType Return, QualType Argument)
667{
668 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
669
670 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000671 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000672 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000673 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000674 Alloc != AllocEnd; ++Alloc) {
675 // FIXME: Do we need to check for default arguments here?
676 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
677 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000678 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000679 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000680 }
681 }
682
683 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
684 FunctionDecl *Alloc =
685 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000686 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000687 Alloc->setImplicit();
688 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000689 0, Argument, /*DInfo=*/0,
690 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000691 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000692
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000693 // FIXME: Also add this declaration to the IdentifierResolver, but
694 // make sure it is at the end of the chain to coincide with the
695 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000696 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000697}
698
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000699/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
700/// @code ::delete ptr; @endcode
701/// or
702/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000703Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000704Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000705 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000706{
707 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
708 // having a single conversion function to a pointer type. The result has
709 // type void."
710 // DR599 amends "pointer type" to "pointer to object type" in both cases.
711
Anders Carlssond67c4c32009-08-16 20:29:29 +0000712 FunctionDecl *OperatorDelete = 0;
713
Sebastian Redlf53597f2009-03-15 17:47:39 +0000714 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000715 if (!Ex->isTypeDependent()) {
716 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000717
Sebastian Redl28507842009-02-26 14:39:58 +0000718 if (Type->isRecordType()) {
719 // FIXME: Find that one conversion function and amend the type.
720 }
721
Sebastian Redlf53597f2009-03-15 17:47:39 +0000722 if (!Type->isPointerType())
723 return ExprError(Diag(StartLoc, diag::err_delete_operand)
724 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000725
Ted Kremenek6217b802009-07-29 21:53:49 +0000726 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000727 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000728 return ExprError(Diag(StartLoc, diag::err_delete_operand)
729 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000730 else if (!Pointee->isDependentType() &&
731 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000732 PDiag(diag::warn_delete_incomplete)
733 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000734 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000735
Anders Carlssond67c4c32009-08-16 20:29:29 +0000736 // FIXME: This should be shared with the code for finding the delete
737 // operator in ActOnCXXNew.
738 IntegerLiteral Size(llvm::APInt::getNullValue(
739 Context.Target.getPointerWidth(0)),
740 Context.getSizeType(),
741 SourceLocation());
742 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
743 CastExpr::CK_Unknown, &Size, false);
744 Expr *DeleteArg = &Cast;
745
746 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
747 ArrayForm ? OO_Array_Delete : OO_Delete);
748
749 if (Pointee->isRecordType() && !UseGlobal) {
750 CXXRecordDecl *Record
751 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
752 // FIXME: We fail to find inherited overloads.
753 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
754 &DeleteArg, 1, Record, /*AllowMissing=*/true,
755 OperatorDelete))
756 return ExprError();
757 }
758
759 if (!OperatorDelete) {
760 // Didn't find a member overload. Look for a global one.
761 DeclareGlobalNewDelete();
762 DeclContext *TUDecl = Context.getTranslationUnitDecl();
763 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
764 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
765 OperatorDelete))
766 return ExprError();
767 }
768
Sebastian Redl28507842009-02-26 14:39:58 +0000769 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000770 }
771
Sebastian Redlf53597f2009-03-15 17:47:39 +0000772 Operand.release();
773 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000774 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000775}
776
777
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000778/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
779/// C++ if/switch/while/for statement.
780/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000781Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000782Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
783 Declarator &D,
784 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000785 ExprArg AssignExprVal) {
786 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000787
788 // C++ 6.4p2:
789 // The declarator shall not specify a function or an array.
790 // The type-specifier-seq shall not contain typedef and shall not declare a
791 // new class or enumeration.
792
793 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
794 "Parser allowed 'typedef' as storage class of condition decl.");
795
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000796 // FIXME: Store DeclaratorInfo in the expression.
797 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000798 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000799 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000800
801 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
802 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
803 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000804 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
805 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000806 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000807 Diag(StartLoc, diag::err_invalid_use_of_array_type)
808 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000809 } else if (OwnedTag && OwnedTag->isDefinition()) {
810 // The type-specifier-seq shall not declare a new class or enumeration.
811 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000812 }
813
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000814 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000815 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000816 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000817 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000818
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000819 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000820 // We know that the decl had to be a VarDecl because that is the only type of
821 // decl that can be assigned and the grammar requires an '='.
822 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
823 VD->setDeclaredInCondition(true);
824 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000825}
826
827/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
828bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
829 // C++ 6.4p4:
830 // The value of a condition that is an initialized declaration in a statement
831 // other than a switch statement is the value of the declared variable
832 // implicitly converted to type bool. If that conversion is ill-formed, the
833 // program is ill-formed.
834 // The value of a condition that is an expression is the value of the
835 // expression, implicitly converted to bool.
836 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000837 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000838}
Douglas Gregor77a52232008-09-12 00:47:35 +0000839
840/// Helper function to determine whether this is the (deprecated) C++
841/// conversion from a string literal to a pointer to non-const char or
842/// non-const wchar_t (for narrow and wide string literals,
843/// respectively).
844bool
845Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
846 // Look inside the implicit cast, if it exists.
847 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
848 From = Cast->getSubExpr();
849
850 // A string literal (2.13.4) that is not a wide string literal can
851 // be converted to an rvalue of type "pointer to char"; a wide
852 // string literal can be converted to an rvalue of type "pointer
853 // to wchar_t" (C++ 4.2p2).
854 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000855 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor77a52232008-09-12 00:47:35 +0000856 if (const BuiltinType *ToPointeeType
857 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
858 // This conversion is considered only when there is an
859 // explicit appropriate pointer target type (C++ 4.2p2).
860 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
861 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
862 (!StrLit->isWide() &&
863 (ToPointeeType->getKind() == BuiltinType::Char_U ||
864 ToPointeeType->getKind() == BuiltinType::Char_S))))
865 return true;
866 }
867
868 return false;
869}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000870
871/// PerformImplicitConversion - Perform an implicit conversion of the
872/// expression From to the type ToType. Returns true if there was an
873/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000874/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000875/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000876/// explicit user-defined conversions are permitted. @p Elidable should be true
877/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
878/// resolution works differently in that case.
879bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000880Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000881 const char *Flavor, bool AllowExplicit,
882 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000883{
Sebastian Redle2b68332009-04-12 17:16:29 +0000884 ImplicitConversionSequence ICS;
885 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
886 if (Elidable && getLangOptions().CPlusPlus0x) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000887 ICS = TryImplicitConversion(From, ToType,
888 /*SuppressUserConversions=*/false,
889 AllowExplicit,
890 /*ForceRValue=*/true);
Sebastian Redle2b68332009-04-12 17:16:29 +0000891 }
892 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000893 ICS = TryImplicitConversion(From, ToType,
894 /*SuppressUserConversions=*/false,
895 AllowExplicit,
896 /*ForceRValue=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000897 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000898 return PerformImplicitConversion(From, ToType, ICS, Flavor);
899}
900
901/// PerformImplicitConversion - Perform an implicit conversion of the
902/// expression From to the type ToType using the pre-computed implicit
903/// conversion sequence ICS. Returns true if there was an error, false
904/// otherwise. The expression From is replaced with the converted
905/// expression. Flavor is the kind of conversion we're performing,
906/// used in the error message.
907bool
908Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
909 const ImplicitConversionSequence &ICS,
910 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000911 switch (ICS.ConversionKind) {
912 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000913 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000914 return true;
915 break;
916
917 case ImplicitConversionSequence::UserDefinedConversion:
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000918 // FIXME. Support other kinds of user defined convesions.
919 if (CXXConversionDecl *CV =
920 dyn_cast<CXXConversionDecl>(ICS.UserDefined.ConversionFunction))
921 // FIXME. Get actual Source Location.
922 From =
923 new (Context) CXXFunctionalCastExpr(ToType.getNonReferenceType(),
924 ToType, SourceLocation(),
925 CastExpr::CK_UserDefinedConversion,
926 From, CV,
927 SourceLocation());
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000928 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +0000929 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000930 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000931 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000932
933 case ImplicitConversionSequence::EllipsisConversion:
934 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000935 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000936
937 case ImplicitConversionSequence::BadConversion:
938 return true;
939 }
940
941 // Everything went well.
942 return false;
943}
944
945/// PerformImplicitConversion - Perform an implicit conversion of the
946/// expression From to the type ToType by following the standard
947/// conversion sequence SCS. Returns true if there was an error, false
948/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000949/// expression. Flavor is the context in which we're performing this
950/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000951bool
952Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000953 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000954 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000955 // Overall FIXME: we are recomputing too many types here and doing far too
956 // much extra work. What this means is that we need to keep track of more
957 // information that is computed when we try the implicit conversion initially,
958 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000959 QualType FromType = From->getType();
960
Douglas Gregor225c41e2008-11-03 19:09:14 +0000961 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000962 // FIXME: When can ToType be a reference type?
963 assert(!ToType->isReferenceType());
964
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000965 OwningExprResult FromResult =
966 BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
967
968 if (FromResult.isInvalid())
969 return true;
970
971 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000972 return false;
973 }
974
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000975 // Perform the first implicit conversion.
976 switch (SCS.First) {
977 case ICK_Identity:
978 case ICK_Lvalue_To_Rvalue:
979 // Nothing to do.
980 break;
981
982 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000983 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +0000984 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000985 break;
986
987 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000988 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000989 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
990 if (!Fn)
991 return true;
992
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000993 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
994 return true;
995
Douglas Gregor904eed32008-11-10 20:40:00 +0000996 FixOverloadedFunctionReference(From, Fn);
997 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000998 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000999 FromType = Context.getPointerType(FromType);
1000 ImpCastExprToType(From, FromType);
1001 break;
1002
1003 default:
1004 assert(false && "Improper first standard conversion");
1005 break;
1006 }
1007
1008 // Perform the second implicit conversion
1009 switch (SCS.Second) {
1010 case ICK_Identity:
1011 // Nothing to do.
1012 break;
1013
1014 case ICK_Integral_Promotion:
1015 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001016 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001017 case ICK_Integral_Conversion:
1018 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001019 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001020 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001021 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001022 case ICK_Compatible_Conversion:
1023 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001024 FromType = ToType.getUnqualifiedType();
1025 ImpCastExprToType(From, FromType);
1026 break;
1027
1028 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001029 if (SCS.IncompatibleObjC) {
1030 // Diagnose incompatible Objective-C conversions
1031 Diag(From->getSourceRange().getBegin(),
1032 diag::ext_typecheck_convert_incompatible_pointer)
1033 << From->getType() << ToType << Flavor
1034 << From->getSourceRange();
1035 }
1036
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001037 if (CheckPointerConversion(From, ToType))
1038 return true;
1039 ImpCastExprToType(From, ToType);
1040 break;
1041
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001042 case ICK_Pointer_Member: {
1043 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1044 if (CheckMemberPointerConversion(From, ToType, Kind))
1045 return true;
1046 ImpCastExprToType(From, ToType, Kind);
1047 break;
1048 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001049 case ICK_Boolean_Conversion:
1050 FromType = Context.BoolTy;
1051 ImpCastExprToType(From, FromType);
1052 break;
1053
1054 default:
1055 assert(false && "Improper second standard conversion");
1056 break;
1057 }
1058
1059 switch (SCS.Third) {
1060 case ICK_Identity:
1061 // Nothing to do.
1062 break;
1063
1064 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001065 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1066 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +00001067 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001068 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001069 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001070 break;
1071
1072 default:
1073 assert(false && "Improper second standard conversion");
1074 break;
1075 }
1076
1077 return false;
1078}
1079
Sebastian Redl64b45f72009-01-05 20:52:13 +00001080Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1081 SourceLocation KWLoc,
1082 SourceLocation LParen,
1083 TypeTy *Ty,
1084 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001085 QualType T = GetTypeFromParser(Ty);
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001086
1087 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1088 // all traits except __is_class, __is_enum and __is_union require a the type
1089 // to be complete.
1090 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1091 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001092 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001093 return ExprError();
1094 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001095
1096 // There is no point in eagerly computing the value. The traits are designed
1097 // to be used from type trait templates, so Ty will be a template parameter
1098 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001099 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1100 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001101}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001102
1103QualType Sema::CheckPointerToMemberOperands(
1104 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1105{
1106 const char *OpSpelling = isIndirect ? "->*" : ".*";
1107 // C++ 5.5p2
1108 // The binary operator .* [p3: ->*] binds its second operand, which shall
1109 // be of type "pointer to member of T" (where T is a completely-defined
1110 // class type) [...]
1111 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001112 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001113 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001114 Diag(Loc, diag::err_bad_memptr_rhs)
1115 << OpSpelling << RType << rex->getSourceRange();
1116 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001117 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001118
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001119 QualType Class(MemPtr->getClass(), 0);
1120
1121 // C++ 5.5p2
1122 // [...] to its first operand, which shall be of class T or of a class of
1123 // which T is an unambiguous and accessible base class. [p3: a pointer to
1124 // such a class]
1125 QualType LType = lex->getType();
1126 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001127 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001128 LType = Ptr->getPointeeType().getNonReferenceType();
1129 else {
1130 Diag(Loc, diag::err_bad_memptr_lhs)
1131 << OpSpelling << 1 << LType << lex->getSourceRange();
1132 return QualType();
1133 }
1134 }
1135
1136 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1137 Context.getCanonicalType(LType).getUnqualifiedType()) {
1138 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1139 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001140 // FIXME: Would it be useful to print full ambiguity paths, or is that
1141 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001142 if (!IsDerivedFrom(LType, Class, Paths) ||
1143 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1144 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1145 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1146 return QualType();
1147 }
1148 }
1149
1150 // C++ 5.5p2
1151 // The result is an object or a function of the type specified by the
1152 // second operand.
1153 // The cv qualifiers are the union of those in the pointer and the left side,
1154 // in accordance with 5.5p5 and 5.2.5.
1155 // FIXME: This returns a dereferenced member function pointer as a normal
1156 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001157 // calling them. There's also a GCC extension to get a function pointer to the
1158 // thing, which is another complication, because this type - unlike the type
1159 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001160 // argument.
1161 // We probably need a "MemberFunctionClosureType" or something like that.
1162 QualType Result = MemPtr->getPointeeType();
1163 if (LType.isConstQualified())
1164 Result.addConst();
1165 if (LType.isVolatileQualified())
1166 Result.addVolatile();
1167 return Result;
1168}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001169
1170/// \brief Get the target type of a standard or user-defined conversion.
1171static QualType TargetType(const ImplicitConversionSequence &ICS) {
1172 assert((ICS.ConversionKind ==
1173 ImplicitConversionSequence::StandardConversion ||
1174 ICS.ConversionKind ==
1175 ImplicitConversionSequence::UserDefinedConversion) &&
1176 "function only valid for standard or user-defined conversions");
1177 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1178 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1179 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1180}
1181
1182/// \brief Try to convert a type to another according to C++0x 5.16p3.
1183///
1184/// This is part of the parameter validation for the ? operator. If either
1185/// value operand is a class type, the two operands are attempted to be
1186/// converted to each other. This function does the conversion in one direction.
1187/// It emits a diagnostic and returns true only if it finds an ambiguous
1188/// conversion.
1189static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1190 SourceLocation QuestionLoc,
1191 ImplicitConversionSequence &ICS)
1192{
1193 // C++0x 5.16p3
1194 // The process for determining whether an operand expression E1 of type T1
1195 // can be converted to match an operand expression E2 of type T2 is defined
1196 // as follows:
1197 // -- If E2 is an lvalue:
1198 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1199 // E1 can be converted to match E2 if E1 can be implicitly converted to
1200 // type "lvalue reference to T2", subject to the constraint that in the
1201 // conversion the reference must bind directly to E1.
1202 if (!Self.CheckReferenceInit(From,
1203 Self.Context.getLValueReferenceType(To->getType()),
1204 &ICS))
1205 {
1206 assert((ICS.ConversionKind ==
1207 ImplicitConversionSequence::StandardConversion ||
1208 ICS.ConversionKind ==
1209 ImplicitConversionSequence::UserDefinedConversion) &&
1210 "expected a definite conversion");
1211 bool DirectBinding =
1212 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1213 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1214 if (DirectBinding)
1215 return false;
1216 }
1217 }
1218 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1219 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1220 // -- if E1 and E2 have class type, and the underlying class types are
1221 // the same or one is a base class of the other:
1222 QualType FTy = From->getType();
1223 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001224 const RecordType *FRec = FTy->getAs<RecordType>();
1225 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001226 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1227 if (FRec && TRec && (FRec == TRec ||
1228 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1229 // E1 can be converted to match E2 if the class of T2 is the
1230 // same type as, or a base class of, the class of T1, and
1231 // [cv2 > cv1].
1232 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1233 // Could still fail if there's no copy constructor.
1234 // FIXME: Is this a hard error then, or just a conversion failure? The
1235 // standard doesn't say.
Anders Carlssond28b4282009-08-27 17:18:13 +00001236 ICS = Self.TryCopyInitialization(From, TTy,
1237 /*SuppressUserConversions=*/false,
1238 /*ForceRValue=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001239 }
1240 } else {
1241 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1242 // implicitly converted to the type that expression E2 would have
1243 // if E2 were converted to an rvalue.
1244 // First find the decayed type.
1245 if (TTy->isFunctionType())
1246 TTy = Self.Context.getPointerType(TTy);
1247 else if(TTy->isArrayType())
1248 TTy = Self.Context.getArrayDecayedType(TTy);
1249
1250 // Now try the implicit conversion.
1251 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001252 ICS = Self.TryImplicitConversion(From, TTy,
1253 /*SuppressUserConversions=*/false,
1254 /*AllowExplicit=*/false,
1255 /*ForceRValue=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001256 }
1257 return false;
1258}
1259
1260/// \brief Try to find a common type for two according to C++0x 5.16p5.
1261///
1262/// This is part of the parameter validation for the ? operator. If either
1263/// value operand is a class type, overload resolution is used to find a
1264/// conversion to a common type.
1265static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1266 SourceLocation Loc) {
1267 Expr *Args[2] = { LHS, RHS };
1268 OverloadCandidateSet CandidateSet;
1269 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1270
1271 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001272 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001273 case Sema::OR_Success:
1274 // We found a match. Perform the conversions on the arguments and move on.
1275 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1276 Best->Conversions[0], "converting") ||
1277 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1278 Best->Conversions[1], "converting"))
1279 break;
1280 return false;
1281
1282 case Sema::OR_No_Viable_Function:
1283 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1284 << LHS->getType() << RHS->getType()
1285 << LHS->getSourceRange() << RHS->getSourceRange();
1286 return true;
1287
1288 case Sema::OR_Ambiguous:
1289 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1290 << LHS->getType() << RHS->getType()
1291 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001292 // FIXME: Print the possible common types by printing the return types of
1293 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001294 break;
1295
1296 case Sema::OR_Deleted:
1297 assert(false && "Conditional operator has only built-in overloads");
1298 break;
1299 }
1300 return true;
1301}
1302
Sebastian Redl76458502009-04-17 16:30:52 +00001303/// \brief Perform an "extended" implicit conversion as returned by
1304/// TryClassUnification.
1305///
1306/// TryClassUnification generates ICSs that include reference bindings.
1307/// PerformImplicitConversion is not suitable for this; it chokes if the
1308/// second part of a standard conversion is ICK_DerivedToBase. This function
1309/// handles the reference binding specially.
1310static bool ConvertForConditional(Sema &Self, Expr *&E,
1311 const ImplicitConversionSequence &ICS)
1312{
1313 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1314 ICS.Standard.ReferenceBinding) {
1315 assert(ICS.Standard.DirectBinding &&
1316 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001317 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1318 // redoing all the work.
1319 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1320 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001321 }
1322 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1323 ICS.UserDefined.After.ReferenceBinding) {
1324 assert(ICS.UserDefined.After.DirectBinding &&
1325 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001326 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1327 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001328 }
1329 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1330 return true;
1331 return false;
1332}
1333
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001334/// \brief Check the operands of ?: under C++ semantics.
1335///
1336/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1337/// extension. In this case, LHS == Cond. (But they're not aliases.)
1338QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1339 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001340 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1341 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001342
1343 // C++0x 5.16p1
1344 // The first expression is contextually converted to bool.
1345 if (!Cond->isTypeDependent()) {
1346 if (CheckCXXBooleanCondition(Cond))
1347 return QualType();
1348 }
1349
1350 // Either of the arguments dependent?
1351 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1352 return Context.DependentTy;
1353
1354 // C++0x 5.16p2
1355 // If either the second or the third operand has type (cv) void, ...
1356 QualType LTy = LHS->getType();
1357 QualType RTy = RHS->getType();
1358 bool LVoid = LTy->isVoidType();
1359 bool RVoid = RTy->isVoidType();
1360 if (LVoid || RVoid) {
1361 // ... then the [l2r] conversions are performed on the second and third
1362 // operands ...
1363 DefaultFunctionArrayConversion(LHS);
1364 DefaultFunctionArrayConversion(RHS);
1365 LTy = LHS->getType();
1366 RTy = RHS->getType();
1367
1368 // ... and one of the following shall hold:
1369 // -- The second or the third operand (but not both) is a throw-
1370 // expression; the result is of the type of the other and is an rvalue.
1371 bool LThrow = isa<CXXThrowExpr>(LHS);
1372 bool RThrow = isa<CXXThrowExpr>(RHS);
1373 if (LThrow && !RThrow)
1374 return RTy;
1375 if (RThrow && !LThrow)
1376 return LTy;
1377
1378 // -- Both the second and third operands have type void; the result is of
1379 // type void and is an rvalue.
1380 if (LVoid && RVoid)
1381 return Context.VoidTy;
1382
1383 // Neither holds, error.
1384 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1385 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1386 << LHS->getSourceRange() << RHS->getSourceRange();
1387 return QualType();
1388 }
1389
1390 // Neither is void.
1391
1392 // C++0x 5.16p3
1393 // Otherwise, if the second and third operand have different types, and
1394 // either has (cv) class type, and attempt is made to convert each of those
1395 // operands to the other.
1396 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1397 (LTy->isRecordType() || RTy->isRecordType())) {
1398 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1399 // These return true if a single direction is already ambiguous.
1400 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1401 return QualType();
1402 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1403 return QualType();
1404
1405 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1406 ImplicitConversionSequence::BadConversion;
1407 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1408 ImplicitConversionSequence::BadConversion;
1409 // If both can be converted, [...] the program is ill-formed.
1410 if (HaveL2R && HaveR2L) {
1411 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1412 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1413 return QualType();
1414 }
1415
1416 // If exactly one conversion is possible, that conversion is applied to
1417 // the chosen operand and the converted operands are used in place of the
1418 // original operands for the remainder of this section.
1419 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001420 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001421 return QualType();
1422 LTy = LHS->getType();
1423 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001424 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001425 return QualType();
1426 RTy = RHS->getType();
1427 }
1428 }
1429
1430 // C++0x 5.16p4
1431 // If the second and third operands are lvalues and have the same type,
1432 // the result is of that type [...]
1433 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1434 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1435 RHS->isLvalue(Context) == Expr::LV_Valid)
1436 return LTy;
1437
1438 // C++0x 5.16p5
1439 // Otherwise, the result is an rvalue. If the second and third operands
1440 // do not have the same type, and either has (cv) class type, ...
1441 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1442 // ... overload resolution is used to determine the conversions (if any)
1443 // to be applied to the operands. If the overload resolution fails, the
1444 // program is ill-formed.
1445 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1446 return QualType();
1447 }
1448
1449 // C++0x 5.16p6
1450 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1451 // conversions are performed on the second and third operands.
1452 DefaultFunctionArrayConversion(LHS);
1453 DefaultFunctionArrayConversion(RHS);
1454 LTy = LHS->getType();
1455 RTy = RHS->getType();
1456
1457 // After those conversions, one of the following shall hold:
1458 // -- The second and third operands have the same type; the result
1459 // is of that type.
1460 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1461 return LTy;
1462
1463 // -- The second and third operands have arithmetic or enumeration type;
1464 // the usual arithmetic conversions are performed to bring them to a
1465 // common type, and the result is of that type.
1466 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1467 UsualArithmeticConversions(LHS, RHS);
1468 return LHS->getType();
1469 }
1470
1471 // -- The second and third operands have pointer type, or one has pointer
1472 // type and the other is a null pointer constant; pointer conversions
1473 // and qualification conversions are performed to bring them to their
1474 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001475 QualType Composite = FindCompositePointerType(LHS, RHS);
1476 if (!Composite.isNull())
1477 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001478
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001479 // Fourth bullet is same for pointers-to-member. However, the possible
1480 // conversions are far more limited: we have null-to-pointer, upcast of
1481 // containing class, and second-level cv-ness.
1482 // cv-ness is not a union, but must match one of the two operands. (Which,
1483 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001484 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1485 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001486 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1487 ImpCastExprToType(RHS, LTy);
1488 return LTy;
1489 }
1490 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1491 ImpCastExprToType(LHS, RTy);
1492 return RTy;
1493 }
1494 if (LMemPtr && RMemPtr) {
1495 QualType LPointee = LMemPtr->getPointeeType();
1496 QualType RPointee = RMemPtr->getPointeeType();
1497 // First, we check that the unqualified pointee type is the same. If it's
1498 // not, there's no conversion that will unify the two pointers.
1499 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1500 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1501 // Second, we take the greater of the two cv qualifications. If neither
1502 // is greater than the other, the conversion is not possible.
1503 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1504 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1505 // Third, we check if either of the container classes is derived from
1506 // the other.
1507 QualType LContainer(LMemPtr->getClass(), 0);
1508 QualType RContainer(RMemPtr->getClass(), 0);
1509 QualType MoreDerived;
1510 if (Context.getCanonicalType(LContainer) ==
1511 Context.getCanonicalType(RContainer))
1512 MoreDerived = LContainer;
1513 else if (IsDerivedFrom(LContainer, RContainer))
1514 MoreDerived = LContainer;
1515 else if (IsDerivedFrom(RContainer, LContainer))
1516 MoreDerived = RContainer;
1517
1518 if (!MoreDerived.isNull()) {
1519 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1520 // We don't use ImpCastExprToType here because this could still fail
1521 // for ambiguous or inaccessible conversions.
1522 QualType Common = Context.getMemberPointerType(
1523 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1524 if (PerformImplicitConversion(LHS, Common, "converting"))
1525 return QualType();
1526 if (PerformImplicitConversion(RHS, Common, "converting"))
1527 return QualType();
1528 return Common;
1529 }
1530 }
1531 }
1532 }
1533
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001534 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1535 << LHS->getType() << RHS->getType()
1536 << LHS->getSourceRange() << RHS->getSourceRange();
1537 return QualType();
1538}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001539
1540/// \brief Find a merged pointer type and convert the two expressions to it.
1541///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001542/// This finds the composite pointer type (or member pointer type) for @p E1
1543/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1544/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001545/// It does not emit diagnostics.
1546QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1547 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1548 QualType T1 = E1->getType(), T2 = E2->getType();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001549
1550 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1551 !T2->isPointerType() && !T2->isMemberPointerType())
1552 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001553
Douglas Gregor20b3e992009-08-24 17:42:35 +00001554 // FIXME: Do we need to work on the canonical types?
1555
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001556 // C++0x 5.9p2
1557 // Pointer conversions and qualification conversions are performed on
1558 // pointer operands to bring them to their composite pointer type. If
1559 // one operand is a null pointer constant, the composite pointer type is
1560 // the type of the other operand.
1561 if (E1->isNullPointerConstant(Context)) {
1562 ImpCastExprToType(E1, T2);
1563 return T2;
1564 }
1565 if (E2->isNullPointerConstant(Context)) {
1566 ImpCastExprToType(E2, T1);
1567 return T1;
1568 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00001569
1570 // Now both have to be pointers or member pointers.
1571 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1572 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001573 return QualType();
1574
1575 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1576 // the other has type "pointer to cv2 T" and the composite pointer type is
1577 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1578 // Otherwise, the composite pointer type is a pointer type similar to the
1579 // type of one of the operands, with a cv-qualification signature that is
1580 // the union of the cv-qualification signatures of the operand types.
1581 // In practice, the first part here is redundant; it's subsumed by the second.
1582 // What we do here is, we build the two possible composite types, and try the
1583 // conversions in both directions. If only one works, or if the two composite
1584 // types are the same, we have succeeded.
1585 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001586 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001587 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001588 do {
1589 const PointerType *Ptr1, *Ptr2;
1590 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1591 (Ptr2 = Composite2->getAs<PointerType>())) {
1592 Composite1 = Ptr1->getPointeeType();
1593 Composite2 = Ptr2->getPointeeType();
1594 QualifierUnion.push_back(
1595 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1596 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1597 continue;
1598 }
1599
1600 const MemberPointerType *MemPtr1, *MemPtr2;
1601 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1602 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1603 Composite1 = MemPtr1->getPointeeType();
1604 Composite2 = MemPtr2->getPointeeType();
1605 QualifierUnion.push_back(
1606 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1607 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1608 MemPtr2->getClass()));
1609 continue;
1610 }
1611
1612 // FIXME: block pointer types?
1613
1614 // Cannot unwrap any more types.
1615 break;
1616 } while (true);
1617
1618 // Rewrap the composites as pointers or member pointers with the union CVRs.
1619 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1620 = MemberOfClass.begin();
1621 for (llvm::SmallVector<unsigned, 4>::iterator
1622 I = QualifierUnion.begin(),
1623 E = QualifierUnion.end();
1624 I != E; (void)++I, ++MOC) {
1625 if (MOC->first && MOC->second) {
1626 // Rebuild member pointer type
1627 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1628 MOC->first);
1629 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1630 MOC->second);
1631 } else {
1632 // Rebuild pointer type
1633 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1634 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1635 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001636 }
1637
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001638 ImplicitConversionSequence E1ToC1 =
1639 TryImplicitConversion(E1, Composite1,
1640 /*SuppressUserConversions=*/false,
1641 /*AllowExplicit=*/false,
1642 /*ForceRValue=*/false);
1643 ImplicitConversionSequence E2ToC1 =
1644 TryImplicitConversion(E2, Composite1,
1645 /*SuppressUserConversions=*/false,
1646 /*AllowExplicit=*/false,
1647 /*ForceRValue=*/false);
1648
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001649 ImplicitConversionSequence E1ToC2, E2ToC2;
1650 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1651 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1652 if (Context.getCanonicalType(Composite1) !=
1653 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001654 E1ToC2 = TryImplicitConversion(E1, Composite2,
1655 /*SuppressUserConversions=*/false,
1656 /*AllowExplicit=*/false,
1657 /*ForceRValue=*/false);
1658 E2ToC2 = TryImplicitConversion(E2, Composite2,
1659 /*SuppressUserConversions=*/false,
1660 /*AllowExplicit=*/false,
1661 /*ForceRValue=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001662 }
1663
1664 bool ToC1Viable = E1ToC1.ConversionKind !=
1665 ImplicitConversionSequence::BadConversion
1666 && E2ToC1.ConversionKind !=
1667 ImplicitConversionSequence::BadConversion;
1668 bool ToC2Viable = E1ToC2.ConversionKind !=
1669 ImplicitConversionSequence::BadConversion
1670 && E2ToC2.ConversionKind !=
1671 ImplicitConversionSequence::BadConversion;
1672 if (ToC1Viable && !ToC2Viable) {
1673 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1674 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1675 return Composite1;
1676 }
1677 if (ToC2Viable && !ToC1Viable) {
1678 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1679 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1680 return Composite2;
1681 }
1682 return QualType();
1683}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001684
Anders Carlssondef11992009-05-30 20:36:53 +00001685Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001686 if (!Context.getLangOptions().CPlusPlus)
1687 return Owned(E);
1688
Ted Kremenek6217b802009-07-29 21:53:49 +00001689 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001690 if (!RT)
1691 return Owned(E);
1692
1693 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1694 if (RD->hasTrivialDestructor())
1695 return Owned(E);
1696
1697 CXXTemporary *Temp = CXXTemporary::Create(Context,
1698 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001699 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001700 if (CXXDestructorDecl *Destructor =
1701 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1702 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001703 // FIXME: Add the temporary to the temporaries vector.
1704 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1705}
1706
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001707Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001708 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001709 assert(SubExpr && "sub expression can't be null!");
1710
1711 if (ExprTemporaries.empty())
1712 return SubExpr;
1713
1714 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1715 &ExprTemporaries[0],
1716 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001717 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001718 ExprTemporaries.clear();
1719
1720 return E;
1721}
1722
Anders Carlssonec773872009-08-25 23:46:41 +00001723Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001724Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001725 SourceLocation OpLoc,
1726 tok::TokenKind OpKind,
1727 SourceLocation ClassNameLoc,
1728 IdentifierInfo *ClassName,
1729 const CXXScopeSpec *SS) {
1730 if (SS && SS->isInvalid())
1731 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001732
1733 Expr *BaseExpr = (Expr *)Base.get();
Anders Carlssonec773872009-08-25 23:46:41 +00001734
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001735 if (BaseExpr->isTypeDependent() ||
1736 (SS && isDependentScopeSpecifier(*SS))) {
1737 // FIXME: Return an unresolved ref expr.
1738 return ExprError();
1739 }
1740
1741 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, SS);
1742 if (!BaseTy) {
1743 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1744 << ClassName;
1745 return ExprError();
1746 }
Anders Carlssonec773872009-08-25 23:46:41 +00001747
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001748 QualType BaseType = GetTypeFromParser(BaseTy);
1749 if (!BaseType->isRecordType()) {
1750 Diag(ClassNameLoc, diag::err_type_in_pseudo_dtor_not_a_class_type)
1751 << BaseType;
1752 return ExprError();
1753 }
Anders Carlssonec773872009-08-25 23:46:41 +00001754
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001755 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
1756 DeclarationName DtorName =
1757 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1758
1759 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1760 DtorName, DeclPtrTy(), SS);
Anders Carlssonec773872009-08-25 23:46:41 +00001761}
1762
Anders Carlsson165a0a02009-05-17 18:41:29 +00001763Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1764 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001765 if (FullExpr)
Anders Carlssonf54741e2009-06-16 03:37:31 +00001766 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1767 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001768
Anders Carlssonec773872009-08-25 23:46:41 +00001769
Anders Carlsson165a0a02009-05-17 18:41:29 +00001770 return Owned(FullExpr);
1771}