blob: 5e0ce666ea2ffe338f3330d136e04fe70706fec0 [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
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Sebastian Redlc42e1182008-11-11 11:37:55 +000027/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000028Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000029Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
30 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000031 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000032 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000033
34 if (isType)
35 // FIXME: Preserve type source info.
36 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
37
Chris Lattner572af492008-11-20 05:51:55 +000038 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000039 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
40 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +000041 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +000042 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +000043 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +000044
45 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
46
Douglas Gregorac7610d2009-06-22 20:57:11 +000047 if (!isType) {
48 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +000049 // When typeid is applied to an expression other than an lvalue of a
50 // polymorphic class type [...] [the] expression is an unevaluated
Douglas Gregorac7610d2009-06-22 20:57:11 +000051 // operand.
Mike Stump1eb44332009-09-09 15:08:12 +000052
Douglas Gregorac7610d2009-06-22 20:57:11 +000053 // FIXME: if the type of the expression is a class type, the class
54 // shall be completely defined.
55 bool isUnevaluatedOperand = true;
56 Expr *E = static_cast<Expr *>(TyOrExpr);
57 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
58 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +000059 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000060 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
61 if (RecordD->isPolymorphic())
62 isUnevaluatedOperand = false;
63 }
64 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregor2afce722009-11-26 00:44:06 +000066 // If this is an unevaluated operand, clear out the set of
67 // declaration references we have been computing and eliminate any
68 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +000069 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +000070 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +000071 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Sebastian Redlf53597f2009-03-15 17:47:39 +000073 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
74 TypeInfoType.withConst(),
75 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076}
77
Steve Naroff1b273c42007-09-16 14:56:35 +000078/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000079Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000081 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000082 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000083 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
84 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
Chris Lattner50dd2892008-02-26 00:51:44 +000086
Sebastian Redl6e8ed162009-05-10 18:38:11 +000087/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
88Action::OwningExprResult
89Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
90 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
91}
92
Chris Lattner50dd2892008-02-26 00:51:44 +000093/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000094Action::OwningExprResult
95Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000096 Expr *Ex = E.takeAs<Expr>();
97 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
98 return ExprError();
99 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
100}
101
102/// CheckCXXThrowOperand - Validate the operand of a throw.
103bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
104 // C++ [except.throw]p3:
105 // [...] adjusting the type from "array of T" or "function returning T"
106 // to "pointer to T" or "pointer to function returning T", [...]
107 DefaultFunctionArrayConversion(E);
108
109 // If the type of the exception would be an incomplete type or a pointer
110 // to an incomplete type other than (cv) void the program is ill-formed.
111 QualType Ty = E->getType();
112 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000113 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000114 Ty = Ptr->getPointeeType();
115 isPointer = 1;
116 }
117 if (!isPointer || !Ty->isVoidType()) {
118 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000119 PDiag(isPointer ? diag::err_throw_incomplete_ptr
120 : diag::err_throw_incomplete)
121 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000122 return true;
123 }
124
125 // FIXME: Construct a temporary here.
126 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000127}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000128
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000130 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
131 /// is a non-lvalue expression whose value is the address of the object for
132 /// which the function is called.
133
Sebastian Redlf53597f2009-03-15 17:47:39 +0000134 if (!isa<FunctionDecl>(CurContext))
135 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000136
137 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
138 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000139 return Owned(new (Context) CXXThisExpr(ThisLoc,
140 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000141
Sebastian Redlf53597f2009-03-15 17:47:39 +0000142 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000143}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000144
145/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
146/// Can be interpreted either as function-style casting ("int(x)")
147/// or class type construction ("ClassType(x,y,z)")
148/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000149Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000150Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
151 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000153 SourceLocation *CommaLocs,
154 SourceLocation RParenLoc) {
155 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000156 // FIXME: Preserve type source info.
157 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000158 unsigned NumExprs = exprs.size();
159 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000160 SourceLocation TyBeginLoc = TypeRange.getBegin();
161 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000164 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
167 return Owned(CXXUnresolvedConstructExpr::Create(Context,
168 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000169 LParenLoc,
170 Exprs, NumExprs,
171 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000172 }
173
Anders Carlssonbb60a502009-08-27 03:53:50 +0000174 if (Ty->isArrayType())
175 return ExprError(Diag(TyBeginLoc,
176 diag::err_value_init_for_array_type) << FullRange);
177 if (!Ty->isVoidType() &&
178 RequireCompleteType(TyBeginLoc, Ty,
179 PDiag(diag::err_invalid_incomplete_type_use)
180 << FullRange))
181 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000182
Anders Carlssonbb60a502009-08-27 03:53:50 +0000183 if (RequireNonAbstractType(TyBeginLoc, Ty,
184 diag::err_allocation_of_abstract_type))
185 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
187
Douglas Gregor506ae412009-01-16 18:33:17 +0000188 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000189 // If the expression list is a single expression, the type conversion
190 // expression is equivalent (in definedness, and if defined in meaning) to the
191 // corresponding cast expression.
192 //
193 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000194 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000195 CXXMethodDecl *Method = 0;
196 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
197 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000198 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000199
200 exprs.release();
201 if (Method) {
202 OwningExprResult CastArg
203 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
204 Kind, Method, Owned(Exprs[0]));
205 if (CastArg.isInvalid())
206 return ExprError();
207
208 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000209 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000210
211 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
212 Ty, TyBeginLoc, Kind,
213 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000214 }
215
Ted Kremenek6217b802009-07-29 21:53:49 +0000216 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000217 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000218
Mike Stump1eb44332009-09-09 15:08:12 +0000219 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000220 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000221 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
222
Douglas Gregor506ae412009-01-16 18:33:17 +0000223 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000224 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000225 TypeRange.getBegin(),
226 SourceRange(TypeRange.getBegin(),
227 RParenLoc),
228 DeclarationName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000229 InitializationKind::CreateDirect(TypeRange.getBegin(),
230 LParenLoc,
231 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000232 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000233
Sebastian Redlf53597f2009-03-15 17:47:39 +0000234 if (!Constructor)
235 return ExprError();
236
Mike Stump1eb44332009-09-09 15:08:12 +0000237 OwningExprResult Result =
238 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000239 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000240 if (Result.isInvalid())
241 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Anders Carlssone7624a72009-08-27 05:08:22 +0000243 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000244 }
245
246 // Fall through to value-initialize an object of class type that
247 // doesn't have a user-declared default constructor.
248 }
249
250 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000251 // If the expression list specifies more than a single value, the type shall
252 // be a class with a suitably declared constructor.
253 //
254 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000255 return ExprError(Diag(CommaLocs[0],
256 diag::err_builtin_func_cast_more_than_one_arg)
257 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000258
259 assert(NumExprs == 0 && "Expected 0 expressions");
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 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000265 exprs.release();
266 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000267}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000268
269
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000270/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
271/// @code new (memory) int[size][4] @endcode
272/// or
273/// @code ::new Foo(23, "hello") @endcode
274/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000275Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000276Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000278 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000280 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000281 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000282 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000283 // If the specified type is an array, unwrap it and save the expression.
284 if (D.getNumTypeObjects() > 0 &&
285 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
286 DeclaratorChunk &Chunk = D.getTypeObject(0);
287 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000288 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
289 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000290 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000291 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
292 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000293
294 if (ParenTypeId) {
295 // Can't have dynamic array size when the type-id is in parentheses.
296 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
297 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
298 !NumElts->isIntegerConstantExpr(Context)) {
299 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
300 << NumElts->getSourceRange();
301 return ExprError();
302 }
303 }
304
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000305 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000306 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000307 }
308
Douglas Gregor043cad22009-09-11 00:18:58 +0000309 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000310 if (ArraySize) {
311 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000312 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
313 break;
314
315 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
316 if (Expr *NumElts = (Expr *)Array.NumElts) {
317 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
318 !NumElts->isIntegerConstantExpr(Context)) {
319 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
320 << NumElts->getSourceRange();
321 return ExprError();
322 }
323 }
324 }
325 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000326
John McCalla93c9342009-12-07 02:54:59 +0000327 //FIXME: Store TypeSourceInfo in CXXNew expression.
328 TypeSourceInfo *TInfo = 0;
329 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000330 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000331 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000332
Mike Stump1eb44332009-09-09 15:08:12 +0000333 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000334 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000335 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000336 PlacementRParen,
337 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000338 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000339 D.getSourceRange().getBegin(),
340 D.getSourceRange(),
341 Owned(ArraySize),
342 ConstructorLParen,
343 move(ConstructorArgs),
344 ConstructorRParen);
345}
346
Mike Stump1eb44332009-09-09 15:08:12 +0000347Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000348Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
349 SourceLocation PlacementLParen,
350 MultiExprArg PlacementArgs,
351 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000352 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000353 QualType AllocType,
354 SourceLocation TypeLoc,
355 SourceRange TypeRange,
356 ExprArg ArraySizeE,
357 SourceLocation ConstructorLParen,
358 MultiExprArg ConstructorArgs,
359 SourceLocation ConstructorRParen) {
360 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000361 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000362
Douglas Gregor3433cf72009-05-21 00:00:09 +0000363 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000364
365 // That every array dimension except the first is constant was already
366 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000367
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000368 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
369 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000370 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000371 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000372 QualType SizeType = ArraySize->getType();
373 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000374 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
375 diag::err_array_size_not_integral)
376 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000377 // Let's see if this is a constant < 0. If so, we reject it out of hand.
378 // We don't care about special rules, so we tell the machinery it's not
379 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000380 if (!ArraySize->isValueDependent()) {
381 llvm::APSInt Value;
382 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
383 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000384 llvm::APInt::getNullValue(Value.getBitWidth()),
385 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000386 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
387 diag::err_typecheck_negative_array_size)
388 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000389 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000390 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000391
Eli Friedman73c39ab2009-10-20 08:27:19 +0000392 ImpCastExprToType(ArraySize, Context.getSizeType(),
393 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000394 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000395
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000396 FunctionDecl *OperatorNew = 0;
397 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000398 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
399 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000400
Sebastian Redl28507842009-02-26 14:39:58 +0000401 if (!AllocType->isDependentType() &&
402 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
403 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000404 SourceRange(PlacementLParen, PlacementRParen),
405 UseGlobal, AllocType, ArraySize, PlaceArgs,
406 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000407 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000408 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000409 if (OperatorNew) {
410 // Add default arguments, if any.
411 const FunctionProtoType *Proto =
412 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000413 VariadicCallType CallType =
414 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000415 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
416 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000417 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000418 if (Invalid)
419 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000420
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000421 NumPlaceArgs = AllPlaceArgs.size();
422 if (NumPlaceArgs > 0)
423 PlaceArgs = &AllPlaceArgs[0];
424 }
425
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000426 bool Init = ConstructorLParen.isValid();
427 // --- Choosing a constructor ---
428 // C++ 5.3.4p15
429 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
430 // the object is not initialized. If the object, or any part of it, is
431 // const-qualified, it's an error.
432 // 2) If T is a POD and there's an empty initializer, the object is value-
433 // initialized.
434 // 3) If T is a POD and there's one initializer argument, the object is copy-
435 // constructed.
436 // 4) If T is a POD and there's more initializer arguments, it's an error.
437 // 5) If T is not a POD, the initializer arguments are used as constructor
438 // arguments.
439 //
440 // Or by the C++0x formulation:
441 // 1) If there's no initializer, the object is default-initialized according
442 // to C++0x rules.
443 // 2) Otherwise, the object is direct-initialized.
444 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000445 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000446 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000447 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000448 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
449
Douglas Gregor089407b2009-10-17 21:40:42 +0000450 if (AllocType->isDependentType() ||
451 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000452 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000453 } else if ((RT = AllocType->getAs<RecordType>()) &&
454 !AllocType->isAggregateType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +0000455 InitializationKind InitKind = InitializationKind::CreateDefault(TypeLoc);
456 if (NumConsArgs > 0)
457 InitKind = InitializationKind::CreateDirect(TypeLoc,
458 PlacementLParen,
459 PlacementRParen);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000460 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000461 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000462 TypeLoc,
463 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000464 RT->getDecl()->getDeclName(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000465 InitKind,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000466 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000467 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000469
470 // Take the converted constructor arguments and use them for the new
471 // expression.
472 NumConsArgs = ConvertedConstructorArgs.size();
473 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000474 } else {
475 if (!Init) {
476 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 if (AllocType.isConstQualified())
478 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000479 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000480 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000481 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000482 } else if (NumConsArgs == 1) {
483 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000484 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000485 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000486 DeclarationName() /*AllocType.getAsString()*/,
487 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000489 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000490 return ExprError(Diag(StartLoc,
491 diag::err_builtin_direct_init_more_than_one_arg)
492 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000493 }
494 }
495
496 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000497
Sebastian Redlf53597f2009-03-15 17:47:39 +0000498 PlacementArgs.release();
499 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000500 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000501 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000502 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000503 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000504 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000505}
506
507/// CheckAllocatedType - Checks that a type is suitable as the allocated type
508/// in a new-expression.
509/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000510bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000511 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000512 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
513 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000514 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000515 return Diag(Loc, diag::err_bad_new_type)
516 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000517 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000518 return Diag(Loc, diag::err_bad_new_type)
519 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000520 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000522 PDiag(diag::err_new_incomplete_type)
523 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000524 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000525 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000526 diag::err_allocation_of_abstract_type))
527 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000528
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000529 return false;
530}
531
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000532/// FindAllocationFunctions - Finds the overloads of operator new and delete
533/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000534bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
535 bool UseGlobal, QualType AllocType,
536 bool IsArray, Expr **PlaceArgs,
537 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000538 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000539 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000540 // --- Choosing an allocation function ---
541 // C++ 5.3.4p8 - 14 & 18
542 // 1) If UseGlobal is true, only look in the global scope. Else, also look
543 // in the scope of the allocated class.
544 // 2) If an array size is given, look for operator new[], else look for
545 // operator new.
546 // 3) The first argument is always size_t. Append the arguments from the
547 // placement form.
548 // FIXME: Also find the appropriate delete operator.
549
550 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
551 // We don't care about the actual value of this argument.
552 // FIXME: Should the Sema create the expression and embed it in the syntax
553 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000554 IntegerLiteral Size(llvm::APInt::getNullValue(
555 Context.Target.getPointerWidth(0)),
556 Context.getSizeType(),
557 SourceLocation());
558 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000559 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
560
561 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
562 IsArray ? OO_Array_New : OO_New);
563 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000564 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000565 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000566 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000567 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000568 AllocArgs.size(), Record, /*AllowMissing=*/true,
569 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000570 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000571 }
572 if (!OperatorNew) {
573 // Didn't find a member overload. Look for a global one.
574 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000575 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000576 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000577 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
578 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000579 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000580 }
581
Anders Carlssond9583892009-05-31 20:26:12 +0000582 // FindAllocationOverload can change the passed in arguments, so we need to
583 // copy them back.
584 if (NumPlaceArgs > 0)
585 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000587 return false;
588}
589
Sebastian Redl7f662392008-12-04 22:20:51 +0000590/// FindAllocationOverload - Find an fitting overload for the allocation
591/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000592bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
593 DeclarationName Name, Expr** Args,
594 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000595 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000596 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
597 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000598 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000599 if (AllowMissing)
600 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000601 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000602 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000603 }
604
John McCallf36e02d2009-10-09 21:13:30 +0000605 // FIXME: handle ambiguity
606
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000608 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
609 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000610 // Even member operator new/delete are implicitly treated as
611 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000612 if (FunctionDecl *Fn =
613 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000614 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
615 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000616 continue;
617 }
618
619 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000620 }
621
622 // Do the resolution.
623 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000624 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000625 case OR_Success: {
626 // Got one!
627 FunctionDecl *FnDecl = Best->Function;
628 // The first argument is size_t, and the first parameter must be size_t,
629 // too. This is checked on declaration and can be assumed. (It can't be
630 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000631 // Whatch out for variadic allocator function.
632 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
633 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000635 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000636 FnDecl->getParamDecl(i)->getType(),
637 "passing"))
638 return true;
639 }
640 Operator = FnDecl;
641 return false;
642 }
643
644 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000645 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000646 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000647 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
648 return true;
649
650 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000651 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000652 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000653 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
654 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000655
656 case OR_Deleted:
657 Diag(StartLoc, diag::err_ovl_deleted_call)
658 << Best->Function->isDeleted()
659 << Name << Range;
660 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
661 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000662 }
663 assert(false && "Unreachable, bad result from BestViableFunction");
664 return true;
665}
666
667
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000668/// DeclareGlobalNewDelete - Declare the global forms of operator new and
669/// delete. These are:
670/// @code
671/// void* operator new(std::size_t) throw(std::bad_alloc);
672/// void* operator new[](std::size_t) throw(std::bad_alloc);
673/// void operator delete(void *) throw();
674/// void operator delete[](void *) throw();
675/// @endcode
676/// Note that the placement and nothrow forms of new are *not* implicitly
677/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000678void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000679 if (GlobalNewDeleteDeclared)
680 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000681
682 // C++ [basic.std.dynamic]p2:
683 // [...] The following allocation and deallocation functions (18.4) are
684 // implicitly declared in global scope in each translation unit of a
685 // program
686 //
687 // void* operator new(std::size_t) throw(std::bad_alloc);
688 // void* operator new[](std::size_t) throw(std::bad_alloc);
689 // void operator delete(void*) throw();
690 // void operator delete[](void*) throw();
691 //
692 // These implicit declarations introduce only the function names operator
693 // new, operator new[], operator delete, operator delete[].
694 //
695 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
696 // "std" or "bad_alloc" as necessary to form the exception specification.
697 // However, we do not make these implicit declarations visible to name
698 // lookup.
699 if (!StdNamespace) {
700 // The "std" namespace has not yet been defined, so build one implicitly.
701 StdNamespace = NamespaceDecl::Create(Context,
702 Context.getTranslationUnitDecl(),
703 SourceLocation(),
704 &PP.getIdentifierTable().get("std"));
705 StdNamespace->setImplicit(true);
706 }
707
708 if (!StdBadAlloc) {
709 // The "std::bad_alloc" class has not yet been declared, so build it
710 // implicitly.
711 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
712 StdNamespace,
713 SourceLocation(),
714 &PP.getIdentifierTable().get("bad_alloc"),
715 SourceLocation(), 0);
716 StdBadAlloc->setImplicit(true);
717 }
718
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000719 GlobalNewDeleteDeclared = true;
720
721 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
722 QualType SizeT = Context.getSizeType();
723
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000724 DeclareGlobalAllocationFunction(
725 Context.DeclarationNames.getCXXOperatorName(OO_New),
726 VoidPtr, SizeT);
727 DeclareGlobalAllocationFunction(
728 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
729 VoidPtr, SizeT);
730 DeclareGlobalAllocationFunction(
731 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
732 Context.VoidTy, VoidPtr);
733 DeclareGlobalAllocationFunction(
734 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
735 Context.VoidTy, VoidPtr);
736}
737
738/// DeclareGlobalAllocationFunction - Declares a single implicit global
739/// allocation function if it doesn't already exist.
740void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000741 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000742 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
743
744 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000745 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000746 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000747 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000748 Alloc != AllocEnd; ++Alloc) {
749 // FIXME: Do we need to check for default arguments here?
750 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
751 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000752 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000753 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000754 }
755 }
756
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000757 QualType BadAllocType;
758 bool HasBadAllocExceptionSpec
759 = (Name.getCXXOverloadedOperator() == OO_New ||
760 Name.getCXXOverloadedOperator() == OO_Array_New);
761 if (HasBadAllocExceptionSpec) {
762 assert(StdBadAlloc && "Must have std::bad_alloc declared");
763 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
764 }
765
766 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
767 true, false,
768 HasBadAllocExceptionSpec? 1 : 0,
769 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000770 FunctionDecl *Alloc =
771 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000772 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000773 Alloc->setImplicit();
774 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000775 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000776 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000777 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000778
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000779 // FIXME: Also add this declaration to the IdentifierResolver, but
780 // make sure it is at the end of the chain to coincide with the
781 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000782 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000783}
784
Anders Carlsson78f74552009-11-15 18:45:20 +0000785bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
786 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000787 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000788 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000789 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000790 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000791
John McCalla24dc2e2009-11-17 02:14:36 +0000792 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000793 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000794
795 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
796 F != FEnd; ++F) {
797 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
798 if (Delete->isUsualDeallocationFunction()) {
799 Operator = Delete;
800 return false;
801 }
802 }
803
804 // We did find operator delete/operator delete[] declarations, but
805 // none of them were suitable.
806 if (!Found.empty()) {
807 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
808 << Name << RD;
809
810 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
811 F != FEnd; ++F) {
812 Diag((*F)->getLocation(),
813 diag::note_delete_member_function_declared_here)
814 << Name;
815 }
816
817 return true;
818 }
819
820 // Look for a global declaration.
821 DeclareGlobalNewDelete();
822 DeclContext *TUDecl = Context.getTranslationUnitDecl();
823
824 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
825 Expr* DeallocArgs[1];
826 DeallocArgs[0] = &Null;
827 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
828 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
829 Operator))
830 return true;
831
832 assert(Operator && "Did not find a deallocation function!");
833 return false;
834}
835
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000836/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
837/// @code ::delete ptr; @endcode
838/// or
839/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000840Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000841Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000842 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000843 // C++ [expr.delete]p1:
844 // The operand shall have a pointer type, or a class type having a single
845 // conversion function to a pointer type. The result has type void.
846 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000847 // DR599 amends "pointer type" to "pointer to object type" in both cases.
848
Anders Carlssond67c4c32009-08-16 20:29:29 +0000849 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Sebastian Redlf53597f2009-03-15 17:47:39 +0000851 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000852 if (!Ex->isTypeDependent()) {
853 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000854
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000855 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000856 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000857 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000858 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000859
John McCallba135432009-11-21 08:51:07 +0000860 for (UnresolvedSet::iterator I = Conversions->begin(),
861 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000862 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000863 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000864 continue;
865
John McCallba135432009-11-21 08:51:07 +0000866 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000867
868 QualType ConvType = Conv->getConversionType().getNonReferenceType();
869 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
870 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000871 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000872 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000873 if (ObjectPtrConversions.size() == 1) {
874 // We have a single conversion to a pointer-to-object type. Perform
875 // that conversion.
876 Operand.release();
877 if (!PerformImplicitConversion(Ex,
878 ObjectPtrConversions.front()->getConversionType(),
879 "converting")) {
880 Operand = Owned(Ex);
881 Type = Ex->getType();
882 }
883 }
884 else if (ObjectPtrConversions.size() > 1) {
885 Diag(StartLoc, diag::err_ambiguous_delete_operand)
886 << Type << Ex->getSourceRange();
887 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
888 CXXConversionDecl *Conv = ObjectPtrConversions[i];
889 Diag(Conv->getLocation(), diag::err_ovl_candidate);
890 }
891 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000892 }
Sebastian Redl28507842009-02-26 14:39:58 +0000893 }
894
Sebastian Redlf53597f2009-03-15 17:47:39 +0000895 if (!Type->isPointerType())
896 return ExprError(Diag(StartLoc, diag::err_delete_operand)
897 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000898
Ted Kremenek6217b802009-07-29 21:53:49 +0000899 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000900 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000901 return ExprError(Diag(StartLoc, diag::err_delete_operand)
902 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000903 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000904 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000905 PDiag(diag::warn_delete_incomplete)
906 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000907 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000908
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000909 // C++ [expr.delete]p2:
910 // [Note: a pointer to a const type can be the operand of a
911 // delete-expression; it is not necessary to cast away the constness
912 // (5.2.11) of the pointer expression before it is used as the operand
913 // of the delete-expression. ]
914 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
915 CastExpr::CK_NoOp);
916
917 // Update the operand.
918 Operand.take();
919 Operand = ExprArg(*this, Ex);
920
Anders Carlssond67c4c32009-08-16 20:29:29 +0000921 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
922 ArrayForm ? OO_Array_Delete : OO_Delete);
923
Anders Carlsson78f74552009-11-15 18:45:20 +0000924 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
925 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
926
927 if (!UseGlobal &&
928 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000929 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000930
Anders Carlsson78f74552009-11-15 18:45:20 +0000931 if (!RD->hasTrivialDestructor())
932 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000933 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000934 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000935 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000936
Anders Carlssond67c4c32009-08-16 20:29:29 +0000937 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000938 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000939 DeclareGlobalNewDelete();
940 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000941 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000942 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000943 OperatorDelete))
944 return ExprError();
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Sebastian Redl28507842009-02-26 14:39:58 +0000947 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000948 }
949
Sebastian Redlf53597f2009-03-15 17:47:39 +0000950 Operand.release();
951 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000952 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000953}
954
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000955/// \brief Check the use of the given variable as a C++ condition in an if,
956/// while, do-while, or switch statement.
957Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
958 QualType T = ConditionVar->getType();
959
960 // C++ [stmt.select]p2:
961 // The declarator shall not specify a function or an array.
962 if (T->isFunctionType())
963 return ExprError(Diag(ConditionVar->getLocation(),
964 diag::err_invalid_use_of_function_type)
965 << ConditionVar->getSourceRange());
966 else if (T->isArrayType())
967 return ExprError(Diag(ConditionVar->getLocation(),
968 diag::err_invalid_use_of_array_type)
969 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +0000970
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000971 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
972 ConditionVar->getLocation(),
973 ConditionVar->getType().getNonReferenceType()));
974}
975
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000976/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
977bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
978 // C++ 6.4p4:
979 // The value of a condition that is an initialized declaration in a statement
980 // other than a switch statement is the value of the declared variable
981 // implicitly converted to type bool. If that conversion is ill-formed, the
982 // program is ill-formed.
983 // The value of a condition that is an expression is the value of the
984 // expression, implicitly converted to bool.
985 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000986 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000987}
Douglas Gregor77a52232008-09-12 00:47:35 +0000988
989/// Helper function to determine whether this is the (deprecated) C++
990/// conversion from a string literal to a pointer to non-const char or
991/// non-const wchar_t (for narrow and wide string literals,
992/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000993bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000994Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
995 // Look inside the implicit cast, if it exists.
996 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
997 From = Cast->getSubExpr();
998
999 // A string literal (2.13.4) that is not a wide string literal can
1000 // be converted to an rvalue of type "pointer to char"; a wide
1001 // string literal can be converted to an rvalue of type "pointer
1002 // to wchar_t" (C++ 4.2p2).
1003 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001004 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001005 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001006 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001007 // This conversion is considered only when there is an
1008 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001009 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001010 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1011 (!StrLit->isWide() &&
1012 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1013 ToPointeeType->getKind() == BuiltinType::Char_S))))
1014 return true;
1015 }
1016
1017 return false;
1018}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001019
1020/// PerformImplicitConversion - Perform an implicit conversion of the
1021/// expression From to the type ToType. Returns true if there was an
1022/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001023/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001024/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001025/// explicit user-defined conversions are permitted. @p Elidable should be true
1026/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1027/// resolution works differently in that case.
1028bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001029Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001030 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001031 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001032 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001033 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1034 Elidable, ICS);
1035}
1036
1037bool
1038Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1039 const char *Flavor, bool AllowExplicit,
1040 bool Elidable,
1041 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001042 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1043 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001044 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001045 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001046 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001047 /*ForceRValue=*/true,
1048 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001049 }
1050 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001051 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001052 /*SuppressUserConversions=*/false,
1053 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001054 /*ForceRValue=*/false,
1055 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001056 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001057 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1058}
1059
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001060/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1061/// for the derived to base conversion of the expression 'From'. All
1062/// necessary information is passed in ICS.
1063bool
1064Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1065 const ImplicitConversionSequence& ICS,
1066 const char *Flavor) {
1067 QualType BaseType =
1068 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1069 // Must do additional defined to base conversion.
1070 QualType DerivedType =
1071 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1072
1073 From = new (Context) ImplicitCastExpr(
1074 DerivedType.getNonReferenceType(),
1075 CastKind,
1076 From,
1077 DerivedType->isLValueReferenceType());
1078 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1079 CastExpr::CK_DerivedToBase, From,
1080 BaseType->isLValueReferenceType());
1081 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1082 OwningExprResult FromResult =
1083 BuildCXXConstructExpr(
1084 ICS.UserDefined.After.CopyConstructor->getLocation(),
1085 BaseType,
1086 ICS.UserDefined.After.CopyConstructor,
1087 MultiExprArg(*this, (void **)&From, 1));
1088 if (FromResult.isInvalid())
1089 return true;
1090 From = FromResult.takeAs<Expr>();
1091 return false;
1092}
1093
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001094/// PerformImplicitConversion - Perform an implicit conversion of the
1095/// expression From to the type ToType using the pre-computed implicit
1096/// conversion sequence ICS. Returns true if there was an error, false
1097/// otherwise. The expression From is replaced with the converted
1098/// expression. Flavor is the kind of conversion we're performing,
1099/// used in the error message.
1100bool
1101Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1102 const ImplicitConversionSequence &ICS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001103 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001104 switch (ICS.ConversionKind) {
1105 case ImplicitConversionSequence::StandardConversion:
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001106 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1107 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001108 return true;
1109 break;
1110
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001111 case ImplicitConversionSequence::UserDefinedConversion: {
1112
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001113 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1114 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001115 QualType BeforeToType;
1116 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001117 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001118
1119 // If the user-defined conversion is specified by a conversion function,
1120 // the initial standard conversion sequence converts the source type to
1121 // the implicit object parameter of the conversion function.
1122 BeforeToType = Context.getTagDeclType(Conv->getParent());
1123 } else if (const CXXConstructorDecl *Ctor =
1124 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001125 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001126 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001127 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001128 // If the user-defined conversion is specified by a constructor, the
1129 // initial standard conversion sequence converts the source type to the
1130 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001131 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1132 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001133 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001134 else
1135 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001136 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001137 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001138 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001139 ICS.UserDefined.Before, "converting",
1140 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001141 return true;
1142 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001143
Anders Carlsson0aebc812009-09-09 21:33:21 +00001144 OwningExprResult CastArg
1145 = BuildCXXCastArgument(From->getLocStart(),
1146 ToType.getNonReferenceType(),
1147 CastKind, cast<CXXMethodDecl>(FD),
1148 Owned(From));
1149
1150 if (CastArg.isInvalid())
1151 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001152
1153 From = CastArg.takeAs<Expr>();
1154
1155 // FIXME: This and the following if statement shouldn't be necessary, but
1156 // there's some nasty stuff involving MaybeBindToTemporary going on here.
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001157 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1158 ICS.UserDefined.After.CopyConstructor) {
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001159 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1160 }
Eli Friedmand8889622009-11-27 04:41:50 +00001161
1162 if (ICS.UserDefined.After.CopyConstructor) {
1163 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1164 CastKind, From,
1165 ToType->isLValueReferenceType());
1166 return false;
1167 }
1168
1169 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1170 "converting", IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001171 }
1172
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001173 case ImplicitConversionSequence::EllipsisConversion:
1174 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001175 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001176
1177 case ImplicitConversionSequence::BadConversion:
1178 return true;
1179 }
1180
1181 // Everything went well.
1182 return false;
1183}
1184
1185/// PerformImplicitConversion - Perform an implicit conversion of the
1186/// expression From to the type ToType by following the standard
1187/// conversion sequence SCS. Returns true if there was an error, false
1188/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001189/// expression. Flavor is the context in which we're performing this
1190/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001191bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001192Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001193 const StandardConversionSequence& SCS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001194 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001195 // Overall FIXME: we are recomputing too many types here and doing far too
1196 // much extra work. What this means is that we need to keep track of more
1197 // information that is computed when we try the implicit conversion initially,
1198 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001199 QualType FromType = From->getType();
1200
Douglas Gregor225c41e2008-11-03 19:09:14 +00001201 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001202 // FIXME: When can ToType be a reference type?
1203 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001204 if (SCS.Second == ICK_Derived_To_Base) {
1205 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1206 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1207 MultiExprArg(*this, (void **)&From, 1),
1208 /*FIXME:ConstructLoc*/SourceLocation(),
1209 ConstructorArgs))
1210 return true;
1211 OwningExprResult FromResult =
1212 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1213 ToType, SCS.CopyConstructor,
1214 move_arg(ConstructorArgs));
1215 if (FromResult.isInvalid())
1216 return true;
1217 From = FromResult.takeAs<Expr>();
1218 return false;
1219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220 OwningExprResult FromResult =
1221 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1222 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001223 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001225 if (FromResult.isInvalid())
1226 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001228 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001229 return false;
1230 }
1231
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001232 // Perform the first implicit conversion.
1233 switch (SCS.First) {
1234 case ICK_Identity:
1235 case ICK_Lvalue_To_Rvalue:
1236 // Nothing to do.
1237 break;
1238
1239 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001240 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001241 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001242 break;
1243
1244 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001245 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001246 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1247 if (!Fn)
1248 return true;
1249
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001250 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1251 return true;
1252
Anders Carlsson96ad5332009-10-21 17:16:23 +00001253 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001254 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001255
Sebastian Redl759986e2009-10-17 20:50:27 +00001256 // If there's already an address-of operator in the expression, we have
1257 // the right type already, and the code below would just introduce an
1258 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001259 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001260 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001261 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001262 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001263 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001264 break;
1265
1266 default:
1267 assert(false && "Improper first standard conversion");
1268 break;
1269 }
1270
1271 // Perform the second implicit conversion
1272 switch (SCS.Second) {
1273 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001274 // If both sides are functions (or pointers/references to them), there could
1275 // be incompatible exception declarations.
1276 if (CheckExceptionSpecCompatibility(From, ToType))
1277 return true;
1278 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001279 break;
1280
Douglas Gregor43c79c22009-12-09 00:47:37 +00001281 case ICK_NoReturn_Adjustment:
1282 // If both sides are functions (or pointers/references to them), there could
1283 // be incompatible exception declarations.
1284 if (CheckExceptionSpecCompatibility(From, ToType))
1285 return true;
1286
1287 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1288 CastExpr::CK_NoOp);
1289 break;
1290
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001292 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001293 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1294 break;
1295
1296 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001297 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001298 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1299 break;
1300
1301 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001302 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001303 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1304 break;
1305
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001307 if (ToType->isFloatingType())
1308 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1309 else
1310 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1311 break;
1312
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001313 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001314 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1315 break;
1316
Douglas Gregorf9201e02009-02-11 23:02:49 +00001317 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001318 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001319 break;
1320
Anders Carlsson61faec12009-09-12 04:46:44 +00001321 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001322 if (SCS.IncompatibleObjC) {
1323 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001324 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001325 diag::ext_typecheck_convert_incompatible_pointer)
1326 << From->getType() << ToType << Flavor
1327 << From->getSourceRange();
1328 }
1329
Anders Carlsson61faec12009-09-12 04:46:44 +00001330
1331 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001332 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001333 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001334 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001335 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001336 }
1337
1338 case ICK_Pointer_Member: {
1339 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001340 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001341 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001342 if (CheckExceptionSpecCompatibility(From, ToType))
1343 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001344 ImpCastExprToType(From, ToType, Kind);
1345 break;
1346 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001347 case ICK_Boolean_Conversion: {
1348 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1349 if (FromType->isMemberPointerType())
1350 Kind = CastExpr::CK_MemberPointerToBoolean;
1351
1352 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001353 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001354 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001355
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001356 case ICK_Derived_To_Base:
1357 if (CheckDerivedToBaseConversion(From->getType(),
1358 ToType.getNonReferenceType(),
1359 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001360 From->getSourceRange(),
1361 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001362 return true;
1363 ImpCastExprToType(From, ToType.getNonReferenceType(),
1364 CastExpr::CK_DerivedToBase);
1365 break;
1366
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001367 default:
1368 assert(false && "Improper second standard conversion");
1369 break;
1370 }
1371
1372 switch (SCS.Third) {
1373 case ICK_Identity:
1374 // Nothing to do.
1375 break;
1376
1377 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001378 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1379 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001380 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001381 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001382 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001383 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001384
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001385 default:
1386 assert(false && "Improper second standard conversion");
1387 break;
1388 }
1389
1390 return false;
1391}
1392
Sebastian Redl64b45f72009-01-05 20:52:13 +00001393Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1394 SourceLocation KWLoc,
1395 SourceLocation LParen,
1396 TypeTy *Ty,
1397 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001398 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001400 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1401 // all traits except __is_class, __is_enum and __is_union require a the type
1402 // to be complete.
1403 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001404 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001405 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001406 return ExprError();
1407 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001408
1409 // There is no point in eagerly computing the value. The traits are designed
1410 // to be used from type trait templates, so Ty will be a template parameter
1411 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001412 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1413 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001414}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001415
1416QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001417 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001418 const char *OpSpelling = isIndirect ? "->*" : ".*";
1419 // C++ 5.5p2
1420 // The binary operator .* [p3: ->*] binds its second operand, which shall
1421 // be of type "pointer to member of T" (where T is a completely-defined
1422 // class type) [...]
1423 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001424 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001425 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001426 Diag(Loc, diag::err_bad_memptr_rhs)
1427 << OpSpelling << RType << rex->getSourceRange();
1428 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001429 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001430
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001431 QualType Class(MemPtr->getClass(), 0);
1432
1433 // C++ 5.5p2
1434 // [...] to its first operand, which shall be of class T or of a class of
1435 // which T is an unambiguous and accessible base class. [p3: a pointer to
1436 // such a class]
1437 QualType LType = lex->getType();
1438 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001439 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001440 LType = Ptr->getPointeeType().getNonReferenceType();
1441 else {
1442 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001443 << OpSpelling << 1 << LType
1444 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001445 return QualType();
1446 }
1447 }
1448
Douglas Gregora4923eb2009-11-16 21:35:15 +00001449 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001450 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1451 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001452 // FIXME: Would it be useful to print full ambiguity paths, or is that
1453 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001454 if (!IsDerivedFrom(LType, Class, Paths) ||
1455 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001456 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001457 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001458 << (int)isIndirect << lex->getType() <<
1459 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001460 return QualType();
1461 }
1462 }
1463
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001464 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001465 // Diagnose use of pointer-to-member type which when used as
1466 // the functional cast in a pointer-to-member expression.
1467 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1468 return QualType();
1469 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001470 // C++ 5.5p2
1471 // The result is an object or a function of the type specified by the
1472 // second operand.
1473 // The cv qualifiers are the union of those in the pointer and the left side,
1474 // in accordance with 5.5p5 and 5.2.5.
1475 // FIXME: This returns a dereferenced member function pointer as a normal
1476 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001477 // calling them. There's also a GCC extension to get a function pointer to the
1478 // thing, which is another complication, because this type - unlike the type
1479 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001480 // argument.
1481 // We probably need a "MemberFunctionClosureType" or something like that.
1482 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001483 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001484 return Result;
1485}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001486
1487/// \brief Get the target type of a standard or user-defined conversion.
1488static QualType TargetType(const ImplicitConversionSequence &ICS) {
1489 assert((ICS.ConversionKind ==
1490 ImplicitConversionSequence::StandardConversion ||
1491 ICS.ConversionKind ==
1492 ImplicitConversionSequence::UserDefinedConversion) &&
1493 "function only valid for standard or user-defined conversions");
1494 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1495 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1496 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1497}
1498
1499/// \brief Try to convert a type to another according to C++0x 5.16p3.
1500///
1501/// This is part of the parameter validation for the ? operator. If either
1502/// value operand is a class type, the two operands are attempted to be
1503/// converted to each other. This function does the conversion in one direction.
1504/// It emits a diagnostic and returns true only if it finds an ambiguous
1505/// conversion.
1506static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1507 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001508 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001509 // C++0x 5.16p3
1510 // The process for determining whether an operand expression E1 of type T1
1511 // can be converted to match an operand expression E2 of type T2 is defined
1512 // as follows:
1513 // -- If E2 is an lvalue:
1514 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1515 // E1 can be converted to match E2 if E1 can be implicitly converted to
1516 // type "lvalue reference to T2", subject to the constraint that in the
1517 // conversion the reference must bind directly to E1.
1518 if (!Self.CheckReferenceInit(From,
1519 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001520 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001521 /*SuppressUserConversions=*/false,
1522 /*AllowExplicit=*/false,
1523 /*ForceRValue=*/false,
1524 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001525 {
1526 assert((ICS.ConversionKind ==
1527 ImplicitConversionSequence::StandardConversion ||
1528 ICS.ConversionKind ==
1529 ImplicitConversionSequence::UserDefinedConversion) &&
1530 "expected a definite conversion");
1531 bool DirectBinding =
1532 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1533 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1534 if (DirectBinding)
1535 return false;
1536 }
1537 }
1538 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1539 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1540 // -- if E1 and E2 have class type, and the underlying class types are
1541 // the same or one is a base class of the other:
1542 QualType FTy = From->getType();
1543 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001544 const RecordType *FRec = FTy->getAs<RecordType>();
1545 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001546 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1547 if (FRec && TRec && (FRec == TRec ||
1548 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1549 // E1 can be converted to match E2 if the class of T2 is the
1550 // same type as, or a base class of, the class of T1, and
1551 // [cv2 > cv1].
1552 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1553 // Could still fail if there's no copy constructor.
1554 // FIXME: Is this a hard error then, or just a conversion failure? The
1555 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001556 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001557 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001558 /*ForceRValue=*/false,
1559 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001560 }
1561 } else {
1562 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1563 // implicitly converted to the type that expression E2 would have
1564 // if E2 were converted to an rvalue.
1565 // First find the decayed type.
1566 if (TTy->isFunctionType())
1567 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001568 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001569 TTy = Self.Context.getArrayDecayedType(TTy);
1570
1571 // Now try the implicit conversion.
1572 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001573 ICS = Self.TryImplicitConversion(From, TTy,
1574 /*SuppressUserConversions=*/false,
1575 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001576 /*ForceRValue=*/false,
1577 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001578 }
1579 return false;
1580}
1581
1582/// \brief Try to find a common type for two according to C++0x 5.16p5.
1583///
1584/// This is part of the parameter validation for the ? operator. If either
1585/// value operand is a class type, overload resolution is used to find a
1586/// conversion to a common type.
1587static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1588 SourceLocation Loc) {
1589 Expr *Args[2] = { LHS, RHS };
1590 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001591 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001592
1593 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001594 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001595 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001596 // We found a match. Perform the conversions on the arguments and move on.
1597 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1598 Best->Conversions[0], "converting") ||
1599 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1600 Best->Conversions[1], "converting"))
1601 break;
1602 return false;
1603
Douglas Gregor20093b42009-12-09 23:02:17 +00001604 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001605 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1606 << LHS->getType() << RHS->getType()
1607 << LHS->getSourceRange() << RHS->getSourceRange();
1608 return true;
1609
Douglas Gregor20093b42009-12-09 23:02:17 +00001610 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001611 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1612 << LHS->getType() << RHS->getType()
1613 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001614 // FIXME: Print the possible common types by printing the return types of
1615 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001616 break;
1617
Douglas Gregor20093b42009-12-09 23:02:17 +00001618 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001619 assert(false && "Conditional operator has only built-in overloads");
1620 break;
1621 }
1622 return true;
1623}
1624
Sebastian Redl76458502009-04-17 16:30:52 +00001625/// \brief Perform an "extended" implicit conversion as returned by
1626/// TryClassUnification.
1627///
1628/// TryClassUnification generates ICSs that include reference bindings.
1629/// PerformImplicitConversion is not suitable for this; it chokes if the
1630/// second part of a standard conversion is ICK_DerivedToBase. This function
1631/// handles the reference binding specially.
1632static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001633 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001634 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1635 ICS.Standard.ReferenceBinding) {
1636 assert(ICS.Standard.DirectBinding &&
1637 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001638 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1639 // redoing all the work.
1640 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001641 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001642 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001643 /*SuppressUserConversions=*/false,
1644 /*AllowExplicit=*/false,
1645 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001646 }
1647 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1648 ICS.UserDefined.After.ReferenceBinding) {
1649 assert(ICS.UserDefined.After.DirectBinding &&
1650 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001651 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001652 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001653 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001654 /*SuppressUserConversions=*/false,
1655 /*AllowExplicit=*/false,
1656 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001657 }
1658 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1659 return true;
1660 return false;
1661}
1662
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001663/// \brief Check the operands of ?: under C++ semantics.
1664///
1665/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1666/// extension. In this case, LHS == Cond. (But they're not aliases.)
1667QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1668 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001669 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1670 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001671
1672 // C++0x 5.16p1
1673 // The first expression is contextually converted to bool.
1674 if (!Cond->isTypeDependent()) {
1675 if (CheckCXXBooleanCondition(Cond))
1676 return QualType();
1677 }
1678
1679 // Either of the arguments dependent?
1680 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1681 return Context.DependentTy;
1682
John McCallb13c87f2009-11-05 09:23:39 +00001683 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1684
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001685 // C++0x 5.16p2
1686 // If either the second or the third operand has type (cv) void, ...
1687 QualType LTy = LHS->getType();
1688 QualType RTy = RHS->getType();
1689 bool LVoid = LTy->isVoidType();
1690 bool RVoid = RTy->isVoidType();
1691 if (LVoid || RVoid) {
1692 // ... then the [l2r] conversions are performed on the second and third
1693 // operands ...
1694 DefaultFunctionArrayConversion(LHS);
1695 DefaultFunctionArrayConversion(RHS);
1696 LTy = LHS->getType();
1697 RTy = RHS->getType();
1698
1699 // ... and one of the following shall hold:
1700 // -- The second or the third operand (but not both) is a throw-
1701 // expression; the result is of the type of the other and is an rvalue.
1702 bool LThrow = isa<CXXThrowExpr>(LHS);
1703 bool RThrow = isa<CXXThrowExpr>(RHS);
1704 if (LThrow && !RThrow)
1705 return RTy;
1706 if (RThrow && !LThrow)
1707 return LTy;
1708
1709 // -- Both the second and third operands have type void; the result is of
1710 // type void and is an rvalue.
1711 if (LVoid && RVoid)
1712 return Context.VoidTy;
1713
1714 // Neither holds, error.
1715 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1716 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1717 << LHS->getSourceRange() << RHS->getSourceRange();
1718 return QualType();
1719 }
1720
1721 // Neither is void.
1722
1723 // C++0x 5.16p3
1724 // Otherwise, if the second and third operand have different types, and
1725 // either has (cv) class type, and attempt is made to convert each of those
1726 // operands to the other.
1727 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1728 (LTy->isRecordType() || RTy->isRecordType())) {
1729 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1730 // These return true if a single direction is already ambiguous.
1731 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1732 return QualType();
1733 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1734 return QualType();
1735
1736 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1737 ImplicitConversionSequence::BadConversion;
1738 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1739 ImplicitConversionSequence::BadConversion;
1740 // If both can be converted, [...] the program is ill-formed.
1741 if (HaveL2R && HaveR2L) {
1742 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1743 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1744 return QualType();
1745 }
1746
1747 // If exactly one conversion is possible, that conversion is applied to
1748 // the chosen operand and the converted operands are used in place of the
1749 // original operands for the remainder of this section.
1750 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001751 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001752 return QualType();
1753 LTy = LHS->getType();
1754 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001755 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001756 return QualType();
1757 RTy = RHS->getType();
1758 }
1759 }
1760
1761 // C++0x 5.16p4
1762 // If the second and third operands are lvalues and have the same type,
1763 // the result is of that type [...]
1764 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1765 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1766 RHS->isLvalue(Context) == Expr::LV_Valid)
1767 return LTy;
1768
1769 // C++0x 5.16p5
1770 // Otherwise, the result is an rvalue. If the second and third operands
1771 // do not have the same type, and either has (cv) class type, ...
1772 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1773 // ... overload resolution is used to determine the conversions (if any)
1774 // to be applied to the operands. If the overload resolution fails, the
1775 // program is ill-formed.
1776 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1777 return QualType();
1778 }
1779
1780 // C++0x 5.16p6
1781 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1782 // conversions are performed on the second and third operands.
1783 DefaultFunctionArrayConversion(LHS);
1784 DefaultFunctionArrayConversion(RHS);
1785 LTy = LHS->getType();
1786 RTy = RHS->getType();
1787
1788 // After those conversions, one of the following shall hold:
1789 // -- The second and third operands have the same type; the result
1790 // is of that type.
1791 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1792 return LTy;
1793
1794 // -- The second and third operands have arithmetic or enumeration type;
1795 // the usual arithmetic conversions are performed to bring them to a
1796 // common type, and the result is of that type.
1797 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1798 UsualArithmeticConversions(LHS, RHS);
1799 return LHS->getType();
1800 }
1801
1802 // -- The second and third operands have pointer type, or one has pointer
1803 // type and the other is a null pointer constant; pointer conversions
1804 // and qualification conversions are performed to bring them to their
1805 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001806 QualType Composite = FindCompositePointerType(LHS, RHS);
1807 if (!Composite.isNull())
1808 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001809
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001810 // Fourth bullet is same for pointers-to-member. However, the possible
1811 // conversions are far more limited: we have null-to-pointer, upcast of
1812 // containing class, and second-level cv-ness.
1813 // cv-ness is not a union, but must match one of the two operands. (Which,
1814 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001815 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1816 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001817 if (LMemPtr &&
1818 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001819 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001820 return LTy;
1821 }
Douglas Gregorce940492009-09-25 04:25:58 +00001822 if (RMemPtr &&
1823 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001824 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001825 return RTy;
1826 }
1827 if (LMemPtr && RMemPtr) {
1828 QualType LPointee = LMemPtr->getPointeeType();
1829 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001830
1831 QualifierCollector LPQuals, RPQuals;
1832 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1833 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1834
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001835 // First, we check that the unqualified pointee type is the same. If it's
1836 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001837 if (LPCan == RPCan) {
1838
1839 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001840 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001841
1842 Qualifiers MergedQuals = LPQuals + RPQuals;
1843
1844 bool CompatibleQuals = true;
1845 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1846 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1847 CompatibleQuals = false;
1848 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1849 // FIXME:
1850 // C99 6.5.15 as modified by TR 18037:
1851 // If the second and third operands are pointers into different
1852 // address spaces, the address spaces must overlap.
1853 CompatibleQuals = false;
1854 // FIXME: GC qualifiers?
1855
1856 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001857 // Third, we check if either of the container classes is derived from
1858 // the other.
1859 QualType LContainer(LMemPtr->getClass(), 0);
1860 QualType RContainer(RMemPtr->getClass(), 0);
1861 QualType MoreDerived;
1862 if (Context.getCanonicalType(LContainer) ==
1863 Context.getCanonicalType(RContainer))
1864 MoreDerived = LContainer;
1865 else if (IsDerivedFrom(LContainer, RContainer))
1866 MoreDerived = LContainer;
1867 else if (IsDerivedFrom(RContainer, LContainer))
1868 MoreDerived = RContainer;
1869
1870 if (!MoreDerived.isNull()) {
1871 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1872 // We don't use ImpCastExprToType here because this could still fail
1873 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001874 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1875 QualType Common
1876 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001877 if (PerformImplicitConversion(LHS, Common, "converting"))
1878 return QualType();
1879 if (PerformImplicitConversion(RHS, Common, "converting"))
1880 return QualType();
1881 return Common;
1882 }
1883 }
1884 }
1885 }
1886
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001887 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1888 << LHS->getType() << RHS->getType()
1889 << LHS->getSourceRange() << RHS->getSourceRange();
1890 return QualType();
1891}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001892
1893/// \brief Find a merged pointer type and convert the two expressions to it.
1894///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001895/// This finds the composite pointer type (or member pointer type) for @p E1
1896/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1897/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001898/// It does not emit diagnostics.
1899QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1900 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1901 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001903 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1904 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001905 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001906
1907 // C++0x 5.9p2
1908 // Pointer conversions and qualification conversions are performed on
1909 // pointer operands to bring them to their composite pointer type. If
1910 // one operand is a null pointer constant, the composite pointer type is
1911 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001912 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001913 if (T2->isMemberPointerType())
1914 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1915 else
1916 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001917 return T2;
1918 }
Douglas Gregorce940492009-09-25 04:25:58 +00001919 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001920 if (T1->isMemberPointerType())
1921 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1922 else
1923 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001924 return T1;
1925 }
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Douglas Gregor20b3e992009-08-24 17:42:35 +00001927 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001928 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1929 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001930 return QualType();
1931
1932 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1933 // the other has type "pointer to cv2 T" and the composite pointer type is
1934 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1935 // Otherwise, the composite pointer type is a pointer type similar to the
1936 // type of one of the operands, with a cv-qualification signature that is
1937 // the union of the cv-qualification signatures of the operand types.
1938 // In practice, the first part here is redundant; it's subsumed by the second.
1939 // What we do here is, we build the two possible composite types, and try the
1940 // conversions in both directions. If only one works, or if the two composite
1941 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001942 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001943 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1944 QualifierVector QualifierUnion;
1945 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1946 ContainingClassVector;
1947 ContainingClassVector MemberOfClass;
1948 QualType Composite1 = Context.getCanonicalType(T1),
1949 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001950 do {
1951 const PointerType *Ptr1, *Ptr2;
1952 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1953 (Ptr2 = Composite2->getAs<PointerType>())) {
1954 Composite1 = Ptr1->getPointeeType();
1955 Composite2 = Ptr2->getPointeeType();
1956 QualifierUnion.push_back(
1957 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1958 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1959 continue;
1960 }
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Douglas Gregor20b3e992009-08-24 17:42:35 +00001962 const MemberPointerType *MemPtr1, *MemPtr2;
1963 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1964 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1965 Composite1 = MemPtr1->getPointeeType();
1966 Composite2 = MemPtr2->getPointeeType();
1967 QualifierUnion.push_back(
1968 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1969 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1970 MemPtr2->getClass()));
1971 continue;
1972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Douglas Gregor20b3e992009-08-24 17:42:35 +00001974 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregor20b3e992009-08-24 17:42:35 +00001976 // Cannot unwrap any more types.
1977 break;
1978 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregor20b3e992009-08-24 17:42:35 +00001980 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001981 ContainingClassVector::reverse_iterator MOC
1982 = MemberOfClass.rbegin();
1983 for (QualifierVector::reverse_iterator
1984 I = QualifierUnion.rbegin(),
1985 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001986 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001987 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001988 if (MOC->first && MOC->second) {
1989 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001990 Composite1 = Context.getMemberPointerType(
1991 Context.getQualifiedType(Composite1, Quals),
1992 MOC->first);
1993 Composite2 = Context.getMemberPointerType(
1994 Context.getQualifiedType(Composite2, Quals),
1995 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001996 } else {
1997 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001998 Composite1
1999 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2000 Composite2
2001 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002002 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002003 }
2004
Mike Stump1eb44332009-09-09 15:08:12 +00002005 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002006 TryImplicitConversion(E1, Composite1,
2007 /*SuppressUserConversions=*/false,
2008 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002009 /*ForceRValue=*/false,
2010 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002011 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002012 TryImplicitConversion(E2, Composite1,
2013 /*SuppressUserConversions=*/false,
2014 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002015 /*ForceRValue=*/false,
2016 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002018 ImplicitConversionSequence E1ToC2, E2ToC2;
2019 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2020 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2021 if (Context.getCanonicalType(Composite1) !=
2022 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002023 E1ToC2 = TryImplicitConversion(E1, Composite2,
2024 /*SuppressUserConversions=*/false,
2025 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002026 /*ForceRValue=*/false,
2027 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002028 E2ToC2 = TryImplicitConversion(E2, Composite2,
2029 /*SuppressUserConversions=*/false,
2030 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002031 /*ForceRValue=*/false,
2032 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002033 }
2034
2035 bool ToC1Viable = E1ToC1.ConversionKind !=
2036 ImplicitConversionSequence::BadConversion
2037 && E2ToC1.ConversionKind !=
2038 ImplicitConversionSequence::BadConversion;
2039 bool ToC2Viable = E1ToC2.ConversionKind !=
2040 ImplicitConversionSequence::BadConversion
2041 && E2ToC2.ConversionKind !=
2042 ImplicitConversionSequence::BadConversion;
2043 if (ToC1Viable && !ToC2Viable) {
2044 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2045 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2046 return Composite1;
2047 }
2048 if (ToC2Viable && !ToC1Viable) {
2049 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2050 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2051 return Composite2;
2052 }
2053 return QualType();
2054}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002055
Anders Carlssondef11992009-05-30 20:36:53 +00002056Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002057 if (!Context.getLangOptions().CPlusPlus)
2058 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenek6217b802009-07-29 21:53:49 +00002060 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002061 if (!RT)
2062 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Anders Carlssondef11992009-05-30 20:36:53 +00002064 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2065 if (RD->hasTrivialDestructor())
2066 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Anders Carlsson283e4d52009-09-14 01:30:44 +00002068 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2069 QualType Ty = CE->getCallee()->getType();
2070 if (const PointerType *PT = Ty->getAs<PointerType>())
2071 Ty = PT->getPointeeType();
2072
John McCall183700f2009-09-21 23:43:11 +00002073 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002074 if (FTy->getResultType()->isReferenceType())
2075 return Owned(E);
2076 }
Mike Stump1eb44332009-09-09 15:08:12 +00002077 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002078 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002079 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002080 if (CXXDestructorDecl *Destructor =
2081 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2082 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002083 // FIXME: Add the temporary to the temporaries vector.
2084 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2085}
2086
Mike Stump1eb44332009-09-09 15:08:12 +00002087Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002088 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002089 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002091 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2092 assert(ExprTemporaries.size() >= FirstTemporary);
2093 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002094 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002096 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002097 &ExprTemporaries[FirstTemporary],
2098 ExprTemporaries.size() - FirstTemporary,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002099 ShouldDestroyTemps);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002100 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2101 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002103 return E;
2104}
2105
Mike Stump1eb44332009-09-09 15:08:12 +00002106Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002107Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2108 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2109 // Since this might be a postfix expression, get rid of ParenListExprs.
2110 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002112 Expr *BaseExpr = (Expr*)Base.get();
2113 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002115 QualType BaseType = BaseExpr->getType();
2116 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002117 // If we have a pointer to a dependent type and are using the -> operator,
2118 // the object type is the type that the pointer points to. We might still
2119 // have enough information about that type to do something useful.
2120 if (OpKind == tok::arrow)
2121 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2122 BaseType = Ptr->getPointeeType();
2123
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002124 ObjectType = BaseType.getAsOpaquePtr();
2125 return move(Base);
2126 }
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002128 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002129 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002130 // returned, with the original second operand.
2131 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002132 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002133 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002134 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002135 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002136
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002137 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002138 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002139 BaseExpr = (Expr*)Base.get();
2140 if (BaseExpr == NULL)
2141 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002142 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002143 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002144 BaseType = BaseExpr->getType();
2145 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002146 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002147 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002148 for (unsigned i = 0; i < Locations.size(); i++)
2149 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002150 return ExprError();
2151 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002152 }
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Douglas Gregor31658df2009-11-20 19:58:21 +00002154 if (BaseType->isPointerType())
2155 BaseType = BaseType->getPointeeType();
2156 }
Mike Stump1eb44332009-09-09 15:08:12 +00002157
2158 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002159 // vector types or Objective-C interfaces. Just return early and let
2160 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002161 if (!BaseType->isRecordType()) {
2162 // C++ [basic.lookup.classref]p2:
2163 // [...] If the type of the object expression is of pointer to scalar
2164 // type, the unqualified-id is looked up in the context of the complete
2165 // postfix-expression.
2166 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002167 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002168 }
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Douglas Gregor03c57052009-11-17 05:17:33 +00002170 // The object type must be complete (or dependent).
2171 if (!BaseType->isDependentType() &&
2172 RequireCompleteType(OpLoc, BaseType,
2173 PDiag(diag::err_incomplete_member_access)))
2174 return ExprError();
2175
Douglas Gregorc68afe22009-09-03 21:38:09 +00002176 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002177 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002178 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002179 // type C (or of pointer to a class type C), the unqualified-id is looked
2180 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002181 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002182
Mike Stump1eb44332009-09-09 15:08:12 +00002183 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002184}
2185
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002186CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2187 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002188 if (PerformObjectArgumentInitialization(Exp, Method))
2189 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2190
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002191 MemberExpr *ME =
2192 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2193 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002194 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002195 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2196 CXXMemberCallExpr *CE =
2197 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2198 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002199 return CE;
2200}
2201
Anders Carlsson0aebc812009-09-09 21:33:21 +00002202Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2203 QualType Ty,
2204 CastExpr::CastKind Kind,
2205 CXXMethodDecl *Method,
2206 ExprArg Arg) {
2207 Expr *From = Arg.takeAs<Expr>();
2208
2209 switch (Kind) {
2210 default: assert(0 && "Unhandled cast kind!");
2211 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002212 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2213
2214 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2215 MultiExprArg(*this, (void **)&From, 1),
2216 CastLoc, ConstructorArgs))
2217 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002218
2219 OwningExprResult Result =
2220 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2221 move_arg(ConstructorArgs));
2222 if (Result.isInvalid())
2223 return ExprError();
2224
2225 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002226 }
2227
2228 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002229 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002230
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002231 // Create an implicit call expr that calls it.
2232 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002233 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002234 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002235 }
2236}
2237
Anders Carlsson165a0a02009-05-17 18:41:29 +00002238Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2239 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002240 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002241 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002242 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002243
Anders Carlssonec773872009-08-25 23:46:41 +00002244
Anders Carlsson165a0a02009-05-17 18:41:29 +00002245 return Owned(FullExpr);
2246}
Douglas Gregore961afb2009-10-22 07:08:30 +00002247
2248/// \brief Determine whether a reference to the given declaration in the
2249/// current context is an implicit member access
2250/// (C++ [class.mfct.non-static]p2).
2251///
2252/// FIXME: Should Objective-C also use this approach?
2253///
Douglas Gregore961afb2009-10-22 07:08:30 +00002254/// \param D the declaration being referenced from the current scope.
2255///
2256/// \param NameLoc the location of the name in the source.
2257///
2258/// \param ThisType if the reference to this declaration is an implicit member
2259/// access, will be set to the type of the "this" pointer to be used when
2260/// building that implicit member access.
2261///
Douglas Gregore961afb2009-10-22 07:08:30 +00002262/// \returns true if this is an implicit member reference (in which case
2263/// \p ThisType and \p MemberType will be set), or false if it is not an
2264/// implicit member reference.
John McCall129e2df2009-11-30 22:42:35 +00002265bool Sema::isImplicitMemberReference(const LookupResult &R,
2266 QualType &ThisType) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002267 // If this isn't a C++ method, then it isn't an implicit member reference.
2268 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2269 if (!MD || MD->isStatic())
2270 return false;
2271
2272 // C++ [class.mfct.nonstatic]p2:
2273 // [...] if name lookup (3.4.1) resolves the name in the
2274 // id-expression to a nonstatic nontype member of class X or of
2275 // a base class of X, the id-expression is transformed into a
2276 // class member access expression (5.2.5) using (*this) (9.3.2)
2277 // as the postfix-expression to the left of the '.' operator.
2278 DeclContext *Ctx = 0;
John McCall129e2df2009-11-30 22:42:35 +00002279 if (R.isUnresolvableResult()) {
2280 // FIXME: this is just picking one at random
2281 Ctx = R.getRepresentativeDecl()->getDeclContext();
2282 } else if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002283 Ctx = FD->getDeclContext();
Douglas Gregore961afb2009-10-22 07:08:30 +00002284 } else {
John McCall129e2df2009-11-30 22:42:35 +00002285 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2286 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I);
Douglas Gregore961afb2009-10-22 07:08:30 +00002287 FunctionTemplateDecl *FunTmpl = 0;
John McCall129e2df2009-11-30 22:42:35 +00002288 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*I)))
Douglas Gregore961afb2009-10-22 07:08:30 +00002289 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2290
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002291 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002292 if (Method && !Method->isStatic()) {
2293 Ctx = Method->getParent();
Douglas Gregore961afb2009-10-22 07:08:30 +00002294 break;
2295 }
2296 }
2297 }
2298
2299 if (!Ctx || !Ctx->isRecord())
2300 return false;
2301
2302 // Determine whether the declaration(s) we found are actually in a base
2303 // class. If not, this isn't an implicit member reference.
2304 ThisType = MD->getThisType(Context);
John McCall129e2df2009-11-30 22:42:35 +00002305
2306 // FIXME: this doesn't really work for overloaded lookups.
Douglas Gregor7a343142009-11-01 17:08:18 +00002307
Douglas Gregore961afb2009-10-22 07:08:30 +00002308 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2309 QualType ClassType
2310 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2311 return Context.hasSameType(CtxType, ClassType) ||
2312 IsDerivedFrom(ClassType, CtxType);
2313}
2314