blob: a4c3b0dd59459281e8bf1fd1019cb4d36e72133f [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 Carlsson165a0a02009-05-17 18:41:29 +0000242 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
243 // both the ctor and dtor are trivial.
Douglas Gregor506ae412009-01-16 18:33:17 +0000244 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
245 CXXConstructorDecl *Constructor
246 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
247 TypeRange.getBegin(),
248 SourceRange(TypeRange.getBegin(),
249 RParenLoc),
250 DeclarationName(),
251 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000252
Sebastian Redlf53597f2009-03-15 17:47:39 +0000253 if (!Constructor)
254 return ExprError();
255
256 exprs.release();
Anders Carlsson8e587a12009-05-30 20:56:46 +0000257 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssondef11992009-05-30 20:36:53 +0000258 Ty, TyBeginLoc, Exprs,
259 NumExprs, RParenLoc);
260 return MaybeBindToTemporary(E);
Douglas Gregor506ae412009-01-16 18:33:17 +0000261 }
262
263 // Fall through to value-initialize an object of class type that
264 // doesn't have a user-declared default constructor.
265 }
266
267 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000268 // If the expression list specifies more than a single value, the type shall
269 // be a class with a suitably declared constructor.
270 //
271 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000272 return ExprError(Diag(CommaLocs[0],
273 diag::err_builtin_func_cast_more_than_one_arg)
274 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000275
276 assert(NumExprs == 0 && "Expected 0 expressions");
277
Douglas Gregor506ae412009-01-16 18:33:17 +0000278 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000279 // The expression T(), where T is a simple-type-specifier for a non-array
280 // complete object type or the (possibly cv-qualified) void type, creates an
281 // rvalue of the specified type, which is value-initialized.
282 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000283 exprs.release();
284 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000285}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000286
287
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000288/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
289/// @code new (memory) int[size][4] @endcode
290/// or
291/// @code ::new Foo(23, "hello") @endcode
292/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000293Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000294Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000295 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000296 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000297 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000298 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000299 SourceLocation ConstructorRParen)
300{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000301 Expr *ArraySize = 0;
302 unsigned Skip = 0;
303 // If the specified type is an array, unwrap it and save the expression.
304 if (D.getNumTypeObjects() > 0 &&
305 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
306 DeclaratorChunk &Chunk = D.getTypeObject(0);
307 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000308 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
309 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000310 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000311 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
312 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000313 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
314 Skip = 1;
315 }
316
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000317 //FIXME: Store DeclaratorInfo in CXXNew expression.
318 DeclaratorInfo *DInfo = 0;
319 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000320 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000321 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000322
Douglas Gregor3433cf72009-05-21 00:00:09 +0000323 // Every dimension shall be of constant size.
324 unsigned i = 1;
325 QualType ElementType = AllocType;
326 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
327 if (!Array->isConstantArrayType()) {
328 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
329 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
330 return ExprError();
331 }
332 ElementType = Array->getElementType();
333 ++i;
334 }
335
336 return BuildCXXNew(StartLoc, UseGlobal,
337 PlacementLParen,
338 move(PlacementArgs),
339 PlacementRParen,
340 ParenTypeId,
341 AllocType,
342 D.getSourceRange().getBegin(),
343 D.getSourceRange(),
344 Owned(ArraySize),
345 ConstructorLParen,
346 move(ConstructorArgs),
347 ConstructorRParen);
348}
349
350Sema::OwningExprResult
351Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
352 SourceLocation PlacementLParen,
353 MultiExprArg PlacementArgs,
354 SourceLocation PlacementRParen,
355 bool ParenTypeId,
356 QualType AllocType,
357 SourceLocation TypeLoc,
358 SourceRange TypeRange,
359 ExprArg ArraySizeE,
360 SourceLocation ConstructorLParen,
361 MultiExprArg ConstructorArgs,
362 SourceLocation ConstructorRParen) {
363 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000364 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000365
Douglas Gregor3433cf72009-05-21 00:00:09 +0000366 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000367
368 // That every array dimension except the first is constant was already
369 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000370
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000371 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
372 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000373 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000374 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000375 QualType SizeType = ArraySize->getType();
376 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000377 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
378 diag::err_array_size_not_integral)
379 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000380 // Let's see if this is a constant < 0. If so, we reject it out of hand.
381 // We don't care about special rules, so we tell the machinery it's not
382 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000383 if (!ArraySize->isValueDependent()) {
384 llvm::APSInt Value;
385 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
386 if (Value < llvm::APSInt(
387 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000388 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
389 diag::err_typecheck_negative_array_size)
390 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000391 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000392 }
393 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000394
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395 FunctionDecl *OperatorNew = 0;
396 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000397 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
398 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000399 if (!AllocType->isDependentType() &&
400 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
401 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000402 SourceRange(PlacementLParen, PlacementRParen),
403 UseGlobal, AllocType, ArraySize, PlaceArgs,
404 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000405 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000406
407 bool Init = ConstructorLParen.isValid();
408 // --- Choosing a constructor ---
409 // C++ 5.3.4p15
410 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
411 // the object is not initialized. If the object, or any part of it, is
412 // const-qualified, it's an error.
413 // 2) If T is a POD and there's an empty initializer, the object is value-
414 // initialized.
415 // 3) If T is a POD and there's one initializer argument, the object is copy-
416 // constructed.
417 // 4) If T is a POD and there's more initializer arguments, it's an error.
418 // 5) If T is not a POD, the initializer arguments are used as constructor
419 // arguments.
420 //
421 // Or by the C++0x formulation:
422 // 1) If there's no initializer, the object is default-initialized according
423 // to C++0x rules.
424 // 2) Otherwise, the object is direct-initialized.
425 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000426 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000427 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000428 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000429 if (AllocType->isDependentType()) {
430 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000431 } else if ((RT = AllocType->getAs<RecordType>()) &&
432 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000433 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000434 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000435 TypeLoc,
436 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000437 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000438 NumConsArgs != 0 ? IK_Direct : IK_Default);
439 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000440 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000441 } else {
442 if (!Init) {
443 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000444 if (AllocType.isConstQualified())
445 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000446 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000447 } else if (NumConsArgs == 0) {
448 // Object is value-initialized. Do nothing.
449 } else if (NumConsArgs == 1) {
450 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000451 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000452 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000453 DeclarationName() /*AllocType.getAsString()*/,
454 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000455 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000456 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000457 return ExprError(Diag(StartLoc,
458 diag::err_builtin_direct_init_more_than_one_arg)
459 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 }
461 }
462
463 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
464
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 PlacementArgs.release();
466 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000467 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000469 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000470 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000471 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000472}
473
474/// CheckAllocatedType - Checks that a type is suitable as the allocated type
475/// in a new-expression.
476/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000477bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
478 SourceRange R)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000479{
480 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
481 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000482 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000483 return Diag(Loc, diag::err_bad_new_type)
484 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000485 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000486 return Diag(Loc, diag::err_bad_new_type)
487 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000488 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000489 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000490 PDiag(diag::err_new_incomplete_type)
491 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000492 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000493 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000494 diag::err_allocation_of_abstract_type))
495 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000496
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000497 return false;
498}
499
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000500/// FindAllocationFunctions - Finds the overloads of operator new and delete
501/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000502bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
503 bool UseGlobal, QualType AllocType,
504 bool IsArray, Expr **PlaceArgs,
505 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000506 FunctionDecl *&OperatorNew,
507 FunctionDecl *&OperatorDelete)
508{
509 // --- Choosing an allocation function ---
510 // C++ 5.3.4p8 - 14 & 18
511 // 1) If UseGlobal is true, only look in the global scope. Else, also look
512 // in the scope of the allocated class.
513 // 2) If an array size is given, look for operator new[], else look for
514 // operator new.
515 // 3) The first argument is always size_t. Append the arguments from the
516 // placement form.
517 // FIXME: Also find the appropriate delete operator.
518
519 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
520 // We don't care about the actual value of this argument.
521 // FIXME: Should the Sema create the expression and embed it in the syntax
522 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000523 IntegerLiteral Size(llvm::APInt::getNullValue(
524 Context.Target.getPointerWidth(0)),
525 Context.getSizeType(),
526 SourceLocation());
527 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000528 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
529
530 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
531 IsArray ? OO_Array_New : OO_New);
532 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000533 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000534 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000535 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000536 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000537 AllocArgs.size(), Record, /*AllowMissing=*/true,
538 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000539 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000540 }
541 if (!OperatorNew) {
542 // Didn't find a member overload. Look for a global one.
543 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000544 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000545 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000546 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
547 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000548 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000549 }
550
Anders Carlssond9583892009-05-31 20:26:12 +0000551 // FindAllocationOverload can change the passed in arguments, so we need to
552 // copy them back.
553 if (NumPlaceArgs > 0)
554 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
555
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000556 return false;
557}
558
Sebastian Redl7f662392008-12-04 22:20:51 +0000559/// FindAllocationOverload - Find an fitting overload for the allocation
560/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000561bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
562 DeclarationName Name, Expr** Args,
563 unsigned NumArgs, DeclContext *Ctx,
564 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000565{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000566 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000567 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000568 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000569 if (AllowMissing)
570 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000571 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000572 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000573 }
574
575 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000576 for (; Alloc != AllocEnd; ++Alloc) {
577 // Even member operator new/delete are implicitly treated as
578 // static, so don't use AddMemberCandidate.
579 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
580 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
581 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000582 }
583
584 // Do the resolution.
585 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000586 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000587 case OR_Success: {
588 // Got one!
589 FunctionDecl *FnDecl = Best->Function;
590 // The first argument is size_t, and the first parameter must be size_t,
591 // too. This is checked on declaration and can be assumed. (It can't be
592 // asserted on, though, since invalid decls are left in there.)
593 for (unsigned i = 1; i < NumArgs; ++i) {
594 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000595 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000596 FnDecl->getParamDecl(i)->getType(),
597 "passing"))
598 return true;
599 }
600 Operator = FnDecl;
601 return false;
602 }
603
604 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000605 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000606 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
608 return true;
609
610 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000611 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000612 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000613 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
614 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000615
616 case OR_Deleted:
617 Diag(StartLoc, diag::err_ovl_deleted_call)
618 << Best->Function->isDeleted()
619 << Name << Range;
620 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
621 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 }
623 assert(false && "Unreachable, bad result from BestViableFunction");
624 return true;
625}
626
627
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000628/// DeclareGlobalNewDelete - Declare the global forms of operator new and
629/// delete. These are:
630/// @code
631/// void* operator new(std::size_t) throw(std::bad_alloc);
632/// void* operator new[](std::size_t) throw(std::bad_alloc);
633/// void operator delete(void *) throw();
634/// void operator delete[](void *) throw();
635/// @endcode
636/// Note that the placement and nothrow forms of new are *not* implicitly
637/// declared. Their use requires including \<new\>.
638void Sema::DeclareGlobalNewDelete()
639{
640 if (GlobalNewDeleteDeclared)
641 return;
642 GlobalNewDeleteDeclared = true;
643
644 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
645 QualType SizeT = Context.getSizeType();
646
647 // FIXME: Exception specifications are not added.
648 DeclareGlobalAllocationFunction(
649 Context.DeclarationNames.getCXXOperatorName(OO_New),
650 VoidPtr, SizeT);
651 DeclareGlobalAllocationFunction(
652 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
653 VoidPtr, SizeT);
654 DeclareGlobalAllocationFunction(
655 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
656 Context.VoidTy, VoidPtr);
657 DeclareGlobalAllocationFunction(
658 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
659 Context.VoidTy, VoidPtr);
660}
661
662/// DeclareGlobalAllocationFunction - Declares a single implicit global
663/// allocation function if it doesn't already exist.
664void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
665 QualType Return, QualType Argument)
666{
667 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
668
669 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000670 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000671 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000672 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000673 Alloc != AllocEnd; ++Alloc) {
674 // FIXME: Do we need to check for default arguments here?
675 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
676 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000677 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000678 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000679 }
680 }
681
682 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
683 FunctionDecl *Alloc =
684 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000685 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000686 Alloc->setImplicit();
687 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000688 0, Argument, /*DInfo=*/0,
689 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000690 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000691
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000692 // FIXME: Also add this declaration to the IdentifierResolver, but
693 // make sure it is at the end of the chain to coincide with the
694 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000695 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000696}
697
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000698/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
699/// @code ::delete ptr; @endcode
700/// or
701/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000702Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000703Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000704 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000705{
706 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
707 // having a single conversion function to a pointer type. The result has
708 // type void."
709 // DR599 amends "pointer type" to "pointer to object type" in both cases.
710
Anders Carlssond67c4c32009-08-16 20:29:29 +0000711 FunctionDecl *OperatorDelete = 0;
712
Sebastian Redlf53597f2009-03-15 17:47:39 +0000713 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000714 if (!Ex->isTypeDependent()) {
715 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000716
Sebastian Redl28507842009-02-26 14:39:58 +0000717 if (Type->isRecordType()) {
718 // FIXME: Find that one conversion function and amend the type.
719 }
720
Sebastian Redlf53597f2009-03-15 17:47:39 +0000721 if (!Type->isPointerType())
722 return ExprError(Diag(StartLoc, diag::err_delete_operand)
723 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000724
Ted Kremenek6217b802009-07-29 21:53:49 +0000725 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000726 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000727 return ExprError(Diag(StartLoc, diag::err_delete_operand)
728 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000729 else if (!Pointee->isDependentType() &&
730 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000731 PDiag(diag::warn_delete_incomplete)
732 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000733 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000734
Anders Carlssond67c4c32009-08-16 20:29:29 +0000735 // FIXME: This should be shared with the code for finding the delete
736 // operator in ActOnCXXNew.
737 IntegerLiteral Size(llvm::APInt::getNullValue(
738 Context.Target.getPointerWidth(0)),
739 Context.getSizeType(),
740 SourceLocation());
741 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
742 CastExpr::CK_Unknown, &Size, false);
743 Expr *DeleteArg = &Cast;
744
745 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
746 ArrayForm ? OO_Array_Delete : OO_Delete);
747
748 if (Pointee->isRecordType() && !UseGlobal) {
749 CXXRecordDecl *Record
750 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
751 // FIXME: We fail to find inherited overloads.
752 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
753 &DeleteArg, 1, Record, /*AllowMissing=*/true,
754 OperatorDelete))
755 return ExprError();
756 }
757
758 if (!OperatorDelete) {
759 // Didn't find a member overload. Look for a global one.
760 DeclareGlobalNewDelete();
761 DeclContext *TUDecl = Context.getTranslationUnitDecl();
762 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
763 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
764 OperatorDelete))
765 return ExprError();
766 }
767
Sebastian Redl28507842009-02-26 14:39:58 +0000768 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000769 }
770
Sebastian Redlf53597f2009-03-15 17:47:39 +0000771 Operand.release();
772 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000773 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000774}
775
776
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000777/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
778/// C++ if/switch/while/for statement.
779/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000780Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000781Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
782 Declarator &D,
783 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000784 ExprArg AssignExprVal) {
785 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000786
787 // C++ 6.4p2:
788 // The declarator shall not specify a function or an array.
789 // The type-specifier-seq shall not contain typedef and shall not declare a
790 // new class or enumeration.
791
792 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
793 "Parser allowed 'typedef' as storage class of condition decl.");
794
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000795 // FIXME: Store DeclaratorInfo in the expression.
796 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000797 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000798 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000799
800 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
801 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
802 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000803 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
804 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000805 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000806 Diag(StartLoc, diag::err_invalid_use_of_array_type)
807 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000808 } else if (OwnedTag && OwnedTag->isDefinition()) {
809 // The type-specifier-seq shall not declare a new class or enumeration.
810 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000811 }
812
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000813 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000814 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000815 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000816 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000817
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000818 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000819 // We know that the decl had to be a VarDecl because that is the only type of
820 // decl that can be assigned and the grammar requires an '='.
821 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
822 VD->setDeclaredInCondition(true);
823 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000824}
825
826/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
827bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
828 // C++ 6.4p4:
829 // The value of a condition that is an initialized declaration in a statement
830 // other than a switch statement is the value of the declared variable
831 // implicitly converted to type bool. If that conversion is ill-formed, the
832 // program is ill-formed.
833 // The value of a condition that is an expression is the value of the
834 // expression, implicitly converted to bool.
835 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000836 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000837}
Douglas Gregor77a52232008-09-12 00:47:35 +0000838
839/// Helper function to determine whether this is the (deprecated) C++
840/// conversion from a string literal to a pointer to non-const char or
841/// non-const wchar_t (for narrow and wide string literals,
842/// respectively).
843bool
844Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
845 // Look inside the implicit cast, if it exists.
846 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
847 From = Cast->getSubExpr();
848
849 // A string literal (2.13.4) that is not a wide string literal can
850 // be converted to an rvalue of type "pointer to char"; a wide
851 // string literal can be converted to an rvalue of type "pointer
852 // to wchar_t" (C++ 4.2p2).
853 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000854 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor77a52232008-09-12 00:47:35 +0000855 if (const BuiltinType *ToPointeeType
856 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
857 // This conversion is considered only when there is an
858 // explicit appropriate pointer target type (C++ 4.2p2).
859 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
860 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
861 (!StrLit->isWide() &&
862 (ToPointeeType->getKind() == BuiltinType::Char_U ||
863 ToPointeeType->getKind() == BuiltinType::Char_S))))
864 return true;
865 }
866
867 return false;
868}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000869
870/// PerformImplicitConversion - Perform an implicit conversion of the
871/// expression From to the type ToType. Returns true if there was an
872/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000873/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000874/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000875/// explicit user-defined conversions are permitted. @p Elidable should be true
876/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
877/// resolution works differently in that case.
878bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000879Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000880 const char *Flavor, bool AllowExplicit,
881 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000882{
Sebastian Redle2b68332009-04-12 17:16:29 +0000883 ImplicitConversionSequence ICS;
884 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
885 if (Elidable && getLangOptions().CPlusPlus0x) {
886 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
887 AllowExplicit, /*ForceRValue*/true);
888 }
889 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
890 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
891 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000892 return PerformImplicitConversion(From, ToType, ICS, Flavor);
893}
894
895/// PerformImplicitConversion - Perform an implicit conversion of the
896/// expression From to the type ToType using the pre-computed implicit
897/// conversion sequence ICS. Returns true if there was an error, false
898/// otherwise. The expression From is replaced with the converted
899/// expression. Flavor is the kind of conversion we're performing,
900/// used in the error message.
901bool
902Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
903 const ImplicitConversionSequence &ICS,
904 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000905 switch (ICS.ConversionKind) {
906 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000907 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000908 return true;
909 break;
910
911 case ImplicitConversionSequence::UserDefinedConversion:
Fariborz Jahanian9099ff02009-08-26 20:34:58 +0000912 // FIXME. Support other kinds of user defined convesions.
913 if (CXXConversionDecl *CV =
914 dyn_cast<CXXConversionDecl>(ICS.UserDefined.ConversionFunction))
915 // FIXME. Get actual Source Location.
916 From =
917 new (Context) CXXFunctionalCastExpr(ToType.getNonReferenceType(),
918 ToType, SourceLocation(),
919 CastExpr::CK_UserDefinedConversion,
920 From, CV,
921 SourceLocation());
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000922 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +0000923 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000924 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000925 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000926
927 case ImplicitConversionSequence::EllipsisConversion:
928 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000929 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000930
931 case ImplicitConversionSequence::BadConversion:
932 return true;
933 }
934
935 // Everything went well.
936 return false;
937}
938
939/// PerformImplicitConversion - Perform an implicit conversion of the
940/// expression From to the type ToType by following the standard
941/// conversion sequence SCS. Returns true if there was an error, false
942/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000943/// expression. Flavor is the context in which we're performing this
944/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000945bool
946Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000947 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000948 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000949 // Overall FIXME: we are recomputing too many types here and doing far too
950 // much extra work. What this means is that we need to keep track of more
951 // information that is computed when we try the implicit conversion initially,
952 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000953 QualType FromType = From->getType();
954
Douglas Gregor225c41e2008-11-03 19:09:14 +0000955 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000956 // FIXME: When can ToType be a reference type?
957 assert(!ToType->isReferenceType());
958
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000959 OwningExprResult FromResult =
960 BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
961
962 if (FromResult.isInvalid())
963 return true;
964
965 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000966 return false;
967 }
968
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000969 // Perform the first implicit conversion.
970 switch (SCS.First) {
971 case ICK_Identity:
972 case ICK_Lvalue_To_Rvalue:
973 // Nothing to do.
974 break;
975
976 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000977 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +0000978 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000979 break;
980
981 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000982 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000983 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
984 if (!Fn)
985 return true;
986
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000987 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
988 return true;
989
Douglas Gregor904eed32008-11-10 20:40:00 +0000990 FixOverloadedFunctionReference(From, Fn);
991 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000992 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000993 FromType = Context.getPointerType(FromType);
994 ImpCastExprToType(From, FromType);
995 break;
996
997 default:
998 assert(false && "Improper first standard conversion");
999 break;
1000 }
1001
1002 // Perform the second implicit conversion
1003 switch (SCS.Second) {
1004 case ICK_Identity:
1005 // Nothing to do.
1006 break;
1007
1008 case ICK_Integral_Promotion:
1009 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001010 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001011 case ICK_Integral_Conversion:
1012 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001013 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001014 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001015 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001016 case ICK_Compatible_Conversion:
1017 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001018 FromType = ToType.getUnqualifiedType();
1019 ImpCastExprToType(From, FromType);
1020 break;
1021
1022 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001023 if (SCS.IncompatibleObjC) {
1024 // Diagnose incompatible Objective-C conversions
1025 Diag(From->getSourceRange().getBegin(),
1026 diag::ext_typecheck_convert_incompatible_pointer)
1027 << From->getType() << ToType << Flavor
1028 << From->getSourceRange();
1029 }
1030
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001031 if (CheckPointerConversion(From, ToType))
1032 return true;
1033 ImpCastExprToType(From, ToType);
1034 break;
1035
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001036 case ICK_Pointer_Member: {
1037 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1038 if (CheckMemberPointerConversion(From, ToType, Kind))
1039 return true;
1040 ImpCastExprToType(From, ToType, Kind);
1041 break;
1042 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001043 case ICK_Boolean_Conversion:
1044 FromType = Context.BoolTy;
1045 ImpCastExprToType(From, FromType);
1046 break;
1047
1048 default:
1049 assert(false && "Improper second standard conversion");
1050 break;
1051 }
1052
1053 switch (SCS.Third) {
1054 case ICK_Identity:
1055 // Nothing to do.
1056 break;
1057
1058 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001059 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1060 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +00001061 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001062 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001063 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001064 break;
1065
1066 default:
1067 assert(false && "Improper second standard conversion");
1068 break;
1069 }
1070
1071 return false;
1072}
1073
Sebastian Redl64b45f72009-01-05 20:52:13 +00001074Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1075 SourceLocation KWLoc,
1076 SourceLocation LParen,
1077 TypeTy *Ty,
1078 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001079 QualType T = GetTypeFromParser(Ty);
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001080
1081 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1082 // all traits except __is_class, __is_enum and __is_union require a the type
1083 // to be complete.
1084 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1085 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001086 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001087 return ExprError();
1088 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001089
1090 // There is no point in eagerly computing the value. The traits are designed
1091 // to be used from type trait templates, so Ty will be a template parameter
1092 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001093 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1094 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001095}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001096
1097QualType Sema::CheckPointerToMemberOperands(
1098 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1099{
1100 const char *OpSpelling = isIndirect ? "->*" : ".*";
1101 // C++ 5.5p2
1102 // The binary operator .* [p3: ->*] binds its second operand, which shall
1103 // be of type "pointer to member of T" (where T is a completely-defined
1104 // class type) [...]
1105 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001106 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001107 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001108 Diag(Loc, diag::err_bad_memptr_rhs)
1109 << OpSpelling << RType << rex->getSourceRange();
1110 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001111 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001112
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001113 QualType Class(MemPtr->getClass(), 0);
1114
1115 // C++ 5.5p2
1116 // [...] to its first operand, which shall be of class T or of a class of
1117 // which T is an unambiguous and accessible base class. [p3: a pointer to
1118 // such a class]
1119 QualType LType = lex->getType();
1120 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001121 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001122 LType = Ptr->getPointeeType().getNonReferenceType();
1123 else {
1124 Diag(Loc, diag::err_bad_memptr_lhs)
1125 << OpSpelling << 1 << LType << lex->getSourceRange();
1126 return QualType();
1127 }
1128 }
1129
1130 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1131 Context.getCanonicalType(LType).getUnqualifiedType()) {
1132 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1133 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001134 // FIXME: Would it be useful to print full ambiguity paths, or is that
1135 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001136 if (!IsDerivedFrom(LType, Class, Paths) ||
1137 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1138 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1139 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1140 return QualType();
1141 }
1142 }
1143
1144 // C++ 5.5p2
1145 // The result is an object or a function of the type specified by the
1146 // second operand.
1147 // The cv qualifiers are the union of those in the pointer and the left side,
1148 // in accordance with 5.5p5 and 5.2.5.
1149 // FIXME: This returns a dereferenced member function pointer as a normal
1150 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001151 // calling them. There's also a GCC extension to get a function pointer to the
1152 // thing, which is another complication, because this type - unlike the type
1153 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001154 // argument.
1155 // We probably need a "MemberFunctionClosureType" or something like that.
1156 QualType Result = MemPtr->getPointeeType();
1157 if (LType.isConstQualified())
1158 Result.addConst();
1159 if (LType.isVolatileQualified())
1160 Result.addVolatile();
1161 return Result;
1162}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001163
1164/// \brief Get the target type of a standard or user-defined conversion.
1165static QualType TargetType(const ImplicitConversionSequence &ICS) {
1166 assert((ICS.ConversionKind ==
1167 ImplicitConversionSequence::StandardConversion ||
1168 ICS.ConversionKind ==
1169 ImplicitConversionSequence::UserDefinedConversion) &&
1170 "function only valid for standard or user-defined conversions");
1171 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1172 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1173 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1174}
1175
1176/// \brief Try to convert a type to another according to C++0x 5.16p3.
1177///
1178/// This is part of the parameter validation for the ? operator. If either
1179/// value operand is a class type, the two operands are attempted to be
1180/// converted to each other. This function does the conversion in one direction.
1181/// It emits a diagnostic and returns true only if it finds an ambiguous
1182/// conversion.
1183static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1184 SourceLocation QuestionLoc,
1185 ImplicitConversionSequence &ICS)
1186{
1187 // C++0x 5.16p3
1188 // The process for determining whether an operand expression E1 of type T1
1189 // can be converted to match an operand expression E2 of type T2 is defined
1190 // as follows:
1191 // -- If E2 is an lvalue:
1192 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1193 // E1 can be converted to match E2 if E1 can be implicitly converted to
1194 // type "lvalue reference to T2", subject to the constraint that in the
1195 // conversion the reference must bind directly to E1.
1196 if (!Self.CheckReferenceInit(From,
1197 Self.Context.getLValueReferenceType(To->getType()),
1198 &ICS))
1199 {
1200 assert((ICS.ConversionKind ==
1201 ImplicitConversionSequence::StandardConversion ||
1202 ICS.ConversionKind ==
1203 ImplicitConversionSequence::UserDefinedConversion) &&
1204 "expected a definite conversion");
1205 bool DirectBinding =
1206 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1207 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1208 if (DirectBinding)
1209 return false;
1210 }
1211 }
1212 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1213 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1214 // -- if E1 and E2 have class type, and the underlying class types are
1215 // the same or one is a base class of the other:
1216 QualType FTy = From->getType();
1217 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001218 const RecordType *FRec = FTy->getAs<RecordType>();
1219 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001220 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1221 if (FRec && TRec && (FRec == TRec ||
1222 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1223 // E1 can be converted to match E2 if the class of T2 is the
1224 // same type as, or a base class of, the class of T1, and
1225 // [cv2 > cv1].
1226 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1227 // Could still fail if there's no copy constructor.
1228 // FIXME: Is this a hard error then, or just a conversion failure? The
1229 // standard doesn't say.
1230 ICS = Self.TryCopyInitialization(From, TTy);
1231 }
1232 } else {
1233 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1234 // implicitly converted to the type that expression E2 would have
1235 // if E2 were converted to an rvalue.
1236 // First find the decayed type.
1237 if (TTy->isFunctionType())
1238 TTy = Self.Context.getPointerType(TTy);
1239 else if(TTy->isArrayType())
1240 TTy = Self.Context.getArrayDecayedType(TTy);
1241
1242 // Now try the implicit conversion.
1243 // FIXME: This doesn't detect ambiguities.
1244 ICS = Self.TryImplicitConversion(From, TTy);
1245 }
1246 return false;
1247}
1248
1249/// \brief Try to find a common type for two according to C++0x 5.16p5.
1250///
1251/// This is part of the parameter validation for the ? operator. If either
1252/// value operand is a class type, overload resolution is used to find a
1253/// conversion to a common type.
1254static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1255 SourceLocation Loc) {
1256 Expr *Args[2] = { LHS, RHS };
1257 OverloadCandidateSet CandidateSet;
1258 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1259
1260 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001261 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001262 case Sema::OR_Success:
1263 // We found a match. Perform the conversions on the arguments and move on.
1264 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1265 Best->Conversions[0], "converting") ||
1266 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1267 Best->Conversions[1], "converting"))
1268 break;
1269 return false;
1270
1271 case Sema::OR_No_Viable_Function:
1272 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1273 << LHS->getType() << RHS->getType()
1274 << LHS->getSourceRange() << RHS->getSourceRange();
1275 return true;
1276
1277 case Sema::OR_Ambiguous:
1278 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1279 << LHS->getType() << RHS->getType()
1280 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001281 // FIXME: Print the possible common types by printing the return types of
1282 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001283 break;
1284
1285 case Sema::OR_Deleted:
1286 assert(false && "Conditional operator has only built-in overloads");
1287 break;
1288 }
1289 return true;
1290}
1291
Sebastian Redl76458502009-04-17 16:30:52 +00001292/// \brief Perform an "extended" implicit conversion as returned by
1293/// TryClassUnification.
1294///
1295/// TryClassUnification generates ICSs that include reference bindings.
1296/// PerformImplicitConversion is not suitable for this; it chokes if the
1297/// second part of a standard conversion is ICK_DerivedToBase. This function
1298/// handles the reference binding specially.
1299static bool ConvertForConditional(Sema &Self, Expr *&E,
1300 const ImplicitConversionSequence &ICS)
1301{
1302 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1303 ICS.Standard.ReferenceBinding) {
1304 assert(ICS.Standard.DirectBinding &&
1305 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001306 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1307 // redoing all the work.
1308 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1309 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001310 }
1311 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1312 ICS.UserDefined.After.ReferenceBinding) {
1313 assert(ICS.UserDefined.After.DirectBinding &&
1314 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001315 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1316 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001317 }
1318 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1319 return true;
1320 return false;
1321}
1322
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001323/// \brief Check the operands of ?: under C++ semantics.
1324///
1325/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1326/// extension. In this case, LHS == Cond. (But they're not aliases.)
1327QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1328 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001329 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1330 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001331
1332 // C++0x 5.16p1
1333 // The first expression is contextually converted to bool.
1334 if (!Cond->isTypeDependent()) {
1335 if (CheckCXXBooleanCondition(Cond))
1336 return QualType();
1337 }
1338
1339 // Either of the arguments dependent?
1340 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1341 return Context.DependentTy;
1342
1343 // C++0x 5.16p2
1344 // If either the second or the third operand has type (cv) void, ...
1345 QualType LTy = LHS->getType();
1346 QualType RTy = RHS->getType();
1347 bool LVoid = LTy->isVoidType();
1348 bool RVoid = RTy->isVoidType();
1349 if (LVoid || RVoid) {
1350 // ... then the [l2r] conversions are performed on the second and third
1351 // operands ...
1352 DefaultFunctionArrayConversion(LHS);
1353 DefaultFunctionArrayConversion(RHS);
1354 LTy = LHS->getType();
1355 RTy = RHS->getType();
1356
1357 // ... and one of the following shall hold:
1358 // -- The second or the third operand (but not both) is a throw-
1359 // expression; the result is of the type of the other and is an rvalue.
1360 bool LThrow = isa<CXXThrowExpr>(LHS);
1361 bool RThrow = isa<CXXThrowExpr>(RHS);
1362 if (LThrow && !RThrow)
1363 return RTy;
1364 if (RThrow && !LThrow)
1365 return LTy;
1366
1367 // -- Both the second and third operands have type void; the result is of
1368 // type void and is an rvalue.
1369 if (LVoid && RVoid)
1370 return Context.VoidTy;
1371
1372 // Neither holds, error.
1373 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1374 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1375 << LHS->getSourceRange() << RHS->getSourceRange();
1376 return QualType();
1377 }
1378
1379 // Neither is void.
1380
1381 // C++0x 5.16p3
1382 // Otherwise, if the second and third operand have different types, and
1383 // either has (cv) class type, and attempt is made to convert each of those
1384 // operands to the other.
1385 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1386 (LTy->isRecordType() || RTy->isRecordType())) {
1387 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1388 // These return true if a single direction is already ambiguous.
1389 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1390 return QualType();
1391 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1392 return QualType();
1393
1394 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1395 ImplicitConversionSequence::BadConversion;
1396 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1397 ImplicitConversionSequence::BadConversion;
1398 // If both can be converted, [...] the program is ill-formed.
1399 if (HaveL2R && HaveR2L) {
1400 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1401 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1402 return QualType();
1403 }
1404
1405 // If exactly one conversion is possible, that conversion is applied to
1406 // the chosen operand and the converted operands are used in place of the
1407 // original operands for the remainder of this section.
1408 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001409 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001410 return QualType();
1411 LTy = LHS->getType();
1412 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001413 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001414 return QualType();
1415 RTy = RHS->getType();
1416 }
1417 }
1418
1419 // C++0x 5.16p4
1420 // If the second and third operands are lvalues and have the same type,
1421 // the result is of that type [...]
1422 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1423 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1424 RHS->isLvalue(Context) == Expr::LV_Valid)
1425 return LTy;
1426
1427 // C++0x 5.16p5
1428 // Otherwise, the result is an rvalue. If the second and third operands
1429 // do not have the same type, and either has (cv) class type, ...
1430 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1431 // ... overload resolution is used to determine the conversions (if any)
1432 // to be applied to the operands. If the overload resolution fails, the
1433 // program is ill-formed.
1434 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1435 return QualType();
1436 }
1437
1438 // C++0x 5.16p6
1439 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1440 // conversions are performed on the second and third operands.
1441 DefaultFunctionArrayConversion(LHS);
1442 DefaultFunctionArrayConversion(RHS);
1443 LTy = LHS->getType();
1444 RTy = RHS->getType();
1445
1446 // After those conversions, one of the following shall hold:
1447 // -- The second and third operands have the same type; the result
1448 // is of that type.
1449 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1450 return LTy;
1451
1452 // -- The second and third operands have arithmetic or enumeration type;
1453 // the usual arithmetic conversions are performed to bring them to a
1454 // common type, and the result is of that type.
1455 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1456 UsualArithmeticConversions(LHS, RHS);
1457 return LHS->getType();
1458 }
1459
1460 // -- The second and third operands have pointer type, or one has pointer
1461 // type and the other is a null pointer constant; pointer conversions
1462 // and qualification conversions are performed to bring them to their
1463 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001464 QualType Composite = FindCompositePointerType(LHS, RHS);
1465 if (!Composite.isNull())
1466 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001467
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001468 // Fourth bullet is same for pointers-to-member. However, the possible
1469 // conversions are far more limited: we have null-to-pointer, upcast of
1470 // containing class, and second-level cv-ness.
1471 // cv-ness is not a union, but must match one of the two operands. (Which,
1472 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001473 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1474 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001475 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1476 ImpCastExprToType(RHS, LTy);
1477 return LTy;
1478 }
1479 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1480 ImpCastExprToType(LHS, RTy);
1481 return RTy;
1482 }
1483 if (LMemPtr && RMemPtr) {
1484 QualType LPointee = LMemPtr->getPointeeType();
1485 QualType RPointee = RMemPtr->getPointeeType();
1486 // First, we check that the unqualified pointee type is the same. If it's
1487 // not, there's no conversion that will unify the two pointers.
1488 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1489 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1490 // Second, we take the greater of the two cv qualifications. If neither
1491 // is greater than the other, the conversion is not possible.
1492 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1493 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1494 // Third, we check if either of the container classes is derived from
1495 // the other.
1496 QualType LContainer(LMemPtr->getClass(), 0);
1497 QualType RContainer(RMemPtr->getClass(), 0);
1498 QualType MoreDerived;
1499 if (Context.getCanonicalType(LContainer) ==
1500 Context.getCanonicalType(RContainer))
1501 MoreDerived = LContainer;
1502 else if (IsDerivedFrom(LContainer, RContainer))
1503 MoreDerived = LContainer;
1504 else if (IsDerivedFrom(RContainer, LContainer))
1505 MoreDerived = RContainer;
1506
1507 if (!MoreDerived.isNull()) {
1508 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1509 // We don't use ImpCastExprToType here because this could still fail
1510 // for ambiguous or inaccessible conversions.
1511 QualType Common = Context.getMemberPointerType(
1512 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1513 if (PerformImplicitConversion(LHS, Common, "converting"))
1514 return QualType();
1515 if (PerformImplicitConversion(RHS, Common, "converting"))
1516 return QualType();
1517 return Common;
1518 }
1519 }
1520 }
1521 }
1522
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001523 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1524 << LHS->getType() << RHS->getType()
1525 << LHS->getSourceRange() << RHS->getSourceRange();
1526 return QualType();
1527}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001528
1529/// \brief Find a merged pointer type and convert the two expressions to it.
1530///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001531/// This finds the composite pointer type (or member pointer type) for @p E1
1532/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1533/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001534/// It does not emit diagnostics.
1535QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1536 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1537 QualType T1 = E1->getType(), T2 = E2->getType();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001538
1539 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1540 !T2->isPointerType() && !T2->isMemberPointerType())
1541 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001542
Douglas Gregor20b3e992009-08-24 17:42:35 +00001543 // FIXME: Do we need to work on the canonical types?
1544
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001545 // C++0x 5.9p2
1546 // Pointer conversions and qualification conversions are performed on
1547 // pointer operands to bring them to their composite pointer type. If
1548 // one operand is a null pointer constant, the composite pointer type is
1549 // the type of the other operand.
1550 if (E1->isNullPointerConstant(Context)) {
1551 ImpCastExprToType(E1, T2);
1552 return T2;
1553 }
1554 if (E2->isNullPointerConstant(Context)) {
1555 ImpCastExprToType(E2, T1);
1556 return T1;
1557 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00001558
1559 // Now both have to be pointers or member pointers.
1560 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1561 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001562 return QualType();
1563
1564 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1565 // the other has type "pointer to cv2 T" and the composite pointer type is
1566 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1567 // Otherwise, the composite pointer type is a pointer type similar to the
1568 // type of one of the operands, with a cv-qualification signature that is
1569 // the union of the cv-qualification signatures of the operand types.
1570 // In practice, the first part here is redundant; it's subsumed by the second.
1571 // What we do here is, we build the two possible composite types, and try the
1572 // conversions in both directions. If only one works, or if the two composite
1573 // types are the same, we have succeeded.
1574 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001575 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001576 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001577 do {
1578 const PointerType *Ptr1, *Ptr2;
1579 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1580 (Ptr2 = Composite2->getAs<PointerType>())) {
1581 Composite1 = Ptr1->getPointeeType();
1582 Composite2 = Ptr2->getPointeeType();
1583 QualifierUnion.push_back(
1584 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1585 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1586 continue;
1587 }
1588
1589 const MemberPointerType *MemPtr1, *MemPtr2;
1590 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1591 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1592 Composite1 = MemPtr1->getPointeeType();
1593 Composite2 = MemPtr2->getPointeeType();
1594 QualifierUnion.push_back(
1595 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1596 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1597 MemPtr2->getClass()));
1598 continue;
1599 }
1600
1601 // FIXME: block pointer types?
1602
1603 // Cannot unwrap any more types.
1604 break;
1605 } while (true);
1606
1607 // Rewrap the composites as pointers or member pointers with the union CVRs.
1608 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1609 = MemberOfClass.begin();
1610 for (llvm::SmallVector<unsigned, 4>::iterator
1611 I = QualifierUnion.begin(),
1612 E = QualifierUnion.end();
1613 I != E; (void)++I, ++MOC) {
1614 if (MOC->first && MOC->second) {
1615 // Rebuild member pointer type
1616 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1617 MOC->first);
1618 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1619 MOC->second);
1620 } else {
1621 // Rebuild pointer type
1622 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1623 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1624 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001625 }
1626
1627 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1628 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1629 ImplicitConversionSequence E1ToC2, E2ToC2;
1630 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1631 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1632 if (Context.getCanonicalType(Composite1) !=
1633 Context.getCanonicalType(Composite2)) {
1634 E1ToC2 = TryImplicitConversion(E1, Composite2);
1635 E2ToC2 = TryImplicitConversion(E2, Composite2);
1636 }
1637
1638 bool ToC1Viable = E1ToC1.ConversionKind !=
1639 ImplicitConversionSequence::BadConversion
1640 && E2ToC1.ConversionKind !=
1641 ImplicitConversionSequence::BadConversion;
1642 bool ToC2Viable = E1ToC2.ConversionKind !=
1643 ImplicitConversionSequence::BadConversion
1644 && E2ToC2.ConversionKind !=
1645 ImplicitConversionSequence::BadConversion;
1646 if (ToC1Viable && !ToC2Viable) {
1647 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1648 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1649 return Composite1;
1650 }
1651 if (ToC2Viable && !ToC1Viable) {
1652 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1653 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1654 return Composite2;
1655 }
1656 return QualType();
1657}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001658
Anders Carlssondef11992009-05-30 20:36:53 +00001659Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001660 if (!Context.getLangOptions().CPlusPlus)
1661 return Owned(E);
1662
Ted Kremenek6217b802009-07-29 21:53:49 +00001663 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001664 if (!RT)
1665 return Owned(E);
1666
1667 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1668 if (RD->hasTrivialDestructor())
1669 return Owned(E);
1670
1671 CXXTemporary *Temp = CXXTemporary::Create(Context,
1672 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001673 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001674 if (CXXDestructorDecl *Destructor =
1675 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1676 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001677 // FIXME: Add the temporary to the temporaries vector.
1678 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1679}
1680
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001681Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001682 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001683 assert(SubExpr && "sub expression can't be null!");
1684
1685 if (ExprTemporaries.empty())
1686 return SubExpr;
1687
1688 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1689 &ExprTemporaries[0],
1690 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001691 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001692 ExprTemporaries.clear();
1693
1694 return E;
1695}
1696
Anders Carlssonec773872009-08-25 23:46:41 +00001697Sema::OwningExprResult
Anders Carlsson3aa4ca42009-08-26 17:36:19 +00001698Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
Anders Carlssonec773872009-08-25 23:46:41 +00001699 SourceLocation OpLoc,
1700 tok::TokenKind OpKind,
1701 SourceLocation ClassNameLoc,
1702 IdentifierInfo *ClassName,
1703 const CXXScopeSpec *SS) {
1704 if (SS && SS->isInvalid())
1705 return ExprError();
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001706
1707 Expr *BaseExpr = (Expr *)Base.get();
Anders Carlssonec773872009-08-25 23:46:41 +00001708
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001709 if (BaseExpr->isTypeDependent() ||
1710 (SS && isDependentScopeSpecifier(*SS))) {
1711 // FIXME: Return an unresolved ref expr.
1712 return ExprError();
1713 }
1714
1715 TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, SS);
1716 if (!BaseTy) {
1717 Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1718 << ClassName;
1719 return ExprError();
1720 }
Anders Carlssonec773872009-08-25 23:46:41 +00001721
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001722 QualType BaseType = GetTypeFromParser(BaseTy);
1723 if (!BaseType->isRecordType()) {
1724 Diag(ClassNameLoc, diag::err_type_in_pseudo_dtor_not_a_class_type)
1725 << BaseType;
1726 return ExprError();
1727 }
Anders Carlssonec773872009-08-25 23:46:41 +00001728
Anders Carlsson2cf738f2009-08-26 19:22:42 +00001729 CanQualType CanBaseType = Context.getCanonicalType(BaseType);
1730 DeclarationName DtorName =
1731 Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1732
1733 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1734 DtorName, DeclPtrTy(), SS);
Anders Carlssonec773872009-08-25 23:46:41 +00001735}
1736
Anders Carlsson165a0a02009-05-17 18:41:29 +00001737Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1738 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001739 if (FullExpr)
Anders Carlssonf54741e2009-06-16 03:37:31 +00001740 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1741 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001742
Anders Carlssonec773872009-08-25 23:46:41 +00001743
Anders Carlsson165a0a02009-05-17 18:41:29 +00001744 return Owned(FullExpr);
1745}