blob: a714f327d4dc9f2a67206b100509e17d85c31d80 [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"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000034 //FIXME: Preserve type source info.
35 QualType ConvType = GetTypeFromParser(Ty);
Douglas Gregor50d62d12009-08-05 05:36:45 +000036 CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
Douglas Gregor2def4832008-11-17 20:34:05 +000037 DeclarationName ConvName
38 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000039 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000040 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000041}
Sebastian Redlc42e1182008-11-11 11:37:55 +000042
Douglas Gregor487a75a2008-11-19 19:09:45 +000043/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000044/// name (e.g., @c operator+ ) as an expression. This is very
45/// similar to ActOnIdentifierExpr, except that instead of providing
46/// an identifier the parser provides the kind of overloaded
47/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000048Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000049Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
50 OverloadedOperatorKind Op,
51 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000052 const CXXScopeSpec &SS,
53 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000054 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000055 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000056 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000057}
58
Sebastian Redlc42e1182008-11-11 11:37:55 +000059/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000060Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000061Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
62 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000063 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000064 if (!StdNs)
Sebastian Redlf53597f2009-03-15 17:47:39 +000065 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000066
67 if (isType)
68 // FIXME: Preserve type source info.
69 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
Chris Lattner572af492008-11-20 05:51:55 +000071 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000072 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000073 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000074 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000075 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076
77 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
78
Douglas Gregorac7610d2009-06-22 20:57:11 +000079 if (!isType) {
80 // C++0x [expr.typeid]p3:
81 // When typeid is applied to an expression other than an lvalue of a
82 // polymorphic class type [...] [the] expression is an unevaluated
83 // operand.
84
85 // FIXME: if the type of the expression is a class type, the class
86 // shall be completely defined.
87 bool isUnevaluatedOperand = true;
88 Expr *E = static_cast<Expr *>(TyOrExpr);
89 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
90 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000091 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000092 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
93 if (RecordD->isPolymorphic())
94 isUnevaluatedOperand = false;
95 }
96 }
97
98 // If this is an unevaluated operand, clear out the set of declaration
99 // references we have been computing.
100 if (isUnevaluatedOperand)
101 PotentiallyReferencedDeclStack.back().clear();
102 }
103
Sebastian Redlf53597f2009-03-15 17:47:39 +0000104 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
105 TypeInfoType.withConst(),
106 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000107}
108
Steve Naroff1b273c42007-09-16 14:56:35 +0000109/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000110Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000111Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000112 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000114 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
115 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000116}
Chris Lattner50dd2892008-02-26 00:51:44 +0000117
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000118/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
119Action::OwningExprResult
120Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
121 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
122}
123
Chris Lattner50dd2892008-02-26 00:51:44 +0000124/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000125Action::OwningExprResult
126Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000127 Expr *Ex = E.takeAs<Expr>();
128 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
129 return ExprError();
130 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
131}
132
133/// CheckCXXThrowOperand - Validate the operand of a throw.
134bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
135 // C++ [except.throw]p3:
136 // [...] adjusting the type from "array of T" or "function returning T"
137 // to "pointer to T" or "pointer to function returning T", [...]
138 DefaultFunctionArrayConversion(E);
139
140 // If the type of the exception would be an incomplete type or a pointer
141 // to an incomplete type other than (cv) void the program is ill-formed.
142 QualType Ty = E->getType();
143 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000144 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000145 Ty = Ptr->getPointeeType();
146 isPointer = 1;
147 }
148 if (!isPointer || !Ty->isVoidType()) {
149 if (RequireCompleteType(ThrowLoc, Ty,
150 isPointer ? diag::err_throw_incomplete_ptr
151 : diag::err_throw_incomplete,
152 E->getSourceRange(), SourceRange(), QualType()))
153 return true;
154 }
155
156 // FIXME: Construct a temporary here.
157 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000158}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000159
Sebastian Redlf53597f2009-03-15 17:47:39 +0000160Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000161 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
162 /// is a non-lvalue expression whose value is the address of the object for
163 /// which the function is called.
164
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 if (!isa<FunctionDecl>(CurContext))
166 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000167
168 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
169 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000170 return Owned(new (Context) CXXThisExpr(ThisLoc,
171 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000172
Sebastian Redlf53597f2009-03-15 17:47:39 +0000173 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000174}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000175
176/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
177/// Can be interpreted either as function-style casting ("int(x)")
178/// or class type construction ("ClassType(x,y,z)")
179/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000180Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000181Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
182 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000183 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000184 SourceLocation *CommaLocs,
185 SourceLocation RParenLoc) {
186 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000187 // FIXME: Preserve type source info.
188 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000189 unsigned NumExprs = exprs.size();
190 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000191 SourceLocation TyBeginLoc = TypeRange.getBegin();
192 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
193
Sebastian Redlf53597f2009-03-15 17:47:39 +0000194 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000195 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000196 exprs.release();
Anders Carlsson26de5492009-04-24 05:23:13 +0000197
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000198 return Owned(CXXUnresolvedConstructExpr::Create(Context,
199 TypeRange.getBegin(), Ty,
200 LParenLoc,
201 Exprs, NumExprs,
202 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000203 }
204
205
Douglas Gregor506ae412009-01-16 18:33:17 +0000206 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000207 // If the expression list is a single expression, the type conversion
208 // expression is equivalent (in definedness, and if defined in meaning) to the
209 // corresponding cast expression.
210 //
211 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000212 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
213 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*functional-style*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000214 return ExprError();
215 exprs.release();
216 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000217 Ty, TyBeginLoc, Kind,
Anders Carlssoncdef2b72009-07-31 00:48:10 +0000218 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000219 }
220
Ted Kremenek6217b802009-07-29 21:53:49 +0000221 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000222 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000223
Anders Carlsson165a0a02009-05-17 18:41:29 +0000224 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
225 // both the ctor and dtor are trivial.
Douglas Gregor506ae412009-01-16 18:33:17 +0000226 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
227 CXXConstructorDecl *Constructor
228 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
229 TypeRange.getBegin(),
230 SourceRange(TypeRange.getBegin(),
231 RParenLoc),
232 DeclarationName(),
233 IK_Direct);
Douglas Gregor506ae412009-01-16 18:33:17 +0000234
Sebastian Redlf53597f2009-03-15 17:47:39 +0000235 if (!Constructor)
236 return ExprError();
237
238 exprs.release();
Anders Carlsson8e587a12009-05-30 20:56:46 +0000239 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
Anders Carlssondef11992009-05-30 20:36:53 +0000240 Ty, TyBeginLoc, Exprs,
241 NumExprs, RParenLoc);
242 return MaybeBindToTemporary(E);
Douglas Gregor506ae412009-01-16 18:33:17 +0000243 }
244
245 // Fall through to value-initialize an object of class type that
246 // doesn't have a user-declared default constructor.
247 }
248
249 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000250 // If the expression list specifies more than a single value, the type shall
251 // be a class with a suitably declared constructor.
252 //
253 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000254 return ExprError(Diag(CommaLocs[0],
255 diag::err_builtin_func_cast_more_than_one_arg)
256 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000257
258 assert(NumExprs == 0 && "Expected 0 expressions");
259
Douglas Gregor506ae412009-01-16 18:33:17 +0000260 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000261 // The expression T(), where T is a simple-type-specifier for a non-array
262 // complete object type or the (possibly cv-qualified) void type, creates an
263 // rvalue of the specified type, which is value-initialized.
264 //
265 if (Ty->isArrayType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000266 return ExprError(Diag(TyBeginLoc,
267 diag::err_value_init_for_array_type) << FullRange);
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000268 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Sebastian Redlf53597f2009-03-15 17:47:39 +0000269 RequireCompleteType(TyBeginLoc, Ty,
270 diag::err_invalid_incomplete_type_use, FullRange))
271 return ExprError();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000272
Anders Carlsson8211eff2009-03-24 01:19:16 +0000273 if (RequireNonAbstractType(TyBeginLoc, Ty,
274 diag::err_allocation_of_abstract_type))
Anders Carlsson11f21a02009-03-23 19:10:31 +0000275 return ExprError();
276
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 exprs.release();
278 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000279}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000280
281
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000282/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
283/// @code new (memory) int[size][4] @endcode
284/// or
285/// @code ::new Foo(23, "hello") @endcode
286/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000287Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000288Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000289 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000290 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000291 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000292 MultiExprArg ConstructorArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000293 SourceLocation ConstructorRParen)
294{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000295 Expr *ArraySize = 0;
296 unsigned Skip = 0;
297 // If the specified type is an array, unwrap it and save the expression.
298 if (D.getNumTypeObjects() > 0 &&
299 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
300 DeclaratorChunk &Chunk = D.getTypeObject(0);
301 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000302 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
303 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000305 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
306 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000307 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
308 Skip = 1;
309 }
310
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000311 //FIXME: Store DeclaratorInfo in CXXNew expression.
312 DeclaratorInfo *DInfo = 0;
313 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000314 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000315 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000316
Douglas Gregor3433cf72009-05-21 00:00:09 +0000317 // Every dimension shall be of constant size.
318 unsigned i = 1;
319 QualType ElementType = AllocType;
320 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
321 if (!Array->isConstantArrayType()) {
322 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
323 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
324 return ExprError();
325 }
326 ElementType = Array->getElementType();
327 ++i;
328 }
329
330 return BuildCXXNew(StartLoc, UseGlobal,
331 PlacementLParen,
332 move(PlacementArgs),
333 PlacementRParen,
334 ParenTypeId,
335 AllocType,
336 D.getSourceRange().getBegin(),
337 D.getSourceRange(),
338 Owned(ArraySize),
339 ConstructorLParen,
340 move(ConstructorArgs),
341 ConstructorRParen);
342}
343
344Sema::OwningExprResult
345Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
346 SourceLocation PlacementLParen,
347 MultiExprArg PlacementArgs,
348 SourceLocation PlacementRParen,
349 bool ParenTypeId,
350 QualType AllocType,
351 SourceLocation TypeLoc,
352 SourceRange TypeRange,
353 ExprArg ArraySizeE,
354 SourceLocation ConstructorLParen,
355 MultiExprArg ConstructorArgs,
356 SourceLocation ConstructorRParen) {
357 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000359
Douglas Gregor3433cf72009-05-21 00:00:09 +0000360 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000361
362 // That every array dimension except the first is constant was already
363 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000364
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
366 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000367 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000368 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000369 QualType SizeType = ArraySize->getType();
370 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
372 diag::err_array_size_not_integral)
373 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000374 // Let's see if this is a constant < 0. If so, we reject it out of hand.
375 // We don't care about special rules, so we tell the machinery it's not
376 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000377 if (!ArraySize->isValueDependent()) {
378 llvm::APSInt Value;
379 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
380 if (Value < llvm::APSInt(
381 llvm::APInt::getNullValue(Value.getBitWidth()), false))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000382 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
383 diag::err_typecheck_negative_array_size)
384 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000385 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000386 }
387 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000388
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000389 FunctionDecl *OperatorNew = 0;
390 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
392 unsigned NumPlaceArgs = PlacementArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000393 if (!AllocType->isDependentType() &&
394 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
395 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000396 SourceRange(PlacementLParen, PlacementRParen),
397 UseGlobal, AllocType, ArraySize, PlaceArgs,
398 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000399 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000400
401 bool Init = ConstructorLParen.isValid();
402 // --- Choosing a constructor ---
403 // C++ 5.3.4p15
404 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
405 // the object is not initialized. If the object, or any part of it, is
406 // const-qualified, it's an error.
407 // 2) If T is a POD and there's an empty initializer, the object is value-
408 // initialized.
409 // 3) If T is a POD and there's one initializer argument, the object is copy-
410 // constructed.
411 // 4) If T is a POD and there's more initializer arguments, it's an error.
412 // 5) If T is not a POD, the initializer arguments are used as constructor
413 // arguments.
414 //
415 // Or by the C++0x formulation:
416 // 1) If there's no initializer, the object is default-initialized according
417 // to C++0x rules.
418 // 2) Otherwise, the object is direct-initialized.
419 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000420 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000421 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000422 unsigned NumConsArgs = ConstructorArgs.size();
Sebastian Redl28507842009-02-26 14:39:58 +0000423 if (AllocType->isDependentType()) {
424 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000425 } else if ((RT = AllocType->getAs<RecordType>()) &&
426 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000427 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000428 AllocType, ConsArgs, NumConsArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000429 TypeLoc,
430 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000431 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000432 NumConsArgs != 0 ? IK_Direct : IK_Default);
433 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000434 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000435 } else {
436 if (!Init) {
437 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000438 if (AllocType.isConstQualified())
439 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000440 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000441 } else if (NumConsArgs == 0) {
442 // Object is value-initialized. Do nothing.
443 } else if (NumConsArgs == 1) {
444 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000445 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000446 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000447 DeclarationName() /*AllocType.getAsString()*/,
448 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000449 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000450 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000451 return ExprError(Diag(StartLoc,
452 diag::err_builtin_direct_init_more_than_one_arg)
453 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000454 }
455 }
456
457 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
458
Sebastian Redlf53597f2009-03-15 17:47:39 +0000459 PlacementArgs.release();
460 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000461 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000462 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000463 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000464 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000465 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000466}
467
468/// CheckAllocatedType - Checks that a type is suitable as the allocated type
469/// in a new-expression.
470/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000471bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
472 SourceRange R)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000473{
474 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
475 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000476 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000477 return Diag(Loc, diag::err_bad_new_type)
478 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000479 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000480 return Diag(Loc, diag::err_bad_new_type)
481 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000482 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000483 RequireCompleteType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000484 diag::err_new_incomplete_type,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000485 R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000486 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000487 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000488 diag::err_allocation_of_abstract_type))
489 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000490
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000491 return false;
492}
493
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000494/// FindAllocationFunctions - Finds the overloads of operator new and delete
495/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000496bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
497 bool UseGlobal, QualType AllocType,
498 bool IsArray, Expr **PlaceArgs,
499 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000500 FunctionDecl *&OperatorNew,
501 FunctionDecl *&OperatorDelete)
502{
503 // --- Choosing an allocation function ---
504 // C++ 5.3.4p8 - 14 & 18
505 // 1) If UseGlobal is true, only look in the global scope. Else, also look
506 // in the scope of the allocated class.
507 // 2) If an array size is given, look for operator new[], else look for
508 // operator new.
509 // 3) The first argument is always size_t. Append the arguments from the
510 // placement form.
511 // FIXME: Also find the appropriate delete operator.
512
513 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
514 // We don't care about the actual value of this argument.
515 // FIXME: Should the Sema create the expression and embed it in the syntax
516 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000517 IntegerLiteral Size(llvm::APInt::getNullValue(
518 Context.Target.getPointerWidth(0)),
519 Context.getSizeType(),
520 SourceLocation());
521 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000522 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
523
524 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
525 IsArray ? OO_Array_New : OO_New);
526 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000527 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000528 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000529 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000530 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000531 AllocArgs.size(), Record, /*AllowMissing=*/true,
532 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000533 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000534 }
535 if (!OperatorNew) {
536 // Didn't find a member overload. Look for a global one.
537 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000538 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000539 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000540 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
541 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000542 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000543 }
544
Anders Carlssond9583892009-05-31 20:26:12 +0000545 // FindAllocationOverload can change the passed in arguments, so we need to
546 // copy them back.
547 if (NumPlaceArgs > 0)
548 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
549
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000550 return false;
551}
552
Sebastian Redl7f662392008-12-04 22:20:51 +0000553/// FindAllocationOverload - Find an fitting overload for the allocation
554/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000555bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
556 DeclarationName Name, Expr** Args,
557 unsigned NumArgs, DeclContext *Ctx,
558 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000559{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000560 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000561 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000562 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000563 if (AllowMissing)
564 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000565 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000566 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000567 }
568
569 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000570 for (; Alloc != AllocEnd; ++Alloc) {
571 // Even member operator new/delete are implicitly treated as
572 // static, so don't use AddMemberCandidate.
573 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
574 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
575 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000576 }
577
578 // Do the resolution.
579 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000580 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000581 case OR_Success: {
582 // Got one!
583 FunctionDecl *FnDecl = Best->Function;
584 // The first argument is size_t, and the first parameter must be size_t,
585 // too. This is checked on declaration and can be assumed. (It can't be
586 // asserted on, though, since invalid decls are left in there.)
587 for (unsigned i = 1; i < NumArgs; ++i) {
588 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000589 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000590 FnDecl->getParamDecl(i)->getType(),
591 "passing"))
592 return true;
593 }
594 Operator = FnDecl;
595 return false;
596 }
597
598 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000600 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000601 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
602 return true;
603
604 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000605 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000606 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
608 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000609
610 case OR_Deleted:
611 Diag(StartLoc, diag::err_ovl_deleted_call)
612 << Best->Function->isDeleted()
613 << Name << Range;
614 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
615 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000616 }
617 assert(false && "Unreachable, bad result from BestViableFunction");
618 return true;
619}
620
621
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000622/// DeclareGlobalNewDelete - Declare the global forms of operator new and
623/// delete. These are:
624/// @code
625/// void* operator new(std::size_t) throw(std::bad_alloc);
626/// void* operator new[](std::size_t) throw(std::bad_alloc);
627/// void operator delete(void *) throw();
628/// void operator delete[](void *) throw();
629/// @endcode
630/// Note that the placement and nothrow forms of new are *not* implicitly
631/// declared. Their use requires including \<new\>.
632void Sema::DeclareGlobalNewDelete()
633{
634 if (GlobalNewDeleteDeclared)
635 return;
636 GlobalNewDeleteDeclared = true;
637
638 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
639 QualType SizeT = Context.getSizeType();
640
641 // FIXME: Exception specifications are not added.
642 DeclareGlobalAllocationFunction(
643 Context.DeclarationNames.getCXXOperatorName(OO_New),
644 VoidPtr, SizeT);
645 DeclareGlobalAllocationFunction(
646 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
647 VoidPtr, SizeT);
648 DeclareGlobalAllocationFunction(
649 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
650 Context.VoidTy, VoidPtr);
651 DeclareGlobalAllocationFunction(
652 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
653 Context.VoidTy, VoidPtr);
654}
655
656/// DeclareGlobalAllocationFunction - Declares a single implicit global
657/// allocation function if it doesn't already exist.
658void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
659 QualType Return, QualType Argument)
660{
661 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
662
663 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000664 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000665 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000666 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000667 Alloc != AllocEnd; ++Alloc) {
668 // FIXME: Do we need to check for default arguments here?
669 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
670 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000671 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000672 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000673 }
674 }
675
676 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
677 FunctionDecl *Alloc =
678 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000679 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000680 Alloc->setImplicit();
681 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000682 0, Argument, /*DInfo=*/0,
683 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000684 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000685
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000686 // FIXME: Also add this declaration to the IdentifierResolver, but
687 // make sure it is at the end of the chain to coincide with the
688 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000689 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000690}
691
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000692/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
693/// @code ::delete ptr; @endcode
694/// or
695/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000696Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000697Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000698 bool ArrayForm, ExprArg Operand)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000699{
700 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
701 // having a single conversion function to a pointer type. The result has
702 // type void."
703 // DR599 amends "pointer type" to "pointer to object type" in both cases.
704
Anders Carlssond67c4c32009-08-16 20:29:29 +0000705 FunctionDecl *OperatorDelete = 0;
706
Sebastian Redlf53597f2009-03-15 17:47:39 +0000707 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000708 if (!Ex->isTypeDependent()) {
709 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000710
Sebastian Redl28507842009-02-26 14:39:58 +0000711 if (Type->isRecordType()) {
712 // FIXME: Find that one conversion function and amend the type.
713 }
714
Sebastian Redlf53597f2009-03-15 17:47:39 +0000715 if (!Type->isPointerType())
716 return ExprError(Diag(StartLoc, diag::err_delete_operand)
717 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000718
Ted Kremenek6217b802009-07-29 21:53:49 +0000719 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000720 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000721 return ExprError(Diag(StartLoc, diag::err_delete_operand)
722 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000723 else if (!Pointee->isDependentType() &&
724 RequireCompleteType(StartLoc, Pointee,
725 diag::warn_delete_incomplete,
726 Ex->getSourceRange()))
727 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000728
Anders Carlssond67c4c32009-08-16 20:29:29 +0000729 // FIXME: This should be shared with the code for finding the delete
730 // operator in ActOnCXXNew.
731 IntegerLiteral Size(llvm::APInt::getNullValue(
732 Context.Target.getPointerWidth(0)),
733 Context.getSizeType(),
734 SourceLocation());
735 ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
736 CastExpr::CK_Unknown, &Size, false);
737 Expr *DeleteArg = &Cast;
738
739 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
740 ArrayForm ? OO_Array_Delete : OO_Delete);
741
742 if (Pointee->isRecordType() && !UseGlobal) {
743 CXXRecordDecl *Record
744 = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
745 // FIXME: We fail to find inherited overloads.
746 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
747 &DeleteArg, 1, Record, /*AllowMissing=*/true,
748 OperatorDelete))
749 return ExprError();
750 }
751
752 if (!OperatorDelete) {
753 // Didn't find a member overload. Look for a global one.
754 DeclareGlobalNewDelete();
755 DeclContext *TUDecl = Context.getTranslationUnitDecl();
756 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
757 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
758 OperatorDelete))
759 return ExprError();
760 }
761
Sebastian Redl28507842009-02-26 14:39:58 +0000762 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000763 }
764
Sebastian Redlf53597f2009-03-15 17:47:39 +0000765 Operand.release();
766 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000767 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000768}
769
770
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000771/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
772/// C++ if/switch/while/for statement.
773/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000774Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000775Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
776 Declarator &D,
777 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000778 ExprArg AssignExprVal) {
779 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000780
781 // C++ 6.4p2:
782 // The declarator shall not specify a function or an array.
783 // The type-specifier-seq shall not contain typedef and shall not declare a
784 // new class or enumeration.
785
786 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
787 "Parser allowed 'typedef' as storage class of condition decl.");
788
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000789 // FIXME: Store DeclaratorInfo in the expression.
790 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000791 TagDecl *OwnedTag = 0;
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000792 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000793
794 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
795 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
796 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000797 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
798 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000799 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000800 Diag(StartLoc, diag::err_invalid_use_of_array_type)
801 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000802 } else if (OwnedTag && OwnedTag->isDefinition()) {
803 // The type-specifier-seq shall not declare a new class or enumeration.
804 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000805 }
806
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000807 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000808 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000809 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000810 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000811
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000812 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000813 // We know that the decl had to be a VarDecl because that is the only type of
814 // decl that can be assigned and the grammar requires an '='.
815 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
816 VD->setDeclaredInCondition(true);
817 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000818}
819
820/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
821bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
822 // C++ 6.4p4:
823 // The value of a condition that is an initialized declaration in a statement
824 // other than a switch statement is the value of the declared variable
825 // implicitly converted to type bool. If that conversion is ill-formed, the
826 // program is ill-formed.
827 // The value of a condition that is an expression is the value of the
828 // expression, implicitly converted to bool.
829 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000830 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000831}
Douglas Gregor77a52232008-09-12 00:47:35 +0000832
833/// Helper function to determine whether this is the (deprecated) C++
834/// conversion from a string literal to a pointer to non-const char or
835/// non-const wchar_t (for narrow and wide string literals,
836/// respectively).
837bool
838Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
839 // Look inside the implicit cast, if it exists.
840 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
841 From = Cast->getSubExpr();
842
843 // A string literal (2.13.4) that is not a wide string literal can
844 // be converted to an rvalue of type "pointer to char"; a wide
845 // string literal can be converted to an rvalue of type "pointer
846 // to wchar_t" (C++ 4.2p2).
847 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000848 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor77a52232008-09-12 00:47:35 +0000849 if (const BuiltinType *ToPointeeType
850 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
851 // This conversion is considered only when there is an
852 // explicit appropriate pointer target type (C++ 4.2p2).
853 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
854 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
855 (!StrLit->isWide() &&
856 (ToPointeeType->getKind() == BuiltinType::Char_U ||
857 ToPointeeType->getKind() == BuiltinType::Char_S))))
858 return true;
859 }
860
861 return false;
862}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000863
864/// PerformImplicitConversion - Perform an implicit conversion of the
865/// expression From to the type ToType. Returns true if there was an
866/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000867/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000868/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +0000869/// explicit user-defined conversions are permitted. @p Elidable should be true
870/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
871/// resolution works differently in that case.
872bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000873Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +0000874 const char *Flavor, bool AllowExplicit,
875 bool Elidable)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000876{
Sebastian Redle2b68332009-04-12 17:16:29 +0000877 ImplicitConversionSequence ICS;
878 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
879 if (Elidable && getLangOptions().CPlusPlus0x) {
880 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
881 AllowExplicit, /*ForceRValue*/true);
882 }
883 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
884 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
885 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000886 return PerformImplicitConversion(From, ToType, ICS, Flavor);
887}
888
889/// PerformImplicitConversion - Perform an implicit conversion of the
890/// expression From to the type ToType using the pre-computed implicit
891/// conversion sequence ICS. Returns true if there was an error, false
892/// otherwise. The expression From is replaced with the converted
893/// expression. Flavor is the kind of conversion we're performing,
894/// used in the error message.
895bool
896Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
897 const ImplicitConversionSequence &ICS,
898 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000899 switch (ICS.ConversionKind) {
900 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000901 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000902 return true;
903 break;
904
905 case ImplicitConversionSequence::UserDefinedConversion:
Mike Stump390b4cc2009-05-16 07:39:55 +0000906 // FIXME: This is, of course, wrong. We'll need to actually call the
907 // constructor or conversion operator, and then cope with the standard
908 // conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000909 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +0000910 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000911 ToType->isLValueReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000912 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000913
914 case ImplicitConversionSequence::EllipsisConversion:
915 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000916 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000917
918 case ImplicitConversionSequence::BadConversion:
919 return true;
920 }
921
922 // Everything went well.
923 return false;
924}
925
926/// PerformImplicitConversion - Perform an implicit conversion of the
927/// expression From to the type ToType by following the standard
928/// conversion sequence SCS. Returns true if there was an error, false
929/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000930/// expression. Flavor is the context in which we're performing this
931/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000932bool
933Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000934 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000935 const char *Flavor) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000936 // Overall FIXME: we are recomputing too many types here and doing far too
937 // much extra work. What this means is that we need to keep track of more
938 // information that is computed when we try the implicit conversion initially,
939 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000940 QualType FromType = From->getType();
941
Douglas Gregor225c41e2008-11-03 19:09:14 +0000942 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +0000943 // FIXME: When can ToType be a reference type?
944 assert(!ToType->isReferenceType());
945
Anders Carlssonda3f4e22009-08-25 05:12:04 +0000946 OwningExprResult FromResult =
947 BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
948
949 if (FromResult.isInvalid())
950 return true;
951
952 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000953 return false;
954 }
955
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000956 // Perform the first implicit conversion.
957 switch (SCS.First) {
958 case ICK_Identity:
959 case ICK_Lvalue_To_Rvalue:
960 // Nothing to do.
961 break;
962
963 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000964 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +0000965 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000966 break;
967
968 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000969 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000970 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
971 if (!Fn)
972 return true;
973
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000974 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
975 return true;
976
Douglas Gregor904eed32008-11-10 20:40:00 +0000977 FixOverloadedFunctionReference(From, Fn);
978 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000979 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000980 FromType = Context.getPointerType(FromType);
981 ImpCastExprToType(From, FromType);
982 break;
983
984 default:
985 assert(false && "Improper first standard conversion");
986 break;
987 }
988
989 // Perform the second implicit conversion
990 switch (SCS.Second) {
991 case ICK_Identity:
992 // Nothing to do.
993 break;
994
995 case ICK_Integral_Promotion:
996 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000997 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000998 case ICK_Integral_Conversion:
999 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001000 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001001 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001002 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +00001003 case ICK_Compatible_Conversion:
1004 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001005 FromType = ToType.getUnqualifiedType();
1006 ImpCastExprToType(From, FromType);
1007 break;
1008
1009 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +00001010 if (SCS.IncompatibleObjC) {
1011 // Diagnose incompatible Objective-C conversions
1012 Diag(From->getSourceRange().getBegin(),
1013 diag::ext_typecheck_convert_incompatible_pointer)
1014 << From->getType() << ToType << Flavor
1015 << From->getSourceRange();
1016 }
1017
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001018 if (CheckPointerConversion(From, ToType))
1019 return true;
1020 ImpCastExprToType(From, ToType);
1021 break;
1022
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001023 case ICK_Pointer_Member: {
1024 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1025 if (CheckMemberPointerConversion(From, ToType, Kind))
1026 return true;
1027 ImpCastExprToType(From, ToType, Kind);
1028 break;
1029 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001030 case ICK_Boolean_Conversion:
1031 FromType = Context.BoolTy;
1032 ImpCastExprToType(From, FromType);
1033 break;
1034
1035 default:
1036 assert(false && "Improper second standard conversion");
1037 break;
1038 }
1039
1040 switch (SCS.Third) {
1041 case ICK_Identity:
1042 // Nothing to do.
1043 break;
1044
1045 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001046 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1047 // references.
Douglas Gregor66b947f2009-01-16 19:38:23 +00001048 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00001049 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001050 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001051 break;
1052
1053 default:
1054 assert(false && "Improper second standard conversion");
1055 break;
1056 }
1057
1058 return false;
1059}
1060
Sebastian Redl64b45f72009-01-05 20:52:13 +00001061Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1062 SourceLocation KWLoc,
1063 SourceLocation LParen,
1064 TypeTy *Ty,
1065 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001066 QualType T = GetTypeFromParser(Ty);
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001067
1068 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1069 // all traits except __is_class, __is_enum and __is_union require a the type
1070 // to be complete.
1071 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1072 if (RequireCompleteType(KWLoc, T,
1073 diag::err_incomplete_type_used_in_type_trait_expr,
1074 SourceRange(), SourceRange(), T))
1075 return ExprError();
1076 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001077
1078 // There is no point in eagerly computing the value. The traits are designed
1079 // to be used from type trait templates, so Ty will be a template parameter
1080 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001081 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1082 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001083}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001084
1085QualType Sema::CheckPointerToMemberOperands(
1086 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1087{
1088 const char *OpSpelling = isIndirect ? "->*" : ".*";
1089 // C++ 5.5p2
1090 // The binary operator .* [p3: ->*] binds its second operand, which shall
1091 // be of type "pointer to member of T" (where T is a completely-defined
1092 // class type) [...]
1093 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001094 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001095 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001096 Diag(Loc, diag::err_bad_memptr_rhs)
1097 << OpSpelling << RType << rex->getSourceRange();
1098 return QualType();
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00001099 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001100
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001101 QualType Class(MemPtr->getClass(), 0);
1102
1103 // C++ 5.5p2
1104 // [...] to its first operand, which shall be of class T or of a class of
1105 // which T is an unambiguous and accessible base class. [p3: a pointer to
1106 // such a class]
1107 QualType LType = lex->getType();
1108 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001109 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001110 LType = Ptr->getPointeeType().getNonReferenceType();
1111 else {
1112 Diag(Loc, diag::err_bad_memptr_lhs)
1113 << OpSpelling << 1 << LType << lex->getSourceRange();
1114 return QualType();
1115 }
1116 }
1117
1118 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1119 Context.getCanonicalType(LType).getUnqualifiedType()) {
1120 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1121 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001122 // FIXME: Would it be useful to print full ambiguity paths, or is that
1123 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001124 if (!IsDerivedFrom(LType, Class, Paths) ||
1125 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1126 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1127 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1128 return QualType();
1129 }
1130 }
1131
1132 // C++ 5.5p2
1133 // The result is an object or a function of the type specified by the
1134 // second operand.
1135 // The cv qualifiers are the union of those in the pointer and the left side,
1136 // in accordance with 5.5p5 and 5.2.5.
1137 // FIXME: This returns a dereferenced member function pointer as a normal
1138 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001139 // calling them. There's also a GCC extension to get a function pointer to the
1140 // thing, which is another complication, because this type - unlike the type
1141 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001142 // argument.
1143 // We probably need a "MemberFunctionClosureType" or something like that.
1144 QualType Result = MemPtr->getPointeeType();
1145 if (LType.isConstQualified())
1146 Result.addConst();
1147 if (LType.isVolatileQualified())
1148 Result.addVolatile();
1149 return Result;
1150}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001151
1152/// \brief Get the target type of a standard or user-defined conversion.
1153static QualType TargetType(const ImplicitConversionSequence &ICS) {
1154 assert((ICS.ConversionKind ==
1155 ImplicitConversionSequence::StandardConversion ||
1156 ICS.ConversionKind ==
1157 ImplicitConversionSequence::UserDefinedConversion) &&
1158 "function only valid for standard or user-defined conversions");
1159 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1160 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1161 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1162}
1163
1164/// \brief Try to convert a type to another according to C++0x 5.16p3.
1165///
1166/// This is part of the parameter validation for the ? operator. If either
1167/// value operand is a class type, the two operands are attempted to be
1168/// converted to each other. This function does the conversion in one direction.
1169/// It emits a diagnostic and returns true only if it finds an ambiguous
1170/// conversion.
1171static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1172 SourceLocation QuestionLoc,
1173 ImplicitConversionSequence &ICS)
1174{
1175 // C++0x 5.16p3
1176 // The process for determining whether an operand expression E1 of type T1
1177 // can be converted to match an operand expression E2 of type T2 is defined
1178 // as follows:
1179 // -- If E2 is an lvalue:
1180 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1181 // E1 can be converted to match E2 if E1 can be implicitly converted to
1182 // type "lvalue reference to T2", subject to the constraint that in the
1183 // conversion the reference must bind directly to E1.
1184 if (!Self.CheckReferenceInit(From,
1185 Self.Context.getLValueReferenceType(To->getType()),
1186 &ICS))
1187 {
1188 assert((ICS.ConversionKind ==
1189 ImplicitConversionSequence::StandardConversion ||
1190 ICS.ConversionKind ==
1191 ImplicitConversionSequence::UserDefinedConversion) &&
1192 "expected a definite conversion");
1193 bool DirectBinding =
1194 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1195 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1196 if (DirectBinding)
1197 return false;
1198 }
1199 }
1200 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1201 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1202 // -- if E1 and E2 have class type, and the underlying class types are
1203 // the same or one is a base class of the other:
1204 QualType FTy = From->getType();
1205 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001206 const RecordType *FRec = FTy->getAs<RecordType>();
1207 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001208 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1209 if (FRec && TRec && (FRec == TRec ||
1210 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1211 // E1 can be converted to match E2 if the class of T2 is the
1212 // same type as, or a base class of, the class of T1, and
1213 // [cv2 > cv1].
1214 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1215 // Could still fail if there's no copy constructor.
1216 // FIXME: Is this a hard error then, or just a conversion failure? The
1217 // standard doesn't say.
1218 ICS = Self.TryCopyInitialization(From, TTy);
1219 }
1220 } else {
1221 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1222 // implicitly converted to the type that expression E2 would have
1223 // if E2 were converted to an rvalue.
1224 // First find the decayed type.
1225 if (TTy->isFunctionType())
1226 TTy = Self.Context.getPointerType(TTy);
1227 else if(TTy->isArrayType())
1228 TTy = Self.Context.getArrayDecayedType(TTy);
1229
1230 // Now try the implicit conversion.
1231 // FIXME: This doesn't detect ambiguities.
1232 ICS = Self.TryImplicitConversion(From, TTy);
1233 }
1234 return false;
1235}
1236
1237/// \brief Try to find a common type for two according to C++0x 5.16p5.
1238///
1239/// This is part of the parameter validation for the ? operator. If either
1240/// value operand is a class type, overload resolution is used to find a
1241/// conversion to a common type.
1242static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1243 SourceLocation Loc) {
1244 Expr *Args[2] = { LHS, RHS };
1245 OverloadCandidateSet CandidateSet;
1246 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1247
1248 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001249 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001250 case Sema::OR_Success:
1251 // We found a match. Perform the conversions on the arguments and move on.
1252 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1253 Best->Conversions[0], "converting") ||
1254 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1255 Best->Conversions[1], "converting"))
1256 break;
1257 return false;
1258
1259 case Sema::OR_No_Viable_Function:
1260 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1261 << LHS->getType() << RHS->getType()
1262 << LHS->getSourceRange() << RHS->getSourceRange();
1263 return true;
1264
1265 case Sema::OR_Ambiguous:
1266 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1267 << LHS->getType() << RHS->getType()
1268 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001269 // FIXME: Print the possible common types by printing the return types of
1270 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001271 break;
1272
1273 case Sema::OR_Deleted:
1274 assert(false && "Conditional operator has only built-in overloads");
1275 break;
1276 }
1277 return true;
1278}
1279
Sebastian Redl76458502009-04-17 16:30:52 +00001280/// \brief Perform an "extended" implicit conversion as returned by
1281/// TryClassUnification.
1282///
1283/// TryClassUnification generates ICSs that include reference bindings.
1284/// PerformImplicitConversion is not suitable for this; it chokes if the
1285/// second part of a standard conversion is ICK_DerivedToBase. This function
1286/// handles the reference binding specially.
1287static bool ConvertForConditional(Sema &Self, Expr *&E,
1288 const ImplicitConversionSequence &ICS)
1289{
1290 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1291 ICS.Standard.ReferenceBinding) {
1292 assert(ICS.Standard.DirectBinding &&
1293 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001294 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1295 // redoing all the work.
1296 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1297 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001298 }
1299 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1300 ICS.UserDefined.After.ReferenceBinding) {
1301 assert(ICS.UserDefined.After.DirectBinding &&
1302 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001303 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1304 TargetType(ICS)));
Sebastian Redl76458502009-04-17 16:30:52 +00001305 }
1306 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1307 return true;
1308 return false;
1309}
1310
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001311/// \brief Check the operands of ?: under C++ semantics.
1312///
1313/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1314/// extension. In this case, LHS == Cond. (But they're not aliases.)
1315QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1316 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001317 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1318 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001319
1320 // C++0x 5.16p1
1321 // The first expression is contextually converted to bool.
1322 if (!Cond->isTypeDependent()) {
1323 if (CheckCXXBooleanCondition(Cond))
1324 return QualType();
1325 }
1326
1327 // Either of the arguments dependent?
1328 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1329 return Context.DependentTy;
1330
1331 // C++0x 5.16p2
1332 // If either the second or the third operand has type (cv) void, ...
1333 QualType LTy = LHS->getType();
1334 QualType RTy = RHS->getType();
1335 bool LVoid = LTy->isVoidType();
1336 bool RVoid = RTy->isVoidType();
1337 if (LVoid || RVoid) {
1338 // ... then the [l2r] conversions are performed on the second and third
1339 // operands ...
1340 DefaultFunctionArrayConversion(LHS);
1341 DefaultFunctionArrayConversion(RHS);
1342 LTy = LHS->getType();
1343 RTy = RHS->getType();
1344
1345 // ... and one of the following shall hold:
1346 // -- The second or the third operand (but not both) is a throw-
1347 // expression; the result is of the type of the other and is an rvalue.
1348 bool LThrow = isa<CXXThrowExpr>(LHS);
1349 bool RThrow = isa<CXXThrowExpr>(RHS);
1350 if (LThrow && !RThrow)
1351 return RTy;
1352 if (RThrow && !LThrow)
1353 return LTy;
1354
1355 // -- Both the second and third operands have type void; the result is of
1356 // type void and is an rvalue.
1357 if (LVoid && RVoid)
1358 return Context.VoidTy;
1359
1360 // Neither holds, error.
1361 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1362 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1363 << LHS->getSourceRange() << RHS->getSourceRange();
1364 return QualType();
1365 }
1366
1367 // Neither is void.
1368
1369 // C++0x 5.16p3
1370 // Otherwise, if the second and third operand have different types, and
1371 // either has (cv) class type, and attempt is made to convert each of those
1372 // operands to the other.
1373 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1374 (LTy->isRecordType() || RTy->isRecordType())) {
1375 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1376 // These return true if a single direction is already ambiguous.
1377 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1378 return QualType();
1379 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1380 return QualType();
1381
1382 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1383 ImplicitConversionSequence::BadConversion;
1384 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1385 ImplicitConversionSequence::BadConversion;
1386 // If both can be converted, [...] the program is ill-formed.
1387 if (HaveL2R && HaveR2L) {
1388 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1389 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1390 return QualType();
1391 }
1392
1393 // If exactly one conversion is possible, that conversion is applied to
1394 // the chosen operand and the converted operands are used in place of the
1395 // original operands for the remainder of this section.
1396 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001397 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001398 return QualType();
1399 LTy = LHS->getType();
1400 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001401 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001402 return QualType();
1403 RTy = RHS->getType();
1404 }
1405 }
1406
1407 // C++0x 5.16p4
1408 // If the second and third operands are lvalues and have the same type,
1409 // the result is of that type [...]
1410 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1411 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1412 RHS->isLvalue(Context) == Expr::LV_Valid)
1413 return LTy;
1414
1415 // C++0x 5.16p5
1416 // Otherwise, the result is an rvalue. If the second and third operands
1417 // do not have the same type, and either has (cv) class type, ...
1418 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1419 // ... overload resolution is used to determine the conversions (if any)
1420 // to be applied to the operands. If the overload resolution fails, the
1421 // program is ill-formed.
1422 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1423 return QualType();
1424 }
1425
1426 // C++0x 5.16p6
1427 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1428 // conversions are performed on the second and third operands.
1429 DefaultFunctionArrayConversion(LHS);
1430 DefaultFunctionArrayConversion(RHS);
1431 LTy = LHS->getType();
1432 RTy = RHS->getType();
1433
1434 // After those conversions, one of the following shall hold:
1435 // -- The second and third operands have the same type; the result
1436 // is of that type.
1437 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1438 return LTy;
1439
1440 // -- The second and third operands have arithmetic or enumeration type;
1441 // the usual arithmetic conversions are performed to bring them to a
1442 // common type, and the result is of that type.
1443 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1444 UsualArithmeticConversions(LHS, RHS);
1445 return LHS->getType();
1446 }
1447
1448 // -- The second and third operands have pointer type, or one has pointer
1449 // type and the other is a null pointer constant; pointer conversions
1450 // and qualification conversions are performed to bring them to their
1451 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001452 QualType Composite = FindCompositePointerType(LHS, RHS);
1453 if (!Composite.isNull())
1454 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001455
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001456 // Fourth bullet is same for pointers-to-member. However, the possible
1457 // conversions are far more limited: we have null-to-pointer, upcast of
1458 // containing class, and second-level cv-ness.
1459 // cv-ness is not a union, but must match one of the two operands. (Which,
1460 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001461 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1462 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001463 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1464 ImpCastExprToType(RHS, LTy);
1465 return LTy;
1466 }
1467 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1468 ImpCastExprToType(LHS, RTy);
1469 return RTy;
1470 }
1471 if (LMemPtr && RMemPtr) {
1472 QualType LPointee = LMemPtr->getPointeeType();
1473 QualType RPointee = RMemPtr->getPointeeType();
1474 // First, we check that the unqualified pointee type is the same. If it's
1475 // not, there's no conversion that will unify the two pointers.
1476 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1477 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1478 // Second, we take the greater of the two cv qualifications. If neither
1479 // is greater than the other, the conversion is not possible.
1480 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1481 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1482 // Third, we check if either of the container classes is derived from
1483 // the other.
1484 QualType LContainer(LMemPtr->getClass(), 0);
1485 QualType RContainer(RMemPtr->getClass(), 0);
1486 QualType MoreDerived;
1487 if (Context.getCanonicalType(LContainer) ==
1488 Context.getCanonicalType(RContainer))
1489 MoreDerived = LContainer;
1490 else if (IsDerivedFrom(LContainer, RContainer))
1491 MoreDerived = LContainer;
1492 else if (IsDerivedFrom(RContainer, LContainer))
1493 MoreDerived = RContainer;
1494
1495 if (!MoreDerived.isNull()) {
1496 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1497 // We don't use ImpCastExprToType here because this could still fail
1498 // for ambiguous or inaccessible conversions.
1499 QualType Common = Context.getMemberPointerType(
1500 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1501 if (PerformImplicitConversion(LHS, Common, "converting"))
1502 return QualType();
1503 if (PerformImplicitConversion(RHS, Common, "converting"))
1504 return QualType();
1505 return Common;
1506 }
1507 }
1508 }
1509 }
1510
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001511 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1512 << LHS->getType() << RHS->getType()
1513 << LHS->getSourceRange() << RHS->getSourceRange();
1514 return QualType();
1515}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001516
1517/// \brief Find a merged pointer type and convert the two expressions to it.
1518///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001519/// This finds the composite pointer type (or member pointer type) for @p E1
1520/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1521/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001522/// It does not emit diagnostics.
1523QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1524 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1525 QualType T1 = E1->getType(), T2 = E2->getType();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001526
1527 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1528 !T2->isPointerType() && !T2->isMemberPointerType())
1529 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001530
Douglas Gregor20b3e992009-08-24 17:42:35 +00001531 // FIXME: Do we need to work on the canonical types?
1532
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001533 // C++0x 5.9p2
1534 // Pointer conversions and qualification conversions are performed on
1535 // pointer operands to bring them to their composite pointer type. If
1536 // one operand is a null pointer constant, the composite pointer type is
1537 // the type of the other operand.
1538 if (E1->isNullPointerConstant(Context)) {
1539 ImpCastExprToType(E1, T2);
1540 return T2;
1541 }
1542 if (E2->isNullPointerConstant(Context)) {
1543 ImpCastExprToType(E2, T1);
1544 return T1;
1545 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00001546
1547 // Now both have to be pointers or member pointers.
1548 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1549 !T2->isPointerType() && !T2->isMemberPointerType())
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001550 return QualType();
1551
1552 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1553 // the other has type "pointer to cv2 T" and the composite pointer type is
1554 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1555 // Otherwise, the composite pointer type is a pointer type similar to the
1556 // type of one of the operands, with a cv-qualification signature that is
1557 // the union of the cv-qualification signatures of the operand types.
1558 // In practice, the first part here is redundant; it's subsumed by the second.
1559 // What we do here is, we build the two possible composite types, and try the
1560 // conversions in both directions. If only one works, or if the two composite
1561 // types are the same, we have succeeded.
1562 llvm::SmallVector<unsigned, 4> QualifierUnion;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001563 llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001564 QualType Composite1 = T1, Composite2 = T2;
Douglas Gregor20b3e992009-08-24 17:42:35 +00001565 do {
1566 const PointerType *Ptr1, *Ptr2;
1567 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1568 (Ptr2 = Composite2->getAs<PointerType>())) {
1569 Composite1 = Ptr1->getPointeeType();
1570 Composite2 = Ptr2->getPointeeType();
1571 QualifierUnion.push_back(
1572 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1573 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1574 continue;
1575 }
1576
1577 const MemberPointerType *MemPtr1, *MemPtr2;
1578 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1579 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1580 Composite1 = MemPtr1->getPointeeType();
1581 Composite2 = MemPtr2->getPointeeType();
1582 QualifierUnion.push_back(
1583 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1584 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1585 MemPtr2->getClass()));
1586 continue;
1587 }
1588
1589 // FIXME: block pointer types?
1590
1591 // Cannot unwrap any more types.
1592 break;
1593 } while (true);
1594
1595 // Rewrap the composites as pointers or member pointers with the union CVRs.
1596 llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1597 = MemberOfClass.begin();
1598 for (llvm::SmallVector<unsigned, 4>::iterator
1599 I = QualifierUnion.begin(),
1600 E = QualifierUnion.end();
1601 I != E; (void)++I, ++MOC) {
1602 if (MOC->first && MOC->second) {
1603 // Rebuild member pointer type
1604 Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1605 MOC->first);
1606 Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1607 MOC->second);
1608 } else {
1609 // Rebuild pointer type
1610 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1611 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1612 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001613 }
1614
1615 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1616 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1617 ImplicitConversionSequence E1ToC2, E2ToC2;
1618 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1619 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1620 if (Context.getCanonicalType(Composite1) !=
1621 Context.getCanonicalType(Composite2)) {
1622 E1ToC2 = TryImplicitConversion(E1, Composite2);
1623 E2ToC2 = TryImplicitConversion(E2, Composite2);
1624 }
1625
1626 bool ToC1Viable = E1ToC1.ConversionKind !=
1627 ImplicitConversionSequence::BadConversion
1628 && E2ToC1.ConversionKind !=
1629 ImplicitConversionSequence::BadConversion;
1630 bool ToC2Viable = E1ToC2.ConversionKind !=
1631 ImplicitConversionSequence::BadConversion
1632 && E2ToC2.ConversionKind !=
1633 ImplicitConversionSequence::BadConversion;
1634 if (ToC1Viable && !ToC2Viable) {
1635 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1636 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1637 return Composite1;
1638 }
1639 if (ToC2Viable && !ToC1Viable) {
1640 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1641 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1642 return Composite2;
1643 }
1644 return QualType();
1645}
Anders Carlsson165a0a02009-05-17 18:41:29 +00001646
Anders Carlssondef11992009-05-30 20:36:53 +00001647Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00001648 if (!Context.getLangOptions().CPlusPlus)
1649 return Owned(E);
1650
Ted Kremenek6217b802009-07-29 21:53:49 +00001651 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00001652 if (!RT)
1653 return Owned(E);
1654
1655 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1656 if (RD->hasTrivialDestructor())
1657 return Owned(E);
1658
1659 CXXTemporary *Temp = CXXTemporary::Create(Context,
1660 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00001661 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00001662 if (CXXDestructorDecl *Destructor =
1663 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1664 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00001665 // FIXME: Add the temporary to the temporaries vector.
1666 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1667}
1668
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001669Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00001670 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001671 assert(SubExpr && "sub expression can't be null!");
1672
1673 if (ExprTemporaries.empty())
1674 return SubExpr;
1675
1676 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1677 &ExprTemporaries[0],
1678 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00001679 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001680 ExprTemporaries.clear();
1681
1682 return E;
1683}
1684
Anders Carlssonec773872009-08-25 23:46:41 +00001685Sema::OwningExprResult
1686Sema::ActOnPseudoDtorReferenceExpr(Scope *S, ExprArg Base,
1687 SourceLocation OpLoc,
1688 tok::TokenKind OpKind,
1689 SourceLocation ClassNameLoc,
1690 IdentifierInfo *ClassName,
1691 const CXXScopeSpec *SS) {
1692 if (SS && SS->isInvalid())
1693 return ExprError();
1694
1695 // Since this might be a postfix expression, get rid of ParenListExprs.
1696 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1697
1698 Expr *BaseExpr = Base.takeAs<Expr>();
1699 assert(BaseExpr && "no record expression");
1700
1701 // Perform default conversions.
1702 DefaultFunctionArrayConversion(BaseExpr);
1703
1704 QualType BaseType = BaseExpr->getType();
1705 return ExprError();
1706}
1707
Anders Carlsson165a0a02009-05-17 18:41:29 +00001708Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1709 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00001710 if (FullExpr)
Anders Carlssonf54741e2009-06-16 03:37:31 +00001711 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1712 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00001713
Anders Carlssonec773872009-08-25 23:46:41 +00001714
Anders Carlsson165a0a02009-05-17 18:41:29 +00001715 return Owned(FullExpr);
1716}