blob: dd3d2ea2ce4f2238a137446a735df88c67ed3ea6 [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 ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000428 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
430 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000431 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
432
Douglas Gregor99a2e602009-12-16 01:38:02 +0000433 if (!AllocType->isDependentType() &&
434 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
435 // C++0x [expr.new]p15:
436 // A new-expression that creates an object of type T initializes that
437 // object as follows:
438 InitializationKind Kind
439 // - If the new-initializer is omitted, the object is default-
440 // initialized (8.5); if no initialization is performed,
441 // the object has indeterminate value
442 = !Init? InitializationKind::CreateDefault(TypeLoc)
443 // - Otherwise, the new-initializer is interpreted according to the
444 // initialization rules of 8.5 for direct-initialization.
445 : InitializationKind::CreateDirect(TypeLoc,
446 ConstructorLParen,
447 ConstructorRParen);
448
Douglas Gregor99a2e602009-12-16 01:38:02 +0000449 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000450 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000451 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000452 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
453 move(ConstructorArgs));
454 if (FullInit.isInvalid())
455 return ExprError();
456
457 // FullInit is our initializer; walk through it to determine if it's a
458 // constructor call, which CXXNewExpr handles directly.
459 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
460 if (CXXBindTemporaryExpr *Binder
461 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
462 FullInitExpr = Binder->getSubExpr();
463 if (CXXConstructExpr *Construct
464 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
465 Constructor = Construct->getConstructor();
466 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
467 AEnd = Construct->arg_end();
468 A != AEnd; ++A)
469 ConvertedConstructorArgs.push_back(A->Retain());
470 } else {
471 // Take the converted initializer.
472 ConvertedConstructorArgs.push_back(FullInit.release());
473 }
474 } else {
475 // No initialization required.
476 }
477
478 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000479 NumConsArgs = ConvertedConstructorArgs.size();
480 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000481 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000482
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000483 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000484
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485 PlacementArgs.release();
486 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000487 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000488 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000489 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000490 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000491 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000492}
493
494/// CheckAllocatedType - Checks that a type is suitable as the allocated type
495/// in a new-expression.
496/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000497bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000498 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000499 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
500 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000501 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000502 return Diag(Loc, diag::err_bad_new_type)
503 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000504 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000505 return Diag(Loc, diag::err_bad_new_type)
506 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000507 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000508 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000509 PDiag(diag::err_new_incomplete_type)
510 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000511 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000512 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000513 diag::err_allocation_of_abstract_type))
514 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000515
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000516 return false;
517}
518
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000519/// FindAllocationFunctions - Finds the overloads of operator new and delete
520/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000521bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
522 bool UseGlobal, QualType AllocType,
523 bool IsArray, Expr **PlaceArgs,
524 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000525 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000526 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000527 // --- Choosing an allocation function ---
528 // C++ 5.3.4p8 - 14 & 18
529 // 1) If UseGlobal is true, only look in the global scope. Else, also look
530 // in the scope of the allocated class.
531 // 2) If an array size is given, look for operator new[], else look for
532 // operator new.
533 // 3) The first argument is always size_t. Append the arguments from the
534 // placement form.
535 // FIXME: Also find the appropriate delete operator.
536
537 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
538 // We don't care about the actual value of this argument.
539 // FIXME: Should the Sema create the expression and embed it in the syntax
540 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000541 IntegerLiteral Size(llvm::APInt::getNullValue(
542 Context.Target.getPointerWidth(0)),
543 Context.getSizeType(),
544 SourceLocation());
545 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000546 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
547
548 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
549 IsArray ? OO_Array_New : OO_New);
550 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000551 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000552 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000553 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000554 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000555 AllocArgs.size(), Record, /*AllowMissing=*/true,
556 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000557 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000558 }
559 if (!OperatorNew) {
560 // Didn't find a member overload. Look for a global one.
561 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000562 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000563 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000564 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
565 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000566 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000567 }
568
Anders Carlssond9583892009-05-31 20:26:12 +0000569 // FindAllocationOverload can change the passed in arguments, so we need to
570 // copy them back.
571 if (NumPlaceArgs > 0)
572 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000574 return false;
575}
576
Sebastian Redl7f662392008-12-04 22:20:51 +0000577/// FindAllocationOverload - Find an fitting overload for the allocation
578/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000579bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
580 DeclarationName Name, Expr** Args,
581 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000582 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000583 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
584 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000585 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000586 if (AllowMissing)
587 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000588 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000589 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000590 }
591
John McCallf36e02d2009-10-09 21:13:30 +0000592 // FIXME: handle ambiguity
593
Sebastian Redl7f662392008-12-04 22:20:51 +0000594 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000595 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
596 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000597 // Even member operator new/delete are implicitly treated as
598 // static, so don't use AddMemberCandidate.
Anders Carlssoneac81392009-12-09 07:39:44 +0000599 if (FunctionDecl *Fn =
600 dyn_cast<FunctionDecl>((*Alloc)->getUnderlyingDecl())) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000601 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
602 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000603 continue;
604 }
605
606 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000607 }
608
609 // Do the resolution.
610 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000611 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000612 case OR_Success: {
613 // Got one!
614 FunctionDecl *FnDecl = Best->Function;
615 // The first argument is size_t, and the first parameter must be size_t,
616 // too. This is checked on declaration and can be assumed. (It can't be
617 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000618 // Whatch out for variadic allocator function.
619 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
620 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000621 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000623 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000624 return true;
625 }
626 Operator = FnDecl;
627 return false;
628 }
629
630 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000631 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000632 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000633 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
634 return true;
635
636 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000637 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000638 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000639 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
640 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000641
642 case OR_Deleted:
643 Diag(StartLoc, diag::err_ovl_deleted_call)
644 << Best->Function->isDeleted()
645 << Name << Range;
646 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
647 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000648 }
649 assert(false && "Unreachable, bad result from BestViableFunction");
650 return true;
651}
652
653
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000654/// DeclareGlobalNewDelete - Declare the global forms of operator new and
655/// delete. These are:
656/// @code
657/// void* operator new(std::size_t) throw(std::bad_alloc);
658/// void* operator new[](std::size_t) throw(std::bad_alloc);
659/// void operator delete(void *) throw();
660/// void operator delete[](void *) throw();
661/// @endcode
662/// Note that the placement and nothrow forms of new are *not* implicitly
663/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000664void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000665 if (GlobalNewDeleteDeclared)
666 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000667
668 // C++ [basic.std.dynamic]p2:
669 // [...] The following allocation and deallocation functions (18.4) are
670 // implicitly declared in global scope in each translation unit of a
671 // program
672 //
673 // void* operator new(std::size_t) throw(std::bad_alloc);
674 // void* operator new[](std::size_t) throw(std::bad_alloc);
675 // void operator delete(void*) throw();
676 // void operator delete[](void*) throw();
677 //
678 // These implicit declarations introduce only the function names operator
679 // new, operator new[], operator delete, operator delete[].
680 //
681 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
682 // "std" or "bad_alloc" as necessary to form the exception specification.
683 // However, we do not make these implicit declarations visible to name
684 // lookup.
685 if (!StdNamespace) {
686 // The "std" namespace has not yet been defined, so build one implicitly.
687 StdNamespace = NamespaceDecl::Create(Context,
688 Context.getTranslationUnitDecl(),
689 SourceLocation(),
690 &PP.getIdentifierTable().get("std"));
691 StdNamespace->setImplicit(true);
692 }
693
694 if (!StdBadAlloc) {
695 // The "std::bad_alloc" class has not yet been declared, so build it
696 // implicitly.
697 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
698 StdNamespace,
699 SourceLocation(),
700 &PP.getIdentifierTable().get("bad_alloc"),
701 SourceLocation(), 0);
702 StdBadAlloc->setImplicit(true);
703 }
704
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000705 GlobalNewDeleteDeclared = true;
706
707 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
708 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000709 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000710
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000711 DeclareGlobalAllocationFunction(
712 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000713 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000714 DeclareGlobalAllocationFunction(
715 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000716 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000717 DeclareGlobalAllocationFunction(
718 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
719 Context.VoidTy, VoidPtr);
720 DeclareGlobalAllocationFunction(
721 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
722 Context.VoidTy, VoidPtr);
723}
724
725/// DeclareGlobalAllocationFunction - Declares a single implicit global
726/// allocation function if it doesn't already exist.
727void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000728 QualType Return, QualType Argument,
729 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000730 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
731
732 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000733 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000734 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000735 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000736 Alloc != AllocEnd; ++Alloc) {
737 // FIXME: Do we need to check for default arguments here?
738 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
739 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000740 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000741 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000742 }
743 }
744
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000745 QualType BadAllocType;
746 bool HasBadAllocExceptionSpec
747 = (Name.getCXXOverloadedOperator() == OO_New ||
748 Name.getCXXOverloadedOperator() == OO_Array_New);
749 if (HasBadAllocExceptionSpec) {
750 assert(StdBadAlloc && "Must have std::bad_alloc declared");
751 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
752 }
753
754 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
755 true, false,
756 HasBadAllocExceptionSpec? 1 : 0,
757 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000758 FunctionDecl *Alloc =
759 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +0000760 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000761 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +0000762
763 if (AddMallocAttr)
764 Alloc->addAttr(::new (Context) MallocAttr());
765
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000766 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +0000767 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000768 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000769 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000770
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000771 // FIXME: Also add this declaration to the IdentifierResolver, but
772 // make sure it is at the end of the chain to coincide with the
773 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000774 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000775}
776
Anders Carlsson78f74552009-11-15 18:45:20 +0000777bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
778 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +0000779 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000780 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000781 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000782 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000783
John McCalla24dc2e2009-11-17 02:14:36 +0000784 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000785 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000786
787 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
788 F != FEnd; ++F) {
789 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
790 if (Delete->isUsualDeallocationFunction()) {
791 Operator = Delete;
792 return false;
793 }
794 }
795
796 // We did find operator delete/operator delete[] declarations, but
797 // none of them were suitable.
798 if (!Found.empty()) {
799 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
800 << Name << RD;
801
802 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
803 F != FEnd; ++F) {
804 Diag((*F)->getLocation(),
805 diag::note_delete_member_function_declared_here)
806 << Name;
807 }
808
809 return true;
810 }
811
812 // Look for a global declaration.
813 DeclareGlobalNewDelete();
814 DeclContext *TUDecl = Context.getTranslationUnitDecl();
815
816 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
817 Expr* DeallocArgs[1];
818 DeallocArgs[0] = &Null;
819 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
820 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
821 Operator))
822 return true;
823
824 assert(Operator && "Did not find a deallocation function!");
825 return false;
826}
827
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000828/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
829/// @code ::delete ptr; @endcode
830/// or
831/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000832Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000833Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000834 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000835 // C++ [expr.delete]p1:
836 // The operand shall have a pointer type, or a class type having a single
837 // conversion function to a pointer type. The result has type void.
838 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000839 // DR599 amends "pointer type" to "pointer to object type" in both cases.
840
Anders Carlssond67c4c32009-08-16 20:29:29 +0000841 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Sebastian Redlf53597f2009-03-15 17:47:39 +0000843 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000844 if (!Ex->isTypeDependent()) {
845 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000846
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000847 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000848 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000849 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallba135432009-11-21 08:51:07 +0000850 const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000851
John McCallba135432009-11-21 08:51:07 +0000852 for (UnresolvedSet::iterator I = Conversions->begin(),
853 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000854 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +0000855 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000856 continue;
857
John McCallba135432009-11-21 08:51:07 +0000858 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000859
860 QualType ConvType = Conv->getConversionType().getNonReferenceType();
861 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
862 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000863 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000864 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000865 if (ObjectPtrConversions.size() == 1) {
866 // We have a single conversion to a pointer-to-object type. Perform
867 // that conversion.
868 Operand.release();
869 if (!PerformImplicitConversion(Ex,
870 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000871 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000872 Operand = Owned(Ex);
873 Type = Ex->getType();
874 }
875 }
876 else if (ObjectPtrConversions.size() > 1) {
877 Diag(StartLoc, diag::err_ambiguous_delete_operand)
878 << Type << Ex->getSourceRange();
879 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
880 CXXConversionDecl *Conv = ObjectPtrConversions[i];
881 Diag(Conv->getLocation(), diag::err_ovl_candidate);
882 }
883 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000884 }
Sebastian Redl28507842009-02-26 14:39:58 +0000885 }
886
Sebastian Redlf53597f2009-03-15 17:47:39 +0000887 if (!Type->isPointerType())
888 return ExprError(Diag(StartLoc, diag::err_delete_operand)
889 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000890
Ted Kremenek6217b802009-07-29 21:53:49 +0000891 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000892 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000893 return ExprError(Diag(StartLoc, diag::err_delete_operand)
894 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000895 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000896 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000897 PDiag(diag::warn_delete_incomplete)
898 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000899 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000900
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000901 // C++ [expr.delete]p2:
902 // [Note: a pointer to a const type can be the operand of a
903 // delete-expression; it is not necessary to cast away the constness
904 // (5.2.11) of the pointer expression before it is used as the operand
905 // of the delete-expression. ]
906 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
907 CastExpr::CK_NoOp);
908
909 // Update the operand.
910 Operand.take();
911 Operand = ExprArg(*this, Ex);
912
Anders Carlssond67c4c32009-08-16 20:29:29 +0000913 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
914 ArrayForm ? OO_Array_Delete : OO_Delete);
915
Anders Carlsson78f74552009-11-15 18:45:20 +0000916 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
917 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
918
919 if (!UseGlobal &&
920 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000921 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000922
Anders Carlsson78f74552009-11-15 18:45:20 +0000923 if (!RD->hasTrivialDestructor())
924 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000925 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000926 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000927 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000928
Anders Carlssond67c4c32009-08-16 20:29:29 +0000929 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000930 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000931 DeclareGlobalNewDelete();
932 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000933 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000934 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000935 OperatorDelete))
936 return ExprError();
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Sebastian Redl28507842009-02-26 14:39:58 +0000939 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000940 }
941
Sebastian Redlf53597f2009-03-15 17:47:39 +0000942 Operand.release();
943 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000944 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000945}
946
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000947/// \brief Check the use of the given variable as a C++ condition in an if,
948/// while, do-while, or switch statement.
949Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
950 QualType T = ConditionVar->getType();
951
952 // C++ [stmt.select]p2:
953 // The declarator shall not specify a function or an array.
954 if (T->isFunctionType())
955 return ExprError(Diag(ConditionVar->getLocation(),
956 diag::err_invalid_use_of_function_type)
957 << ConditionVar->getSourceRange());
958 else if (T->isArrayType())
959 return ExprError(Diag(ConditionVar->getLocation(),
960 diag::err_invalid_use_of_array_type)
961 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +0000962
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000963 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
964 ConditionVar->getLocation(),
965 ConditionVar->getType().getNonReferenceType()));
966}
967
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000968/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
969bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
970 // C++ 6.4p4:
971 // The value of a condition that is an initialized declaration in a statement
972 // other than a switch statement is the value of the declared variable
973 // implicitly converted to type bool. If that conversion is ill-formed, the
974 // program is ill-formed.
975 // The value of a condition that is an expression is the value of the
976 // expression, implicitly converted to bool.
977 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000978 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000979}
Douglas Gregor77a52232008-09-12 00:47:35 +0000980
981/// Helper function to determine whether this is the (deprecated) C++
982/// conversion from a string literal to a pointer to non-const char or
983/// non-const wchar_t (for narrow and wide string literals,
984/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +0000985bool
Douglas Gregor77a52232008-09-12 00:47:35 +0000986Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
987 // Look inside the implicit cast, if it exists.
988 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
989 From = Cast->getSubExpr();
990
991 // A string literal (2.13.4) that is not a wide string literal can
992 // be converted to an rvalue of type "pointer to char"; a wide
993 // string literal can be converted to an rvalue of type "pointer
994 // to wchar_t" (C++ 4.2p2).
995 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +0000996 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +0000997 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +0000998 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +0000999 // This conversion is considered only when there is an
1000 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001001 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001002 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1003 (!StrLit->isWide() &&
1004 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1005 ToPointeeType->getKind() == BuiltinType::Char_S))))
1006 return true;
1007 }
1008
1009 return false;
1010}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001011
1012/// PerformImplicitConversion - Perform an implicit conversion of the
1013/// expression From to the type ToType. Returns true if there was an
1014/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001015/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001016/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001017/// explicit user-defined conversions are permitted. @p Elidable should be true
1018/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1019/// resolution works differently in that case.
1020bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001021Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001022 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001023 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001024 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001025 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001026 Elidable, ICS);
1027}
1028
1029bool
1030Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001031 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001032 bool Elidable,
1033 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001034 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1035 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001036 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001037 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001038 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001039 /*ForceRValue=*/true,
1040 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001041 }
1042 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001043 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001044 /*SuppressUserConversions=*/false,
1045 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001046 /*ForceRValue=*/false,
1047 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001048 }
Douglas Gregor68647482009-12-16 03:45:30 +00001049 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001050}
1051
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001052/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1053/// for the derived to base conversion of the expression 'From'. All
1054/// necessary information is passed in ICS.
1055bool
1056Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
Douglas Gregor68647482009-12-16 03:45:30 +00001057 const ImplicitConversionSequence& ICS) {
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001058 QualType BaseType =
1059 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1060 // Must do additional defined to base conversion.
1061 QualType DerivedType =
1062 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1063
1064 From = new (Context) ImplicitCastExpr(
1065 DerivedType.getNonReferenceType(),
1066 CastKind,
1067 From,
1068 DerivedType->isLValueReferenceType());
1069 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1070 CastExpr::CK_DerivedToBase, From,
1071 BaseType->isLValueReferenceType());
1072 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1073 OwningExprResult FromResult =
1074 BuildCXXConstructExpr(
1075 ICS.UserDefined.After.CopyConstructor->getLocation(),
1076 BaseType,
1077 ICS.UserDefined.After.CopyConstructor,
1078 MultiExprArg(*this, (void **)&From, 1));
1079 if (FromResult.isInvalid())
1080 return true;
1081 From = FromResult.takeAs<Expr>();
1082 return false;
1083}
1084
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001085/// PerformImplicitConversion - Perform an implicit conversion of the
1086/// expression From to the type ToType using the pre-computed implicit
1087/// conversion sequence ICS. Returns true if there was an error, false
1088/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001089/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001090/// used in the error message.
1091bool
1092Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1093 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001094 AssignmentAction Action, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001095 switch (ICS.ConversionKind) {
1096 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001097 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001098 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001099 return true;
1100 break;
1101
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001102 case ImplicitConversionSequence::UserDefinedConversion: {
1103
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001104 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1105 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001106 QualType BeforeToType;
1107 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001108 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001109
1110 // If the user-defined conversion is specified by a conversion function,
1111 // the initial standard conversion sequence converts the source type to
1112 // the implicit object parameter of the conversion function.
1113 BeforeToType = Context.getTagDeclType(Conv->getParent());
1114 } else if (const CXXConstructorDecl *Ctor =
1115 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001116 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001117 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001118 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001119 // If the user-defined conversion is specified by a constructor, the
1120 // initial standard conversion sequence converts the source type to the
1121 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001122 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1123 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001124 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001125 else
1126 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001127 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001128 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001129 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001130 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001131 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001132 return true;
1133 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001134
Anders Carlsson0aebc812009-09-09 21:33:21 +00001135 OwningExprResult CastArg
1136 = BuildCXXCastArgument(From->getLocStart(),
1137 ToType.getNonReferenceType(),
1138 CastKind, cast<CXXMethodDecl>(FD),
1139 Owned(From));
1140
1141 if (CastArg.isInvalid())
1142 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001143
1144 From = CastArg.takeAs<Expr>();
1145
1146 // FIXME: This and the following if statement shouldn't be necessary, but
1147 // there's some nasty stuff involving MaybeBindToTemporary going on here.
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001148 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1149 ICS.UserDefined.After.CopyConstructor) {
Douglas Gregor68647482009-12-16 03:45:30 +00001150 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001151 }
Eli Friedmand8889622009-11-27 04:41:50 +00001152
1153 if (ICS.UserDefined.After.CopyConstructor) {
1154 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1155 CastKind, From,
1156 ToType->isLValueReferenceType());
1157 return false;
1158 }
1159
1160 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001161 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001162 }
1163
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001164 case ImplicitConversionSequence::EllipsisConversion:
1165 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001166 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001167
1168 case ImplicitConversionSequence::BadConversion:
1169 return true;
1170 }
1171
1172 // Everything went well.
1173 return false;
1174}
1175
1176/// PerformImplicitConversion - Perform an implicit conversion of the
1177/// expression From to the type ToType by following the standard
1178/// conversion sequence SCS. Returns true if there was an error, false
1179/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001180/// expression. Flavor is the context in which we're performing this
1181/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001182bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001183Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001184 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001185 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001186 // Overall FIXME: we are recomputing too many types here and doing far too
1187 // much extra work. What this means is that we need to keep track of more
1188 // information that is computed when we try the implicit conversion initially,
1189 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001190 QualType FromType = From->getType();
1191
Douglas Gregor225c41e2008-11-03 19:09:14 +00001192 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001193 // FIXME: When can ToType be a reference type?
1194 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001195 if (SCS.Second == ICK_Derived_To_Base) {
1196 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1197 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1198 MultiExprArg(*this, (void **)&From, 1),
1199 /*FIXME:ConstructLoc*/SourceLocation(),
1200 ConstructorArgs))
1201 return true;
1202 OwningExprResult FromResult =
1203 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1204 ToType, SCS.CopyConstructor,
1205 move_arg(ConstructorArgs));
1206 if (FromResult.isInvalid())
1207 return true;
1208 From = FromResult.takeAs<Expr>();
1209 return false;
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211 OwningExprResult FromResult =
1212 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1213 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001214 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001216 if (FromResult.isInvalid())
1217 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001219 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001220 return false;
1221 }
1222
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001223 // Perform the first implicit conversion.
1224 switch (SCS.First) {
1225 case ICK_Identity:
1226 case ICK_Lvalue_To_Rvalue:
1227 // Nothing to do.
1228 break;
1229
1230 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001231 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001232 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001233 break;
1234
1235 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001236 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001237 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1238 if (!Fn)
1239 return true;
1240
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001241 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1242 return true;
1243
Anders Carlsson96ad5332009-10-21 17:16:23 +00001244 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001245 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001246
Sebastian Redl759986e2009-10-17 20:50:27 +00001247 // If there's already an address-of operator in the expression, we have
1248 // the right type already, and the code below would just introduce an
1249 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001250 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001251 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001252 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001253 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001254 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001255 break;
1256
1257 default:
1258 assert(false && "Improper first standard conversion");
1259 break;
1260 }
1261
1262 // Perform the second implicit conversion
1263 switch (SCS.Second) {
1264 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001265 // If both sides are functions (or pointers/references to them), there could
1266 // be incompatible exception declarations.
1267 if (CheckExceptionSpecCompatibility(From, ToType))
1268 return true;
1269 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001270 break;
1271
Douglas Gregor43c79c22009-12-09 00:47:37 +00001272 case ICK_NoReturn_Adjustment:
1273 // If both sides are functions (or pointers/references to them), there could
1274 // be incompatible exception declarations.
1275 if (CheckExceptionSpecCompatibility(From, ToType))
1276 return true;
1277
1278 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1279 CastExpr::CK_NoOp);
1280 break;
1281
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001282 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001283 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001284 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1285 break;
1286
1287 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001289 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1290 break;
1291
1292 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001293 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001294 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1295 break;
1296
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001297 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001298 if (ToType->isFloatingType())
1299 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1300 else
1301 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1302 break;
1303
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001304 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001305 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1306 break;
1307
Douglas Gregorf9201e02009-02-11 23:02:49 +00001308 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001309 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001310 break;
1311
Anders Carlsson61faec12009-09-12 04:46:44 +00001312 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001313 if (SCS.IncompatibleObjC) {
1314 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001315 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001316 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001317 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001318 << From->getSourceRange();
1319 }
1320
Anders Carlsson61faec12009-09-12 04:46:44 +00001321
1322 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001323 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001324 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001325 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001326 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001327 }
1328
1329 case ICK_Pointer_Member: {
1330 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001331 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001332 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001333 if (CheckExceptionSpecCompatibility(From, ToType))
1334 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001335 ImpCastExprToType(From, ToType, Kind);
1336 break;
1337 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001338 case ICK_Boolean_Conversion: {
1339 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1340 if (FromType->isMemberPointerType())
1341 Kind = CastExpr::CK_MemberPointerToBoolean;
1342
1343 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001344 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001345 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001346
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001347 case ICK_Derived_To_Base:
1348 if (CheckDerivedToBaseConversion(From->getType(),
1349 ToType.getNonReferenceType(),
1350 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001351 From->getSourceRange(),
1352 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001353 return true;
1354 ImpCastExprToType(From, ToType.getNonReferenceType(),
1355 CastExpr::CK_DerivedToBase);
1356 break;
1357
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001358 default:
1359 assert(false && "Improper second standard conversion");
1360 break;
1361 }
1362
1363 switch (SCS.Third) {
1364 case ICK_Identity:
1365 // Nothing to do.
1366 break;
1367
1368 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001369 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1370 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001371 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001372 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001373 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001374 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001375
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001376 default:
1377 assert(false && "Improper second standard conversion");
1378 break;
1379 }
1380
1381 return false;
1382}
1383
Sebastian Redl64b45f72009-01-05 20:52:13 +00001384Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1385 SourceLocation KWLoc,
1386 SourceLocation LParen,
1387 TypeTy *Ty,
1388 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001389 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001391 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1392 // all traits except __is_class, __is_enum and __is_union require a the type
1393 // to be complete.
1394 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001395 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001396 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001397 return ExprError();
1398 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001399
1400 // There is no point in eagerly computing the value. The traits are designed
1401 // to be used from type trait templates, so Ty will be a template parameter
1402 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001403 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1404 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001405}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001406
1407QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001408 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001409 const char *OpSpelling = isIndirect ? "->*" : ".*";
1410 // C++ 5.5p2
1411 // The binary operator .* [p3: ->*] binds its second operand, which shall
1412 // be of type "pointer to member of T" (where T is a completely-defined
1413 // class type) [...]
1414 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001415 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001416 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001417 Diag(Loc, diag::err_bad_memptr_rhs)
1418 << OpSpelling << RType << rex->getSourceRange();
1419 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001420 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001421
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001422 QualType Class(MemPtr->getClass(), 0);
1423
1424 // C++ 5.5p2
1425 // [...] to its first operand, which shall be of class T or of a class of
1426 // which T is an unambiguous and accessible base class. [p3: a pointer to
1427 // such a class]
1428 QualType LType = lex->getType();
1429 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001430 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001431 LType = Ptr->getPointeeType().getNonReferenceType();
1432 else {
1433 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001434 << OpSpelling << 1 << LType
1435 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001436 return QualType();
1437 }
1438 }
1439
Douglas Gregora4923eb2009-11-16 21:35:15 +00001440 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001441 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1442 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001443 // FIXME: Would it be useful to print full ambiguity paths, or is that
1444 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001445 if (!IsDerivedFrom(LType, Class, Paths) ||
1446 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001447 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001448 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001449 << (int)isIndirect << lex->getType() <<
1450 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001451 return QualType();
1452 }
1453 }
1454
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001455 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001456 // Diagnose use of pointer-to-member type which when used as
1457 // the functional cast in a pointer-to-member expression.
1458 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1459 return QualType();
1460 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001461 // C++ 5.5p2
1462 // The result is an object or a function of the type specified by the
1463 // second operand.
1464 // The cv qualifiers are the union of those in the pointer and the left side,
1465 // in accordance with 5.5p5 and 5.2.5.
1466 // FIXME: This returns a dereferenced member function pointer as a normal
1467 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001468 // calling them. There's also a GCC extension to get a function pointer to the
1469 // thing, which is another complication, because this type - unlike the type
1470 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001471 // argument.
1472 // We probably need a "MemberFunctionClosureType" or something like that.
1473 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001474 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001475 return Result;
1476}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001477
1478/// \brief Get the target type of a standard or user-defined conversion.
1479static QualType TargetType(const ImplicitConversionSequence &ICS) {
1480 assert((ICS.ConversionKind ==
1481 ImplicitConversionSequence::StandardConversion ||
1482 ICS.ConversionKind ==
1483 ImplicitConversionSequence::UserDefinedConversion) &&
1484 "function only valid for standard or user-defined conversions");
1485 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1486 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1487 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1488}
1489
1490/// \brief Try to convert a type to another according to C++0x 5.16p3.
1491///
1492/// This is part of the parameter validation for the ? operator. If either
1493/// value operand is a class type, the two operands are attempted to be
1494/// converted to each other. This function does the conversion in one direction.
1495/// It emits a diagnostic and returns true only if it finds an ambiguous
1496/// conversion.
1497static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1498 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001499 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001500 // C++0x 5.16p3
1501 // The process for determining whether an operand expression E1 of type T1
1502 // can be converted to match an operand expression E2 of type T2 is defined
1503 // as follows:
1504 // -- If E2 is an lvalue:
1505 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1506 // E1 can be converted to match E2 if E1 can be implicitly converted to
1507 // type "lvalue reference to T2", subject to the constraint that in the
1508 // conversion the reference must bind directly to E1.
1509 if (!Self.CheckReferenceInit(From,
1510 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001511 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001512 /*SuppressUserConversions=*/false,
1513 /*AllowExplicit=*/false,
1514 /*ForceRValue=*/false,
1515 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001516 {
1517 assert((ICS.ConversionKind ==
1518 ImplicitConversionSequence::StandardConversion ||
1519 ICS.ConversionKind ==
1520 ImplicitConversionSequence::UserDefinedConversion) &&
1521 "expected a definite conversion");
1522 bool DirectBinding =
1523 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1524 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1525 if (DirectBinding)
1526 return false;
1527 }
1528 }
1529 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1530 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1531 // -- if E1 and E2 have class type, and the underlying class types are
1532 // the same or one is a base class of the other:
1533 QualType FTy = From->getType();
1534 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001535 const RecordType *FRec = FTy->getAs<RecordType>();
1536 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001537 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1538 if (FRec && TRec && (FRec == TRec ||
1539 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1540 // E1 can be converted to match E2 if the class of T2 is the
1541 // same type as, or a base class of, the class of T1, and
1542 // [cv2 > cv1].
1543 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1544 // Could still fail if there's no copy constructor.
1545 // FIXME: Is this a hard error then, or just a conversion failure? The
1546 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001547 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001548 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001549 /*ForceRValue=*/false,
1550 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001551 }
1552 } else {
1553 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1554 // implicitly converted to the type that expression E2 would have
1555 // if E2 were converted to an rvalue.
1556 // First find the decayed type.
1557 if (TTy->isFunctionType())
1558 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001559 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001560 TTy = Self.Context.getArrayDecayedType(TTy);
1561
1562 // Now try the implicit conversion.
1563 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001564 ICS = Self.TryImplicitConversion(From, TTy,
1565 /*SuppressUserConversions=*/false,
1566 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001567 /*ForceRValue=*/false,
1568 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001569 }
1570 return false;
1571}
1572
1573/// \brief Try to find a common type for two according to C++0x 5.16p5.
1574///
1575/// This is part of the parameter validation for the ? operator. If either
1576/// value operand is a class type, overload resolution is used to find a
1577/// conversion to a common type.
1578static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1579 SourceLocation Loc) {
1580 Expr *Args[2] = { LHS, RHS };
1581 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001582 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001583
1584 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001585 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001586 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001587 // We found a match. Perform the conversions on the arguments and move on.
1588 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001589 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001590 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001591 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001592 break;
1593 return false;
1594
Douglas Gregor20093b42009-12-09 23:02:17 +00001595 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001596 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1597 << LHS->getType() << RHS->getType()
1598 << LHS->getSourceRange() << RHS->getSourceRange();
1599 return true;
1600
Douglas Gregor20093b42009-12-09 23:02:17 +00001601 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001602 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1603 << LHS->getType() << RHS->getType()
1604 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001605 // FIXME: Print the possible common types by printing the return types of
1606 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001607 break;
1608
Douglas Gregor20093b42009-12-09 23:02:17 +00001609 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001610 assert(false && "Conditional operator has only built-in overloads");
1611 break;
1612 }
1613 return true;
1614}
1615
Sebastian Redl76458502009-04-17 16:30:52 +00001616/// \brief Perform an "extended" implicit conversion as returned by
1617/// TryClassUnification.
1618///
1619/// TryClassUnification generates ICSs that include reference bindings.
1620/// PerformImplicitConversion is not suitable for this; it chokes if the
1621/// second part of a standard conversion is ICK_DerivedToBase. This function
1622/// handles the reference binding specially.
1623static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001624 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001625 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1626 ICS.Standard.ReferenceBinding) {
1627 assert(ICS.Standard.DirectBinding &&
1628 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001629 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1630 // redoing all the work.
1631 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001632 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001633 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001634 /*SuppressUserConversions=*/false,
1635 /*AllowExplicit=*/false,
1636 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001637 }
1638 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1639 ICS.UserDefined.After.ReferenceBinding) {
1640 assert(ICS.UserDefined.After.DirectBinding &&
1641 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001642 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001643 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001644 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001645 /*SuppressUserConversions=*/false,
1646 /*AllowExplicit=*/false,
1647 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001648 }
Douglas Gregor68647482009-12-16 03:45:30 +00001649 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001650 return true;
1651 return false;
1652}
1653
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001654/// \brief Check the operands of ?: under C++ semantics.
1655///
1656/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1657/// extension. In this case, LHS == Cond. (But they're not aliases.)
1658QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1659 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001660 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1661 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001662
1663 // C++0x 5.16p1
1664 // The first expression is contextually converted to bool.
1665 if (!Cond->isTypeDependent()) {
1666 if (CheckCXXBooleanCondition(Cond))
1667 return QualType();
1668 }
1669
1670 // Either of the arguments dependent?
1671 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1672 return Context.DependentTy;
1673
John McCallb13c87f2009-11-05 09:23:39 +00001674 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1675
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001676 // C++0x 5.16p2
1677 // If either the second or the third operand has type (cv) void, ...
1678 QualType LTy = LHS->getType();
1679 QualType RTy = RHS->getType();
1680 bool LVoid = LTy->isVoidType();
1681 bool RVoid = RTy->isVoidType();
1682 if (LVoid || RVoid) {
1683 // ... then the [l2r] conversions are performed on the second and third
1684 // operands ...
1685 DefaultFunctionArrayConversion(LHS);
1686 DefaultFunctionArrayConversion(RHS);
1687 LTy = LHS->getType();
1688 RTy = RHS->getType();
1689
1690 // ... and one of the following shall hold:
1691 // -- The second or the third operand (but not both) is a throw-
1692 // expression; the result is of the type of the other and is an rvalue.
1693 bool LThrow = isa<CXXThrowExpr>(LHS);
1694 bool RThrow = isa<CXXThrowExpr>(RHS);
1695 if (LThrow && !RThrow)
1696 return RTy;
1697 if (RThrow && !LThrow)
1698 return LTy;
1699
1700 // -- Both the second and third operands have type void; the result is of
1701 // type void and is an rvalue.
1702 if (LVoid && RVoid)
1703 return Context.VoidTy;
1704
1705 // Neither holds, error.
1706 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1707 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1708 << LHS->getSourceRange() << RHS->getSourceRange();
1709 return QualType();
1710 }
1711
1712 // Neither is void.
1713
1714 // C++0x 5.16p3
1715 // Otherwise, if the second and third operand have different types, and
1716 // either has (cv) class type, and attempt is made to convert each of those
1717 // operands to the other.
1718 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1719 (LTy->isRecordType() || RTy->isRecordType())) {
1720 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1721 // These return true if a single direction is already ambiguous.
1722 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1723 return QualType();
1724 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1725 return QualType();
1726
1727 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1728 ImplicitConversionSequence::BadConversion;
1729 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1730 ImplicitConversionSequence::BadConversion;
1731 // If both can be converted, [...] the program is ill-formed.
1732 if (HaveL2R && HaveR2L) {
1733 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1734 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1735 return QualType();
1736 }
1737
1738 // If exactly one conversion is possible, that conversion is applied to
1739 // the chosen operand and the converted operands are used in place of the
1740 // original operands for the remainder of this section.
1741 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001742 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001743 return QualType();
1744 LTy = LHS->getType();
1745 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001746 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001747 return QualType();
1748 RTy = RHS->getType();
1749 }
1750 }
1751
1752 // C++0x 5.16p4
1753 // If the second and third operands are lvalues and have the same type,
1754 // the result is of that type [...]
1755 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1756 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1757 RHS->isLvalue(Context) == Expr::LV_Valid)
1758 return LTy;
1759
1760 // C++0x 5.16p5
1761 // Otherwise, the result is an rvalue. If the second and third operands
1762 // do not have the same type, and either has (cv) class type, ...
1763 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1764 // ... overload resolution is used to determine the conversions (if any)
1765 // to be applied to the operands. If the overload resolution fails, the
1766 // program is ill-formed.
1767 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1768 return QualType();
1769 }
1770
1771 // C++0x 5.16p6
1772 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1773 // conversions are performed on the second and third operands.
1774 DefaultFunctionArrayConversion(LHS);
1775 DefaultFunctionArrayConversion(RHS);
1776 LTy = LHS->getType();
1777 RTy = RHS->getType();
1778
1779 // After those conversions, one of the following shall hold:
1780 // -- The second and third operands have the same type; the result
1781 // is of that type.
1782 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1783 return LTy;
1784
1785 // -- The second and third operands have arithmetic or enumeration type;
1786 // the usual arithmetic conversions are performed to bring them to a
1787 // common type, and the result is of that type.
1788 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1789 UsualArithmeticConversions(LHS, RHS);
1790 return LHS->getType();
1791 }
1792
1793 // -- The second and third operands have pointer type, or one has pointer
1794 // type and the other is a null pointer constant; pointer conversions
1795 // and qualification conversions are performed to bring them to their
1796 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001797 QualType Composite = FindCompositePointerType(LHS, RHS);
1798 if (!Composite.isNull())
1799 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00001800
1801 // Similarly, attempt to find composite type of twp objective-c pointers.
1802 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
1803 if (!Composite.isNull())
1804 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001805
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001806 // Fourth bullet is same for pointers-to-member. However, the possible
1807 // conversions are far more limited: we have null-to-pointer, upcast of
1808 // containing class, and second-level cv-ness.
1809 // cv-ness is not a union, but must match one of the two operands. (Which,
1810 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001811 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1812 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001813 if (LMemPtr &&
1814 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001815 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001816 return LTy;
1817 }
Douglas Gregorce940492009-09-25 04:25:58 +00001818 if (RMemPtr &&
1819 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001820 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001821 return RTy;
1822 }
1823 if (LMemPtr && RMemPtr) {
1824 QualType LPointee = LMemPtr->getPointeeType();
1825 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001826
1827 QualifierCollector LPQuals, RPQuals;
1828 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1829 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1830
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001831 // First, we check that the unqualified pointee type is the same. If it's
1832 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001833 if (LPCan == RPCan) {
1834
1835 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001836 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001837
1838 Qualifiers MergedQuals = LPQuals + RPQuals;
1839
1840 bool CompatibleQuals = true;
1841 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1842 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1843 CompatibleQuals = false;
1844 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1845 // FIXME:
1846 // C99 6.5.15 as modified by TR 18037:
1847 // If the second and third operands are pointers into different
1848 // address spaces, the address spaces must overlap.
1849 CompatibleQuals = false;
1850 // FIXME: GC qualifiers?
1851
1852 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001853 // Third, we check if either of the container classes is derived from
1854 // the other.
1855 QualType LContainer(LMemPtr->getClass(), 0);
1856 QualType RContainer(RMemPtr->getClass(), 0);
1857 QualType MoreDerived;
1858 if (Context.getCanonicalType(LContainer) ==
1859 Context.getCanonicalType(RContainer))
1860 MoreDerived = LContainer;
1861 else if (IsDerivedFrom(LContainer, RContainer))
1862 MoreDerived = LContainer;
1863 else if (IsDerivedFrom(RContainer, LContainer))
1864 MoreDerived = RContainer;
1865
1866 if (!MoreDerived.isNull()) {
1867 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1868 // We don't use ImpCastExprToType here because this could still fail
1869 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001870 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1871 QualType Common
1872 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Douglas Gregor68647482009-12-16 03:45:30 +00001873 if (PerformImplicitConversion(LHS, Common, Sema::AA_Converting))
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001874 return QualType();
Douglas Gregor68647482009-12-16 03:45:30 +00001875 if (PerformImplicitConversion(RHS, Common, Sema::AA_Converting))
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001876 return QualType();
1877 return Common;
1878 }
1879 }
1880 }
1881 }
1882
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001883 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1884 << LHS->getType() << RHS->getType()
1885 << LHS->getSourceRange() << RHS->getSourceRange();
1886 return QualType();
1887}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001888
1889/// \brief Find a merged pointer type and convert the two expressions to it.
1890///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001891/// This finds the composite pointer type (or member pointer type) for @p E1
1892/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1893/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001894/// It does not emit diagnostics.
1895QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1896 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1897 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00001899 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
1900 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00001901 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001902
1903 // C++0x 5.9p2
1904 // Pointer conversions and qualification conversions are performed on
1905 // pointer operands to bring them to their composite pointer type. If
1906 // one operand is a null pointer constant, the composite pointer type is
1907 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001908 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001909 if (T2->isMemberPointerType())
1910 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1911 else
1912 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001913 return T2;
1914 }
Douglas Gregorce940492009-09-25 04:25:58 +00001915 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001916 if (T1->isMemberPointerType())
1917 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1918 else
1919 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001920 return T1;
1921 }
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Douglas Gregor20b3e992009-08-24 17:42:35 +00001923 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001924 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1925 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001926 return QualType();
1927
1928 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1929 // the other has type "pointer to cv2 T" and the composite pointer type is
1930 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1931 // Otherwise, the composite pointer type is a pointer type similar to the
1932 // type of one of the operands, with a cv-qualification signature that is
1933 // the union of the cv-qualification signatures of the operand types.
1934 // In practice, the first part here is redundant; it's subsumed by the second.
1935 // What we do here is, we build the two possible composite types, and try the
1936 // conversions in both directions. If only one works, or if the two composite
1937 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001938 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001939 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1940 QualifierVector QualifierUnion;
1941 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1942 ContainingClassVector;
1943 ContainingClassVector MemberOfClass;
1944 QualType Composite1 = Context.getCanonicalType(T1),
1945 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001946 do {
1947 const PointerType *Ptr1, *Ptr2;
1948 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1949 (Ptr2 = Composite2->getAs<PointerType>())) {
1950 Composite1 = Ptr1->getPointeeType();
1951 Composite2 = Ptr2->getPointeeType();
1952 QualifierUnion.push_back(
1953 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1954 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1955 continue;
1956 }
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Douglas Gregor20b3e992009-08-24 17:42:35 +00001958 const MemberPointerType *MemPtr1, *MemPtr2;
1959 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1960 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1961 Composite1 = MemPtr1->getPointeeType();
1962 Composite2 = MemPtr2->getPointeeType();
1963 QualifierUnion.push_back(
1964 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1965 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1966 MemPtr2->getClass()));
1967 continue;
1968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Douglas Gregor20b3e992009-08-24 17:42:35 +00001970 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Douglas Gregor20b3e992009-08-24 17:42:35 +00001972 // Cannot unwrap any more types.
1973 break;
1974 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregor20b3e992009-08-24 17:42:35 +00001976 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001977 ContainingClassVector::reverse_iterator MOC
1978 = MemberOfClass.rbegin();
1979 for (QualifierVector::reverse_iterator
1980 I = QualifierUnion.rbegin(),
1981 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001982 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001983 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001984 if (MOC->first && MOC->second) {
1985 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00001986 Composite1 = Context.getMemberPointerType(
1987 Context.getQualifiedType(Composite1, Quals),
1988 MOC->first);
1989 Composite2 = Context.getMemberPointerType(
1990 Context.getQualifiedType(Composite2, Quals),
1991 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001992 } else {
1993 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00001994 Composite1
1995 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1996 Composite2
1997 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00001998 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001999 }
2000
Mike Stump1eb44332009-09-09 15:08:12 +00002001 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002002 TryImplicitConversion(E1, Composite1,
2003 /*SuppressUserConversions=*/false,
2004 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002005 /*ForceRValue=*/false,
2006 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002007 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002008 TryImplicitConversion(E2, Composite1,
2009 /*SuppressUserConversions=*/false,
2010 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002011 /*ForceRValue=*/false,
2012 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002014 ImplicitConversionSequence E1ToC2, E2ToC2;
2015 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2016 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2017 if (Context.getCanonicalType(Composite1) !=
2018 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002019 E1ToC2 = TryImplicitConversion(E1, Composite2,
2020 /*SuppressUserConversions=*/false,
2021 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002022 /*ForceRValue=*/false,
2023 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002024 E2ToC2 = TryImplicitConversion(E2, Composite2,
2025 /*SuppressUserConversions=*/false,
2026 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002027 /*ForceRValue=*/false,
2028 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002029 }
2030
2031 bool ToC1Viable = E1ToC1.ConversionKind !=
2032 ImplicitConversionSequence::BadConversion
2033 && E2ToC1.ConversionKind !=
2034 ImplicitConversionSequence::BadConversion;
2035 bool ToC2Viable = E1ToC2.ConversionKind !=
2036 ImplicitConversionSequence::BadConversion
2037 && E2ToC2.ConversionKind !=
2038 ImplicitConversionSequence::BadConversion;
2039 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002040 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2041 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002042 return Composite1;
2043 }
2044 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002045 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2046 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002047 return Composite2;
2048 }
2049 return QualType();
2050}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002051
Anders Carlssondef11992009-05-30 20:36:53 +00002052Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002053 if (!Context.getLangOptions().CPlusPlus)
2054 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Ted Kremenek6217b802009-07-29 21:53:49 +00002056 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002057 if (!RT)
2058 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Anders Carlssondef11992009-05-30 20:36:53 +00002060 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2061 if (RD->hasTrivialDestructor())
2062 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Anders Carlsson283e4d52009-09-14 01:30:44 +00002064 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2065 QualType Ty = CE->getCallee()->getType();
2066 if (const PointerType *PT = Ty->getAs<PointerType>())
2067 Ty = PT->getPointeeType();
2068
John McCall183700f2009-09-21 23:43:11 +00002069 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002070 if (FTy->getResultType()->isReferenceType())
2071 return Owned(E);
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002074 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002075 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002076 if (CXXDestructorDecl *Destructor =
2077 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2078 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002079 // FIXME: Add the temporary to the temporaries vector.
2080 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2081}
2082
Anders Carlsson0ece4912009-12-15 20:51:39 +00002083Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002084 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002086 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2087 assert(ExprTemporaries.size() >= FirstTemporary);
2088 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002089 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002091 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002092 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002093 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002094 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2095 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002097 return E;
2098}
2099
Douglas Gregor90f93822009-12-22 22:17:25 +00002100Sema::OwningExprResult
2101Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2102 if (SubExpr.isInvalid())
2103 return ExprError();
2104
2105 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2106}
2107
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002108FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2109 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2110 assert(ExprTemporaries.size() >= FirstTemporary);
2111
2112 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2113 CXXTemporary **Temporaries =
2114 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2115
2116 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2117
2118 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2119 ExprTemporaries.end());
2120
2121 return E;
2122}
2123
Mike Stump1eb44332009-09-09 15:08:12 +00002124Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002125Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2126 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2127 // Since this might be a postfix expression, get rid of ParenListExprs.
2128 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002130 Expr *BaseExpr = (Expr*)Base.get();
2131 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002133 QualType BaseType = BaseExpr->getType();
2134 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002135 // If we have a pointer to a dependent type and are using the -> operator,
2136 // the object type is the type that the pointer points to. We might still
2137 // have enough information about that type to do something useful.
2138 if (OpKind == tok::arrow)
2139 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2140 BaseType = Ptr->getPointeeType();
2141
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002142 ObjectType = BaseType.getAsOpaquePtr();
2143 return move(Base);
2144 }
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002146 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002147 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002148 // returned, with the original second operand.
2149 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002150 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002151 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002152 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002153 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002154
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002155 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002156 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002157 BaseExpr = (Expr*)Base.get();
2158 if (BaseExpr == NULL)
2159 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002160 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002161 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002162 BaseType = BaseExpr->getType();
2163 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002164 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002165 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002166 for (unsigned i = 0; i < Locations.size(); i++)
2167 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002168 return ExprError();
2169 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002170 }
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Douglas Gregor31658df2009-11-20 19:58:21 +00002172 if (BaseType->isPointerType())
2173 BaseType = BaseType->getPointeeType();
2174 }
Mike Stump1eb44332009-09-09 15:08:12 +00002175
2176 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002177 // vector types or Objective-C interfaces. Just return early and let
2178 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002179 if (!BaseType->isRecordType()) {
2180 // C++ [basic.lookup.classref]p2:
2181 // [...] If the type of the object expression is of pointer to scalar
2182 // type, the unqualified-id is looked up in the context of the complete
2183 // postfix-expression.
2184 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002185 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002186 }
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Douglas Gregor03c57052009-11-17 05:17:33 +00002188 // The object type must be complete (or dependent).
2189 if (!BaseType->isDependentType() &&
2190 RequireCompleteType(OpLoc, BaseType,
2191 PDiag(diag::err_incomplete_member_access)))
2192 return ExprError();
2193
Douglas Gregorc68afe22009-09-03 21:38:09 +00002194 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002195 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002196 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002197 // type C (or of pointer to a class type C), the unqualified-id is looked
2198 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002199 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002200
Mike Stump1eb44332009-09-09 15:08:12 +00002201 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002202}
2203
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002204CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2205 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002206 if (PerformObjectArgumentInitialization(Exp, Method))
2207 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2208
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002209 MemberExpr *ME =
2210 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2211 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002212 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002213 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2214 CXXMemberCallExpr *CE =
2215 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2216 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002217 return CE;
2218}
2219
Anders Carlsson0aebc812009-09-09 21:33:21 +00002220Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2221 QualType Ty,
2222 CastExpr::CastKind Kind,
2223 CXXMethodDecl *Method,
2224 ExprArg Arg) {
2225 Expr *From = Arg.takeAs<Expr>();
2226
2227 switch (Kind) {
2228 default: assert(0 && "Unhandled cast kind!");
2229 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002230 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2231
2232 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2233 MultiExprArg(*this, (void **)&From, 1),
2234 CastLoc, ConstructorArgs))
2235 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002236
2237 OwningExprResult Result =
2238 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2239 move_arg(ConstructorArgs));
2240 if (Result.isInvalid())
2241 return ExprError();
2242
2243 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002244 }
2245
2246 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002247 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002248
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002249 // Create an implicit call expr that calls it.
2250 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002251 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002252 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002253 }
2254}
2255
Anders Carlsson165a0a02009-05-17 18:41:29 +00002256Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2257 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002258 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002259 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002260
Anders Carlsson165a0a02009-05-17 18:41:29 +00002261 return Owned(FullExpr);
2262}
Douglas Gregore961afb2009-10-22 07:08:30 +00002263
2264/// \brief Determine whether a reference to the given declaration in the
2265/// current context is an implicit member access
2266/// (C++ [class.mfct.non-static]p2).
2267///
2268/// FIXME: Should Objective-C also use this approach?
2269///
Douglas Gregore961afb2009-10-22 07:08:30 +00002270/// \param D the declaration being referenced from the current scope.
2271///
2272/// \param NameLoc the location of the name in the source.
2273///
2274/// \param ThisType if the reference to this declaration is an implicit member
2275/// access, will be set to the type of the "this" pointer to be used when
2276/// building that implicit member access.
2277///
Douglas Gregore961afb2009-10-22 07:08:30 +00002278/// \returns true if this is an implicit member reference (in which case
2279/// \p ThisType and \p MemberType will be set), or false if it is not an
2280/// implicit member reference.
John McCall129e2df2009-11-30 22:42:35 +00002281bool Sema::isImplicitMemberReference(const LookupResult &R,
2282 QualType &ThisType) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002283 // If this isn't a C++ method, then it isn't an implicit member reference.
2284 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2285 if (!MD || MD->isStatic())
2286 return false;
2287
2288 // C++ [class.mfct.nonstatic]p2:
2289 // [...] if name lookup (3.4.1) resolves the name in the
2290 // id-expression to a nonstatic nontype member of class X or of
2291 // a base class of X, the id-expression is transformed into a
2292 // class member access expression (5.2.5) using (*this) (9.3.2)
2293 // as the postfix-expression to the left of the '.' operator.
2294 DeclContext *Ctx = 0;
John McCall129e2df2009-11-30 22:42:35 +00002295 if (R.isUnresolvableResult()) {
2296 // FIXME: this is just picking one at random
2297 Ctx = R.getRepresentativeDecl()->getDeclContext();
2298 } else if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) {
Douglas Gregore961afb2009-10-22 07:08:30 +00002299 Ctx = FD->getDeclContext();
Douglas Gregore961afb2009-10-22 07:08:30 +00002300 } else {
John McCall129e2df2009-11-30 22:42:35 +00002301 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2302 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I);
Douglas Gregore961afb2009-10-22 07:08:30 +00002303 FunctionTemplateDecl *FunTmpl = 0;
John McCall129e2df2009-11-30 22:42:35 +00002304 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*I)))
Douglas Gregore961afb2009-10-22 07:08:30 +00002305 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2306
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002307 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002308 if (Method && !Method->isStatic()) {
2309 Ctx = Method->getParent();
Douglas Gregore961afb2009-10-22 07:08:30 +00002310 break;
2311 }
2312 }
2313 }
2314
2315 if (!Ctx || !Ctx->isRecord())
2316 return false;
2317
2318 // Determine whether the declaration(s) we found are actually in a base
2319 // class. If not, this isn't an implicit member reference.
2320 ThisType = MD->getThisType(Context);
John McCall129e2df2009-11-30 22:42:35 +00002321
2322 // FIXME: this doesn't really work for overloaded lookups.
Douglas Gregor7a343142009-11-01 17:08:18 +00002323
Douglas Gregore961afb2009-10-22 07:08:30 +00002324 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2325 QualType ClassType
2326 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2327 return Context.hasSameType(CtxType, ClassType) ||
2328 IsDerivedFrom(ClassType, CtxType);
2329}
2330