blob: 209d3069cafeb4fab3ba27e3f9d742a1f5e3864e [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"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Sebastian Redlc42e1182008-11-11 11:37:55 +000026/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +000027Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +000028Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
29 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +000030 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +000031 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +000032
33 if (isType)
34 // FIXME: Preserve type source info.
35 TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
36
Chris Lattner572af492008-11-20 05:51:55 +000037 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +000038 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
39 LookupQualifiedName(R, StdNamespace);
John McCallf36e02d2009-10-09 21:13:30 +000040 Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
Sebastian Redlc42e1182008-11-11 11:37:55 +000041 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
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 Gregorac7610d2009-06-22 20:57:11 +000066 // If this is an unevaluated operand, clear out the set of declaration
67 // references we have been computing.
68 if (isUnevaluatedOperand)
69 PotentiallyReferencedDeclStack.back().clear();
70 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Sebastian Redlf53597f2009-03-15 17:47:39 +000072 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
73 TypeInfoType.withConst(),
74 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +000075}
76
Steve Naroff1b273c42007-09-16 14:56:35 +000077/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +000078Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000079Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000080 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000081 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +000082 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
83 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
Chris Lattner50dd2892008-02-26 00:51:44 +000085
Sebastian Redl6e8ed162009-05-10 18:38:11 +000086/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
87Action::OwningExprResult
88Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
89 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
90}
91
Chris Lattner50dd2892008-02-26 00:51:44 +000092/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +000093Action::OwningExprResult
94Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +000095 Expr *Ex = E.takeAs<Expr>();
96 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
97 return ExprError();
98 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
99}
100
101/// CheckCXXThrowOperand - Validate the operand of a throw.
102bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
103 // C++ [except.throw]p3:
104 // [...] adjusting the type from "array of T" or "function returning T"
105 // to "pointer to T" or "pointer to function returning T", [...]
106 DefaultFunctionArrayConversion(E);
107
108 // If the type of the exception would be an incomplete type or a pointer
109 // to an incomplete type other than (cv) void the program is ill-formed.
110 QualType Ty = E->getType();
111 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000112 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000113 Ty = Ptr->getPointeeType();
114 isPointer = 1;
115 }
116 if (!isPointer || !Ty->isVoidType()) {
117 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000118 PDiag(isPointer ? diag::err_throw_incomplete_ptr
119 : diag::err_throw_incomplete)
120 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000121 return true;
122 }
123
124 // FIXME: Construct a temporary here.
125 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000126}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000127
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000129 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
130 /// is a non-lvalue expression whose value is the address of the object for
131 /// which the function is called.
132
Sebastian Redlf53597f2009-03-15 17:47:39 +0000133 if (!isa<FunctionDecl>(CurContext))
134 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000135
136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
137 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000138 return Owned(new (Context) CXXThisExpr(ThisLoc,
139 MD->getThisType(Context)));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000140
Sebastian Redlf53597f2009-03-15 17:47:39 +0000141 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000142}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000143
144/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
145/// Can be interpreted either as function-style casting ("int(x)")
146/// or class type construction ("ClassType(x,y,z)")
147/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000148Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000149Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
150 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000152 SourceLocation *CommaLocs,
153 SourceLocation RParenLoc) {
154 assert(TypeRep && "Missing type!");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000155 // FIXME: Preserve type source info.
156 QualType Ty = GetTypeFromParser(TypeRep);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157 unsigned NumExprs = exprs.size();
158 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000159 SourceLocation TyBeginLoc = TypeRange.getBegin();
160 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
161
Sebastian Redlf53597f2009-03-15 17:47:39 +0000162 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000163 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000164 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000165
166 return Owned(CXXUnresolvedConstructExpr::Create(Context,
167 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000168 LParenLoc,
169 Exprs, NumExprs,
170 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000171 }
172
Anders Carlssonbb60a502009-08-27 03:53:50 +0000173 if (Ty->isArrayType())
174 return ExprError(Diag(TyBeginLoc,
175 diag::err_value_init_for_array_type) << FullRange);
176 if (!Ty->isVoidType() &&
177 RequireCompleteType(TyBeginLoc, Ty,
178 PDiag(diag::err_invalid_incomplete_type_use)
179 << FullRange))
180 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000181
Anders Carlssonbb60a502009-08-27 03:53:50 +0000182 if (RequireNonAbstractType(TyBeginLoc, Ty,
183 diag::err_allocation_of_abstract_type))
184 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
186
Douglas Gregor506ae412009-01-16 18:33:17 +0000187 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188 // If the expression list is a single expression, the type conversion
189 // expression is equivalent (in definedness, and if defined in meaning) to the
190 // corresponding cast expression.
191 //
192 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000193 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000194 CXXMethodDecl *Method = 0;
195 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
196 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000197 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000198
199 exprs.release();
200 if (Method) {
201 OwningExprResult CastArg
202 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
203 Kind, Method, Owned(Exprs[0]));
204 if (CastArg.isInvalid())
205 return ExprError();
206
207 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000208 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000209
210 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
211 Ty, TyBeginLoc, Kind,
212 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000213 }
214
Ted Kremenek6217b802009-07-29 21:53:49 +0000215 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000216 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000217
Mike Stump1eb44332009-09-09 15:08:12 +0000218 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000219 !Record->hasTrivialDestructor()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000220 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
221
Douglas Gregor506ae412009-01-16 18:33:17 +0000222 CXXConstructorDecl *Constructor
Douglas Gregor39da0b82009-09-09 23:08:42 +0000223 = PerformInitializationByConstructor(Ty, move(exprs),
Douglas Gregor506ae412009-01-16 18:33:17 +0000224 TypeRange.getBegin(),
225 SourceRange(TypeRange.getBegin(),
226 RParenLoc),
227 DeclarationName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000228 IK_Direct,
229 ConstructorArgs);
Douglas Gregor506ae412009-01-16 18:33:17 +0000230
Sebastian Redlf53597f2009-03-15 17:47:39 +0000231 if (!Constructor)
232 return ExprError();
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234 OwningExprResult Result =
235 BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor39da0b82009-09-09 23:08:42 +0000236 move_arg(ConstructorArgs), RParenLoc);
Anders Carlssone7624a72009-08-27 05:08:22 +0000237 if (Result.isInvalid())
238 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Anders Carlssone7624a72009-08-27 05:08:22 +0000240 return MaybeBindToTemporary(Result.takeAs<Expr>());
Douglas Gregor506ae412009-01-16 18:33:17 +0000241 }
242
243 // Fall through to value-initialize an object of class type that
244 // doesn't have a user-declared default constructor.
245 }
246
247 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000248 // If the expression list specifies more than a single value, the type shall
249 // be a class with a suitably declared constructor.
250 //
251 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000252 return ExprError(Diag(CommaLocs[0],
253 diag::err_builtin_func_cast_more_than_one_arg)
254 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000255
256 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000257 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000258 // The expression T(), where T is a simple-type-specifier for a non-array
259 // complete object type or the (possibly cv-qualified) void type, creates an
260 // rvalue of the specified type, which is value-initialized.
261 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000262 exprs.release();
263 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000264}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000265
266
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000267/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
268/// @code new (memory) int[size][4] @endcode
269/// or
270/// @code ::new Foo(23, "hello") @endcode
271/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000272Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000273Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000274 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000275 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000276 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000278 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000279 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000280 // If the specified type is an array, unwrap it and save the expression.
281 if (D.getNumTypeObjects() > 0 &&
282 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
283 DeclaratorChunk &Chunk = D.getTypeObject(0);
284 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000285 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
286 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000287 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000288 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
289 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000290
291 if (ParenTypeId) {
292 // Can't have dynamic array size when the type-id is in parentheses.
293 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
294 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
295 !NumElts->isIntegerConstantExpr(Context)) {
296 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
297 << NumElts->getSourceRange();
298 return ExprError();
299 }
300 }
301
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000302 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000303 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 }
305
Douglas Gregor043cad22009-09-11 00:18:58 +0000306 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000307 if (ArraySize) {
308 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000309 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
310 break;
311
312 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
313 if (Expr *NumElts = (Expr *)Array.NumElts) {
314 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
315 !NumElts->isIntegerConstantExpr(Context)) {
316 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
317 << NumElts->getSourceRange();
318 return ExprError();
319 }
320 }
321 }
322 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000323
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000324 //FIXME: Store DeclaratorInfo in CXXNew expression.
325 DeclaratorInfo *DInfo = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000326 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000327 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000329
Mike Stump1eb44332009-09-09 15:08:12 +0000330 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000331 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000332 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000333 PlacementRParen,
334 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000335 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000336 D.getSourceRange().getBegin(),
337 D.getSourceRange(),
338 Owned(ArraySize),
339 ConstructorLParen,
340 move(ConstructorArgs),
341 ConstructorRParen);
342}
343
Mike Stump1eb44332009-09-09 15:08:12 +0000344Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000345Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
346 SourceLocation PlacementLParen,
347 MultiExprArg PlacementArgs,
348 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000349 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000350 QualType AllocType,
351 SourceLocation TypeLoc,
352 SourceRange TypeRange,
353 ExprArg ArraySizeE,
354 SourceLocation ConstructorLParen,
355 MultiExprArg ConstructorArgs,
356 SourceLocation ConstructorRParen) {
357 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000359
Douglas Gregor3433cf72009-05-21 00:00:09 +0000360 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000361
362 // That every array dimension except the first is constant was already
363 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000364
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
366 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000367 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000368 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000369 QualType SizeType = ArraySize->getType();
370 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
372 diag::err_array_size_not_integral)
373 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000374 // Let's see if this is a constant < 0. If so, we reject it out of hand.
375 // We don't care about special rules, so we tell the machinery it's not
376 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000377 if (!ArraySize->isValueDependent()) {
378 llvm::APSInt Value;
379 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
380 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000381 llvm::APInt::getNullValue(Value.getBitWidth()),
382 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000383 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
384 diag::err_typecheck_negative_array_size)
385 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000386 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000387 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000388
Eli Friedman73c39ab2009-10-20 08:27:19 +0000389 ImpCastExprToType(ArraySize, Context.getSizeType(),
390 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000391 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000392
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000393 FunctionDecl *OperatorNew = 0;
394 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
396 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000397
Sebastian Redl28507842009-02-26 14:39:58 +0000398 if (!AllocType->isDependentType() &&
399 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
400 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000401 SourceRange(PlacementLParen, PlacementRParen),
402 UseGlobal, AllocType, ArraySize, PlaceArgs,
403 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000404 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000405 llvm::SmallVector<Expr *, 4> AllPlaceArgs;
406 if (OperatorNew) {
407 // Add default arguments, if any.
408 const FunctionProtoType *Proto =
409 OperatorNew->getType()->getAs<FunctionProtoType>();
410 unsigned NumArgsInProto = Proto->getNumArgs();
411 for (unsigned i = 1; i != NumArgsInProto; i++) {
412 QualType ProtoArgType = Proto->getArgType(i);
413
414 Expr *Arg;
415 if (i <= NumPlaceArgs) {
416 AllPlaceArgs.push_back(PlaceArgs[i-1]);
417 continue;
418 }
419 ParmVarDecl *Param = OperatorNew->getParamDecl(i);
420
421 OwningExprResult ArgExpr =
422 BuildCXXDefaultArgExpr(StartLoc, OperatorNew, Param);
423 if (ArgExpr.isInvalid())
424 return ExprError();
425
426 Arg = ArgExpr.takeAs<Expr>();
427 AllPlaceArgs.push_back(Arg);
428 }
429 NumPlaceArgs = AllPlaceArgs.size();
430 if (NumPlaceArgs > 0)
431 PlaceArgs = &AllPlaceArgs[0];
432 }
433
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000434 bool Init = ConstructorLParen.isValid();
435 // --- Choosing a constructor ---
436 // C++ 5.3.4p15
437 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
438 // the object is not initialized. If the object, or any part of it, is
439 // const-qualified, it's an error.
440 // 2) If T is a POD and there's an empty initializer, the object is value-
441 // initialized.
442 // 3) If T is a POD and there's one initializer argument, the object is copy-
443 // constructed.
444 // 4) If T is a POD and there's more initializer arguments, it's an error.
445 // 5) If T is not a POD, the initializer arguments are used as constructor
446 // arguments.
447 //
448 // Or by the C++0x formulation:
449 // 1) If there's no initializer, the object is default-initialized according
450 // to C++0x rules.
451 // 2) Otherwise, the object is direct-initialized.
452 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000453 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
Sebastian Redl4f149632009-05-07 16:14:23 +0000454 const RecordType *RT;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000455 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000456 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
457
Douglas Gregor089407b2009-10-17 21:40:42 +0000458 if (AllocType->isDependentType() ||
459 Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
Sebastian Redl28507842009-02-26 14:39:58 +0000460 // Skip all the checks.
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000461 } else if ((RT = AllocType->getAs<RecordType>()) &&
462 !AllocType->isAggregateType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000463 Constructor = PerformInitializationByConstructor(
Douglas Gregor39da0b82009-09-09 23:08:42 +0000464 AllocType, move(ConstructorArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000465 TypeLoc,
466 SourceRange(TypeLoc, ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000467 RT->getDecl()->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000468 NumConsArgs != 0 ? IK_Direct : IK_Default,
469 ConvertedConstructorArgs);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000470 if (!Constructor)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 return ExprError();
Douglas Gregor39da0b82009-09-09 23:08:42 +0000472
473 // Take the converted constructor arguments and use them for the new
474 // expression.
475 NumConsArgs = ConvertedConstructorArgs.size();
476 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000477 } else {
478 if (!Init) {
479 // FIXME: Check that no subpart is const.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000480 if (AllocType.isConstQualified())
481 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
Douglas Gregor3433cf72009-05-21 00:00:09 +0000482 << TypeRange);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000483 } else if (NumConsArgs == 0) {
Fariborz Jahanian6f269202009-11-03 20:38:53 +0000484 // Object is value-initialized. Do nothing.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000485 } else if (NumConsArgs == 1) {
486 // Object is direct-initialized.
Sebastian Redl4f149632009-05-07 16:14:23 +0000487 // FIXME: What DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000488 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000489 DeclarationName() /*AllocType.getAsString()*/,
490 /*DirectInit=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000491 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000492 } else {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000493 return ExprError(Diag(StartLoc,
494 diag::err_builtin_direct_init_more_than_one_arg)
495 << SourceRange(ConstructorLParen, ConstructorRParen));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000496 }
497 }
498
499 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000500
Sebastian Redlf53597f2009-03-15 17:47:39 +0000501 PlacementArgs.release();
502 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000503 ArraySizeE.release();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000504 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000505 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000506 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Mike Stump1eb44332009-09-09 15:08:12 +0000507 StartLoc, Init ? ConstructorRParen : SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000508}
509
510/// CheckAllocatedType - Checks that a type is suitable as the allocated type
511/// in a new-expression.
512/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000513bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000514 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000515 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
516 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000517 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000518 return Diag(Loc, diag::err_bad_new_type)
519 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000520 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000521 return Diag(Loc, diag::err_bad_new_type)
522 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000523 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000524 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000525 PDiag(diag::err_new_incomplete_type)
526 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000527 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000528 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000529 diag::err_allocation_of_abstract_type))
530 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000531
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000532 return false;
533}
534
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000535/// FindAllocationFunctions - Finds the overloads of operator new and delete
536/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000537bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
538 bool UseGlobal, QualType AllocType,
539 bool IsArray, Expr **PlaceArgs,
540 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000541 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000542 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000543 // --- Choosing an allocation function ---
544 // C++ 5.3.4p8 - 14 & 18
545 // 1) If UseGlobal is true, only look in the global scope. Else, also look
546 // in the scope of the allocated class.
547 // 2) If an array size is given, look for operator new[], else look for
548 // operator new.
549 // 3) The first argument is always size_t. Append the arguments from the
550 // placement form.
551 // FIXME: Also find the appropriate delete operator.
552
553 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
554 // We don't care about the actual value of this argument.
555 // FIXME: Should the Sema create the expression and embed it in the syntax
556 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000557 IntegerLiteral Size(llvm::APInt::getNullValue(
558 Context.Target.getPointerWidth(0)),
559 Context.getSizeType(),
560 SourceLocation());
561 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000562 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
563
564 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
565 IsArray ? OO_Array_New : OO_New);
566 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000567 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000568 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000569 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000570 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000571 AllocArgs.size(), Record, /*AllowMissing=*/true,
572 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000573 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000574 }
575 if (!OperatorNew) {
576 // Didn't find a member overload. Look for a global one.
577 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000578 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000579 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000580 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
581 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000582 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000583 }
584
Anders Carlssond9583892009-05-31 20:26:12 +0000585 // FindAllocationOverload can change the passed in arguments, so we need to
586 // copy them back.
587 if (NumPlaceArgs > 0)
588 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000590 return false;
591}
592
Sebastian Redl7f662392008-12-04 22:20:51 +0000593/// FindAllocationOverload - Find an fitting overload for the allocation
594/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000595bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
596 DeclarationName Name, Expr** Args,
597 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000598 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000599 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
600 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000601 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000602 if (AllowMissing)
603 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000604 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000605 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000606 }
607
John McCallf36e02d2009-10-09 21:13:30 +0000608 // FIXME: handle ambiguity
609
Sebastian Redl7f662392008-12-04 22:20:51 +0000610 OverloadCandidateSet Candidates;
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000611 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
612 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000613 // Even member operator new/delete are implicitly treated as
614 // static, so don't use AddMemberCandidate.
Douglas Gregor90916562009-09-29 18:16:17 +0000615 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000616 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
617 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000618 continue;
619 }
620
621 // FIXME: Handle function templates
Sebastian Redl7f662392008-12-04 22:20:51 +0000622 }
623
624 // Do the resolution.
625 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000626 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000627 case OR_Success: {
628 // Got one!
629 FunctionDecl *FnDecl = Best->Function;
630 // The first argument is size_t, and the first parameter must be size_t,
631 // too. This is checked on declaration and can be assumed. (It can't be
632 // asserted on, though, since invalid decls are left in there.)
Douglas Gregor90916562009-09-29 18:16:17 +0000633 for (unsigned i = 0; i < NumArgs; ++i) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000634 // FIXME: Passing word to diagnostic.
Anders Carlssonfc27d262009-05-31 19:49:47 +0000635 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000636 FnDecl->getParamDecl(i)->getType(),
637 "passing"))
638 return true;
639 }
640 Operator = FnDecl;
641 return false;
642 }
643
644 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000645 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000646 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000647 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
648 return true;
649
650 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000651 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000652 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000653 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
654 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000655
656 case OR_Deleted:
657 Diag(StartLoc, diag::err_ovl_deleted_call)
658 << Best->Function->isDeleted()
659 << Name << Range;
660 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
661 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000662 }
663 assert(false && "Unreachable, bad result from BestViableFunction");
664 return true;
665}
666
667
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000668/// DeclareGlobalNewDelete - Declare the global forms of operator new and
669/// delete. These are:
670/// @code
671/// void* operator new(std::size_t) throw(std::bad_alloc);
672/// void* operator new[](std::size_t) throw(std::bad_alloc);
673/// void operator delete(void *) throw();
674/// void operator delete[](void *) throw();
675/// @endcode
676/// Note that the placement and nothrow forms of new are *not* implicitly
677/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000678void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000679 if (GlobalNewDeleteDeclared)
680 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000681
682 // C++ [basic.std.dynamic]p2:
683 // [...] The following allocation and deallocation functions (18.4) are
684 // implicitly declared in global scope in each translation unit of a
685 // program
686 //
687 // void* operator new(std::size_t) throw(std::bad_alloc);
688 // void* operator new[](std::size_t) throw(std::bad_alloc);
689 // void operator delete(void*) throw();
690 // void operator delete[](void*) throw();
691 //
692 // These implicit declarations introduce only the function names operator
693 // new, operator new[], operator delete, operator delete[].
694 //
695 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
696 // "std" or "bad_alloc" as necessary to form the exception specification.
697 // However, we do not make these implicit declarations visible to name
698 // lookup.
699 if (!StdNamespace) {
700 // The "std" namespace has not yet been defined, so build one implicitly.
701 StdNamespace = NamespaceDecl::Create(Context,
702 Context.getTranslationUnitDecl(),
703 SourceLocation(),
704 &PP.getIdentifierTable().get("std"));
705 StdNamespace->setImplicit(true);
706 }
707
708 if (!StdBadAlloc) {
709 // The "std::bad_alloc" class has not yet been declared, so build it
710 // implicitly.
711 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
712 StdNamespace,
713 SourceLocation(),
714 &PP.getIdentifierTable().get("bad_alloc"),
715 SourceLocation(), 0);
716 StdBadAlloc->setImplicit(true);
717 }
718
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000719 GlobalNewDeleteDeclared = true;
720
721 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
722 QualType SizeT = Context.getSizeType();
723
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000724 DeclareGlobalAllocationFunction(
725 Context.DeclarationNames.getCXXOperatorName(OO_New),
726 VoidPtr, SizeT);
727 DeclareGlobalAllocationFunction(
728 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
729 VoidPtr, SizeT);
730 DeclareGlobalAllocationFunction(
731 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
732 Context.VoidTy, VoidPtr);
733 DeclareGlobalAllocationFunction(
734 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
735 Context.VoidTy, VoidPtr);
736}
737
738/// DeclareGlobalAllocationFunction - Declares a single implicit global
739/// allocation function if it doesn't already exist.
740void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Mike Stump1eb44332009-09-09 15:08:12 +0000741 QualType Return, QualType Argument) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000742 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
743
744 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000745 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000746 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000747 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000748 Alloc != AllocEnd; ++Alloc) {
749 // FIXME: Do we need to check for default arguments here?
750 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
751 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000752 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000753 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000754 }
755 }
756
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000757 QualType BadAllocType;
758 bool HasBadAllocExceptionSpec
759 = (Name.getCXXOverloadedOperator() == OO_New ||
760 Name.getCXXOverloadedOperator() == OO_Array_New);
761 if (HasBadAllocExceptionSpec) {
762 assert(StdBadAlloc && "Must have std::bad_alloc declared");
763 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
764 }
765
766 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
767 true, false,
768 HasBadAllocExceptionSpec? 1 : 0,
769 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000770 FunctionDecl *Alloc =
771 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000772 FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000773 Alloc->setImplicit();
774 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000775 0, Argument, /*DInfo=*/0,
776 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000777 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000778
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000779 // FIXME: Also add this declaration to the IdentifierResolver, but
780 // make sure it is at the end of the chain to coincide with the
781 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000782 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000783}
784
Anders Carlsson78f74552009-11-15 18:45:20 +0000785bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
786 DeclarationName Name,
787 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000788 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +0000789 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000790 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +0000791
John McCalla24dc2e2009-11-17 02:14:36 +0000792 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +0000793 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +0000794
795 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
796 F != FEnd; ++F) {
797 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
798 if (Delete->isUsualDeallocationFunction()) {
799 Operator = Delete;
800 return false;
801 }
802 }
803
804 // We did find operator delete/operator delete[] declarations, but
805 // none of them were suitable.
806 if (!Found.empty()) {
807 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
808 << Name << RD;
809
810 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
811 F != FEnd; ++F) {
812 Diag((*F)->getLocation(),
813 diag::note_delete_member_function_declared_here)
814 << Name;
815 }
816
817 return true;
818 }
819
820 // Look for a global declaration.
821 DeclareGlobalNewDelete();
822 DeclContext *TUDecl = Context.getTranslationUnitDecl();
823
824 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
825 Expr* DeallocArgs[1];
826 DeallocArgs[0] = &Null;
827 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
828 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
829 Operator))
830 return true;
831
832 assert(Operator && "Did not find a deallocation function!");
833 return false;
834}
835
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000836/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
837/// @code ::delete ptr; @endcode
838/// or
839/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +0000840Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000841Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +0000842 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000843 // C++ [expr.delete]p1:
844 // The operand shall have a pointer type, or a class type having a single
845 // conversion function to a pointer type. The result has type void.
846 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000847 // DR599 amends "pointer type" to "pointer to object type" in both cases.
848
Anders Carlssond67c4c32009-08-16 20:29:29 +0000849 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Sebastian Redlf53597f2009-03-15 17:47:39 +0000851 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000852 if (!Ex->isTypeDependent()) {
853 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000854
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000855 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000856 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +0000857 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
858 OverloadedFunctionDecl *Conversions =
Fariborz Jahanian62509212009-09-12 18:26:03 +0000859 RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000860
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000861 for (OverloadedFunctionDecl::function_iterator
862 Func = Conversions->function_begin(),
863 FuncEnd = Conversions->function_end();
864 Func != FuncEnd; ++Func) {
865 // Skip over templated conversion functions; they aren't considered.
866 if (isa<FunctionTemplateDecl>(*Func))
867 continue;
868
869 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
870
871 QualType ConvType = Conv->getConversionType().getNonReferenceType();
872 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
873 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000874 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000875 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +0000876 if (ObjectPtrConversions.size() == 1) {
877 // We have a single conversion to a pointer-to-object type. Perform
878 // that conversion.
879 Operand.release();
880 if (!PerformImplicitConversion(Ex,
881 ObjectPtrConversions.front()->getConversionType(),
882 "converting")) {
883 Operand = Owned(Ex);
884 Type = Ex->getType();
885 }
886 }
887 else if (ObjectPtrConversions.size() > 1) {
888 Diag(StartLoc, diag::err_ambiguous_delete_operand)
889 << Type << Ex->getSourceRange();
890 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
891 CXXConversionDecl *Conv = ObjectPtrConversions[i];
892 Diag(Conv->getLocation(), diag::err_ovl_candidate);
893 }
894 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +0000895 }
Sebastian Redl28507842009-02-26 14:39:58 +0000896 }
897
Sebastian Redlf53597f2009-03-15 17:47:39 +0000898 if (!Type->isPointerType())
899 return ExprError(Diag(StartLoc, diag::err_delete_operand)
900 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000901
Ted Kremenek6217b802009-07-29 21:53:49 +0000902 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000903 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000904 return ExprError(Diag(StartLoc, diag::err_delete_operand)
905 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000906 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000907 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000908 PDiag(diag::warn_delete_incomplete)
909 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000910 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +0000911
Douglas Gregor1070c9f2009-09-29 21:38:53 +0000912 // C++ [expr.delete]p2:
913 // [Note: a pointer to a const type can be the operand of a
914 // delete-expression; it is not necessary to cast away the constness
915 // (5.2.11) of the pointer expression before it is used as the operand
916 // of the delete-expression. ]
917 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
918 CastExpr::CK_NoOp);
919
920 // Update the operand.
921 Operand.take();
922 Operand = ExprArg(*this, Ex);
923
Anders Carlssond67c4c32009-08-16 20:29:29 +0000924 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
925 ArrayForm ? OO_Array_Delete : OO_Delete);
926
Anders Carlsson78f74552009-11-15 18:45:20 +0000927 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
928 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
929
930 if (!UseGlobal &&
931 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000932 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +0000933
Anders Carlsson78f74552009-11-15 18:45:20 +0000934 if (!RD->hasTrivialDestructor())
935 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +0000936 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +0000937 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +0000938 }
Anders Carlsson78f74552009-11-15 18:45:20 +0000939
Anders Carlssond67c4c32009-08-16 20:29:29 +0000940 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +0000941 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +0000942 DeclareGlobalNewDelete();
943 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000944 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +0000945 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000946 OperatorDelete))
947 return ExprError();
948 }
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Sebastian Redl28507842009-02-26 14:39:58 +0000950 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000951 }
952
Sebastian Redlf53597f2009-03-15 17:47:39 +0000953 Operand.release();
954 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +0000955 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000956}
957
958
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000959/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
960/// C++ if/switch/while/for statement.
961/// e.g: "if (int x = f()) {...}"
Sebastian Redlf53597f2009-03-15 17:47:39 +0000962Action::OwningExprResult
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000963Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
964 Declarator &D,
965 SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000966 ExprArg AssignExprVal) {
967 assert(AssignExprVal.get() && "Null assignment expression");
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000968
969 // C++ 6.4p2:
970 // The declarator shall not specify a function or an array.
971 // The type-specifier-seq shall not contain typedef and shall not declare a
972 // new class or enumeration.
973
974 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
975 "Parser allowed 'typedef' as storage class of condition decl.");
976
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000977 // FIXME: Store DeclaratorInfo in the expression.
978 DeclaratorInfo *DInfo = 0;
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000979 TagDecl *OwnedTag = 0;
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000980 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000982 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
983 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
984 // would be created and CXXConditionDeclExpr wants a VarDecl.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000985 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
986 << SourceRange(StartLoc, EqualLoc));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000987 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000988 Diag(StartLoc, diag::err_invalid_use_of_array_type)
989 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidise955e722009-08-11 05:20:41 +0000990 } else if (OwnedTag && OwnedTag->isDefinition()) {
991 // The type-specifier-seq shall not declare a new class or enumeration.
992 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000993 }
994
Douglas Gregor2e01cda2009-06-23 21:43:56 +0000995 DeclPtrTy Dcl = ActOnDeclarator(S, D);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000996 if (!Dcl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000997 return ExprError();
Anders Carlssonf5dcd382009-05-30 21:37:25 +0000998 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000999
Douglas Gregorcaaf29a2008-12-10 23:01:14 +00001000 // Mark this variable as one that is declared within a conditional.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001001 // We know that the decl had to be a VarDecl because that is the only type of
1002 // decl that can be assigned and the grammar requires an '='.
1003 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
1004 VD->setDeclaredInCondition(true);
1005 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001006}
1007
1008/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1009bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1010 // C++ 6.4p4:
1011 // The value of a condition that is an initialized declaration in a statement
1012 // other than a switch statement is the value of the declared variable
1013 // implicitly converted to type bool. If that conversion is ill-formed, the
1014 // program is ill-formed.
1015 // The value of a condition that is an expression is the value of the
1016 // expression, implicitly converted to bool.
1017 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001018 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001019}
Douglas Gregor77a52232008-09-12 00:47:35 +00001020
1021/// Helper function to determine whether this is the (deprecated) C++
1022/// conversion from a string literal to a pointer to non-const char or
1023/// non-const wchar_t (for narrow and wide string literals,
1024/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001025bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001026Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1027 // Look inside the implicit cast, if it exists.
1028 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1029 From = Cast->getSubExpr();
1030
1031 // A string literal (2.13.4) that is not a wide string literal can
1032 // be converted to an rvalue of type "pointer to char"; a wide
1033 // string literal can be converted to an rvalue of type "pointer
1034 // to wchar_t" (C++ 4.2p2).
1035 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001036 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001037 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001038 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001039 // This conversion is considered only when there is an
1040 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001041 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001042 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1043 (!StrLit->isWide() &&
1044 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1045 ToPointeeType->getKind() == BuiltinType::Char_S))))
1046 return true;
1047 }
1048
1049 return false;
1050}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001051
1052/// PerformImplicitConversion - Perform an implicit conversion of the
1053/// expression From to the type ToType. Returns true if there was an
1054/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001055/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001056/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001057/// explicit user-defined conversions are permitted. @p Elidable should be true
1058/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1059/// resolution works differently in that case.
1060bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001061Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001062 const char *Flavor, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001063 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001064 ImplicitConversionSequence ICS;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001065 return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1066 Elidable, ICS);
1067}
1068
1069bool
1070Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1071 const char *Flavor, bool AllowExplicit,
1072 bool Elidable,
1073 ImplicitConversionSequence& ICS) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001074 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1075 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001076 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001077 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001078 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001079 /*ForceRValue=*/true,
1080 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001081 }
1082 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001083 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001084 /*SuppressUserConversions=*/false,
1085 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001086 /*ForceRValue=*/false,
1087 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001088 }
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001089 return PerformImplicitConversion(From, ToType, ICS, Flavor);
1090}
1091
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001092/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1093/// for the derived to base conversion of the expression 'From'. All
1094/// necessary information is passed in ICS.
1095bool
1096Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1097 const ImplicitConversionSequence& ICS,
1098 const char *Flavor) {
1099 QualType BaseType =
1100 QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1101 // Must do additional defined to base conversion.
1102 QualType DerivedType =
1103 QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1104
1105 From = new (Context) ImplicitCastExpr(
1106 DerivedType.getNonReferenceType(),
1107 CastKind,
1108 From,
1109 DerivedType->isLValueReferenceType());
1110 From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1111 CastExpr::CK_DerivedToBase, From,
1112 BaseType->isLValueReferenceType());
1113 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1114 OwningExprResult FromResult =
1115 BuildCXXConstructExpr(
1116 ICS.UserDefined.After.CopyConstructor->getLocation(),
1117 BaseType,
1118 ICS.UserDefined.After.CopyConstructor,
1119 MultiExprArg(*this, (void **)&From, 1));
1120 if (FromResult.isInvalid())
1121 return true;
1122 From = FromResult.takeAs<Expr>();
1123 return false;
1124}
1125
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001126/// PerformImplicitConversion - Perform an implicit conversion of the
1127/// expression From to the type ToType using the pre-computed implicit
1128/// conversion sequence ICS. Returns true if there was an error, false
1129/// otherwise. The expression From is replaced with the converted
1130/// expression. Flavor is the kind of conversion we're performing,
1131/// used in the error message.
1132bool
1133Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1134 const ImplicitConversionSequence &ICS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001135 const char* Flavor, bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001136 switch (ICS.ConversionKind) {
1137 case ImplicitConversionSequence::StandardConversion:
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001138 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1139 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001140 return true;
1141 break;
1142
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001143 case ImplicitConversionSequence::UserDefinedConversion: {
1144
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001145 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1146 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001147 QualType BeforeToType;
1148 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001149 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001150
1151 // If the user-defined conversion is specified by a conversion function,
1152 // the initial standard conversion sequence converts the source type to
1153 // the implicit object parameter of the conversion function.
1154 BeforeToType = Context.getTagDeclType(Conv->getParent());
1155 } else if (const CXXConstructorDecl *Ctor =
1156 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001157 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001158 // Do no conversion if dealing with ... for the first conversion.
1159 if (!ICS.UserDefined.EllipsisConversion)
1160 // If the user-defined conversion is specified by a constructor, the
1161 // initial standard conversion sequence converts the source type to the
1162 // type required by the argument of the constructor
1163 BeforeToType = Ctor->getParamDecl(0)->getType();
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001164 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001165 else
1166 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001167 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001168 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001169 if (PerformImplicitConversion(From, BeforeToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001170 ICS.UserDefined.Before, "converting",
1171 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001172 return true;
1173 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001174
Anders Carlsson0aebc812009-09-09 21:33:21 +00001175 OwningExprResult CastArg
1176 = BuildCXXCastArgument(From->getLocStart(),
1177 ToType.getNonReferenceType(),
1178 CastKind, cast<CXXMethodDecl>(FD),
1179 Owned(From));
1180
1181 if (CastArg.isInvalid())
1182 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001183
1184 if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1185 ICS.UserDefined.After.CopyConstructor) {
1186 From = CastArg.takeAs<Expr>();
1187 return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1188 }
Fariborz Jahanian7a1f4cc2009-10-23 18:08:22 +00001189
1190 if (ICS.UserDefined.After.Second == ICK_Pointer_Member &&
1191 ToType.getNonReferenceType()->isMemberFunctionPointerType())
1192 CastKind = CastExpr::CK_BaseToDerivedMemberPointer;
Anders Carlsson0aebc812009-09-09 21:33:21 +00001193
Anders Carlsson626c2d62009-09-15 05:49:31 +00001194 From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001195 CastKind, CastArg.takeAs<Expr>(),
Anders Carlsson626c2d62009-09-15 05:49:31 +00001196 ToType->isLValueReferenceType());
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001197 return false;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001198 }
1199
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001200 case ImplicitConversionSequence::EllipsisConversion:
1201 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001202 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001203
1204 case ImplicitConversionSequence::BadConversion:
1205 return true;
1206 }
1207
1208 // Everything went well.
1209 return false;
1210}
1211
1212/// PerformImplicitConversion - Perform an implicit conversion of the
1213/// expression From to the type ToType by following the standard
1214/// conversion sequence SCS. Returns true if there was an error, false
1215/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001216/// expression. Flavor is the context in which we're performing this
1217/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001218bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001219Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001220 const StandardConversionSequence& SCS,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001221 const char *Flavor, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001222 // Overall FIXME: we are recomputing too many types here and doing far too
1223 // much extra work. What this means is that we need to keep track of more
1224 // information that is computed when we try the implicit conversion initially,
1225 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001226 QualType FromType = From->getType();
1227
Douglas Gregor225c41e2008-11-03 19:09:14 +00001228 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001229 // FIXME: When can ToType be a reference type?
1230 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001231 if (SCS.Second == ICK_Derived_To_Base) {
1232 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1233 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1234 MultiExprArg(*this, (void **)&From, 1),
1235 /*FIXME:ConstructLoc*/SourceLocation(),
1236 ConstructorArgs))
1237 return true;
1238 OwningExprResult FromResult =
1239 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1240 ToType, SCS.CopyConstructor,
1241 move_arg(ConstructorArgs));
1242 if (FromResult.isInvalid())
1243 return true;
1244 From = FromResult.takeAs<Expr>();
1245 return false;
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247 OwningExprResult FromResult =
1248 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1249 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001250 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001252 if (FromResult.isInvalid())
1253 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001255 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001256 return false;
1257 }
1258
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001259 // Perform the first implicit conversion.
1260 switch (SCS.First) {
1261 case ICK_Identity:
1262 case ICK_Lvalue_To_Rvalue:
1263 // Nothing to do.
1264 break;
1265
1266 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001267 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001268 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001269 break;
1270
1271 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001272 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001273 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1274 if (!Fn)
1275 return true;
1276
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001277 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1278 return true;
1279
Anders Carlsson96ad5332009-10-21 17:16:23 +00001280 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001281 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001282
Sebastian Redl759986e2009-10-17 20:50:27 +00001283 // If there's already an address-of operator in the expression, we have
1284 // the right type already, and the code below would just introduce an
1285 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001286 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001287 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001288 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001289 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001290 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 break;
1292
1293 default:
1294 assert(false && "Improper first standard conversion");
1295 break;
1296 }
1297
1298 // Perform the second implicit conversion
1299 switch (SCS.Second) {
1300 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001301 // If both sides are functions (or pointers/references to them), there could
1302 // be incompatible exception declarations.
1303 if (CheckExceptionSpecCompatibility(From, ToType))
1304 return true;
1305 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 break;
1307
1308 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001309 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001310 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1311 break;
1312
1313 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001314 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001315 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1316 break;
1317
1318 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001319 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001320 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1321 break;
1322
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001323 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001324 if (ToType->isFloatingType())
1325 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1326 else
1327 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1328 break;
1329
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001330 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001331 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1332 break;
1333
Douglas Gregorf9201e02009-02-11 23:02:49 +00001334 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001335 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001336 break;
1337
Anders Carlsson61faec12009-09-12 04:46:44 +00001338 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001339 if (SCS.IncompatibleObjC) {
1340 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001341 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001342 diag::ext_typecheck_convert_incompatible_pointer)
1343 << From->getType() << ToType << Flavor
1344 << From->getSourceRange();
1345 }
1346
Anders Carlsson61faec12009-09-12 04:46:44 +00001347
1348 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001349 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001350 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001351 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001352 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001353 }
1354
1355 case ICK_Pointer_Member: {
1356 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001357 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001358 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001359 if (CheckExceptionSpecCompatibility(From, ToType))
1360 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001361 ImpCastExprToType(From, ToType, Kind);
1362 break;
1363 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001364 case ICK_Boolean_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001365 ImpCastExprToType(From, Context.BoolTy, CastExpr::CK_Unknown);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001366 break;
1367
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001368 case ICK_Derived_To_Base:
1369 if (CheckDerivedToBaseConversion(From->getType(),
1370 ToType.getNonReferenceType(),
1371 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001372 From->getSourceRange(),
1373 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001374 return true;
1375 ImpCastExprToType(From, ToType.getNonReferenceType(),
1376 CastExpr::CK_DerivedToBase);
1377 break;
1378
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001379 default:
1380 assert(false && "Improper second standard conversion");
1381 break;
1382 }
1383
1384 switch (SCS.Third) {
1385 case ICK_Identity:
1386 // Nothing to do.
1387 break;
1388
1389 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001390 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1391 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001392 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001393 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001394 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001395 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001396
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001397 default:
1398 assert(false && "Improper second standard conversion");
1399 break;
1400 }
1401
1402 return false;
1403}
1404
Sebastian Redl64b45f72009-01-05 20:52:13 +00001405Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1406 SourceLocation KWLoc,
1407 SourceLocation LParen,
1408 TypeTy *Ty,
1409 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001410 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001412 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1413 // all traits except __is_class, __is_enum and __is_union require a the type
1414 // to be complete.
1415 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001416 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001417 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001418 return ExprError();
1419 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001420
1421 // There is no point in eagerly computing the value. The traits are designed
1422 // to be used from type trait templates, so Ty will be a template parameter
1423 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001424 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1425 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001426}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001427
1428QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001429 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001430 const char *OpSpelling = isIndirect ? "->*" : ".*";
1431 // C++ 5.5p2
1432 // The binary operator .* [p3: ->*] binds its second operand, which shall
1433 // be of type "pointer to member of T" (where T is a completely-defined
1434 // class type) [...]
1435 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001436 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001437 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001438 Diag(Loc, diag::err_bad_memptr_rhs)
1439 << OpSpelling << RType << rex->getSourceRange();
1440 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001441 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001442
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001443 QualType Class(MemPtr->getClass(), 0);
1444
1445 // C++ 5.5p2
1446 // [...] to its first operand, which shall be of class T or of a class of
1447 // which T is an unambiguous and accessible base class. [p3: a pointer to
1448 // such a class]
1449 QualType LType = lex->getType();
1450 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001451 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001452 LType = Ptr->getPointeeType().getNonReferenceType();
1453 else {
1454 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001455 << OpSpelling << 1 << LType
1456 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001457 return QualType();
1458 }
1459 }
1460
Douglas Gregora4923eb2009-11-16 21:35:15 +00001461 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001462 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1463 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001464 // FIXME: Would it be useful to print full ambiguity paths, or is that
1465 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001466 if (!IsDerivedFrom(LType, Class, Paths) ||
1467 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001468 const char *ReplaceStr = isIndirect ? ".*" : "->*";
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001469 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001470 << (int)isIndirect << lex->getType() <<
1471 CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001472 return QualType();
1473 }
1474 }
1475
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001476 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001477 // Diagnose use of pointer-to-member type which when used as
1478 // the functional cast in a pointer-to-member expression.
1479 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1480 return QualType();
1481 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001482 // C++ 5.5p2
1483 // The result is an object or a function of the type specified by the
1484 // second operand.
1485 // The cv qualifiers are the union of those in the pointer and the left side,
1486 // in accordance with 5.5p5 and 5.2.5.
1487 // FIXME: This returns a dereferenced member function pointer as a normal
1488 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001489 // calling them. There's also a GCC extension to get a function pointer to the
1490 // thing, which is another complication, because this type - unlike the type
1491 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001492 // argument.
1493 // We probably need a "MemberFunctionClosureType" or something like that.
1494 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001495 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001496 return Result;
1497}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001498
1499/// \brief Get the target type of a standard or user-defined conversion.
1500static QualType TargetType(const ImplicitConversionSequence &ICS) {
1501 assert((ICS.ConversionKind ==
1502 ImplicitConversionSequence::StandardConversion ||
1503 ICS.ConversionKind ==
1504 ImplicitConversionSequence::UserDefinedConversion) &&
1505 "function only valid for standard or user-defined conversions");
1506 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1507 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1508 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1509}
1510
1511/// \brief Try to convert a type to another according to C++0x 5.16p3.
1512///
1513/// This is part of the parameter validation for the ? operator. If either
1514/// value operand is a class type, the two operands are attempted to be
1515/// converted to each other. This function does the conversion in one direction.
1516/// It emits a diagnostic and returns true only if it finds an ambiguous
1517/// conversion.
1518static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1519 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001520 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001521 // C++0x 5.16p3
1522 // The process for determining whether an operand expression E1 of type T1
1523 // can be converted to match an operand expression E2 of type T2 is defined
1524 // as follows:
1525 // -- If E2 is an lvalue:
1526 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1527 // E1 can be converted to match E2 if E1 can be implicitly converted to
1528 // type "lvalue reference to T2", subject to the constraint that in the
1529 // conversion the reference must bind directly to E1.
1530 if (!Self.CheckReferenceInit(From,
1531 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001532 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001533 /*SuppressUserConversions=*/false,
1534 /*AllowExplicit=*/false,
1535 /*ForceRValue=*/false,
1536 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001537 {
1538 assert((ICS.ConversionKind ==
1539 ImplicitConversionSequence::StandardConversion ||
1540 ICS.ConversionKind ==
1541 ImplicitConversionSequence::UserDefinedConversion) &&
1542 "expected a definite conversion");
1543 bool DirectBinding =
1544 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1545 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1546 if (DirectBinding)
1547 return false;
1548 }
1549 }
1550 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1551 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1552 // -- if E1 and E2 have class type, and the underlying class types are
1553 // the same or one is a base class of the other:
1554 QualType FTy = From->getType();
1555 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001556 const RecordType *FRec = FTy->getAs<RecordType>();
1557 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001558 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1559 if (FRec && TRec && (FRec == TRec ||
1560 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1561 // E1 can be converted to match E2 if the class of T2 is the
1562 // same type as, or a base class of, the class of T1, and
1563 // [cv2 > cv1].
1564 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1565 // Could still fail if there's no copy constructor.
1566 // FIXME: Is this a hard error then, or just a conversion failure? The
1567 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001568 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001569 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001570 /*ForceRValue=*/false,
1571 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001572 }
1573 } else {
1574 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1575 // implicitly converted to the type that expression E2 would have
1576 // if E2 were converted to an rvalue.
1577 // First find the decayed type.
1578 if (TTy->isFunctionType())
1579 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001580 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001581 TTy = Self.Context.getArrayDecayedType(TTy);
1582
1583 // Now try the implicit conversion.
1584 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001585 ICS = Self.TryImplicitConversion(From, TTy,
1586 /*SuppressUserConversions=*/false,
1587 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001588 /*ForceRValue=*/false,
1589 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001590 }
1591 return false;
1592}
1593
1594/// \brief Try to find a common type for two according to C++0x 5.16p5.
1595///
1596/// This is part of the parameter validation for the ? operator. If either
1597/// value operand is a class type, overload resolution is used to find a
1598/// conversion to a common type.
1599static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1600 SourceLocation Loc) {
1601 Expr *Args[2] = { LHS, RHS };
1602 OverloadCandidateSet CandidateSet;
Douglas Gregor573d9c32009-10-21 23:19:44 +00001603 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001604
1605 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001606 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001607 case Sema::OR_Success:
1608 // We found a match. Perform the conversions on the arguments and move on.
1609 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1610 Best->Conversions[0], "converting") ||
1611 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1612 Best->Conversions[1], "converting"))
1613 break;
1614 return false;
1615
1616 case Sema::OR_No_Viable_Function:
1617 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1618 << LHS->getType() << RHS->getType()
1619 << LHS->getSourceRange() << RHS->getSourceRange();
1620 return true;
1621
1622 case Sema::OR_Ambiguous:
1623 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1624 << LHS->getType() << RHS->getType()
1625 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001626 // FIXME: Print the possible common types by printing the return types of
1627 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001628 break;
1629
1630 case Sema::OR_Deleted:
1631 assert(false && "Conditional operator has only built-in overloads");
1632 break;
1633 }
1634 return true;
1635}
1636
Sebastian Redl76458502009-04-17 16:30:52 +00001637/// \brief Perform an "extended" implicit conversion as returned by
1638/// TryClassUnification.
1639///
1640/// TryClassUnification generates ICSs that include reference bindings.
1641/// PerformImplicitConversion is not suitable for this; it chokes if the
1642/// second part of a standard conversion is ICK_DerivedToBase. This function
1643/// handles the reference binding specially.
1644static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001645 const ImplicitConversionSequence &ICS) {
Sebastian Redl76458502009-04-17 16:30:52 +00001646 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1647 ICS.Standard.ReferenceBinding) {
1648 assert(ICS.Standard.DirectBinding &&
1649 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001650 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1651 // redoing all the work.
1652 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001653 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001654 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001655 /*SuppressUserConversions=*/false,
1656 /*AllowExplicit=*/false,
1657 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001658 }
1659 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1660 ICS.UserDefined.After.ReferenceBinding) {
1661 assert(ICS.UserDefined.After.DirectBinding &&
1662 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001663 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001664 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001665 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001666 /*SuppressUserConversions=*/false,
1667 /*AllowExplicit=*/false,
1668 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001669 }
1670 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1671 return true;
1672 return false;
1673}
1674
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001675/// \brief Check the operands of ?: under C++ semantics.
1676///
1677/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1678/// extension. In this case, LHS == Cond. (But they're not aliases.)
1679QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1680 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001681 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1682 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001683
1684 // C++0x 5.16p1
1685 // The first expression is contextually converted to bool.
1686 if (!Cond->isTypeDependent()) {
1687 if (CheckCXXBooleanCondition(Cond))
1688 return QualType();
1689 }
1690
1691 // Either of the arguments dependent?
1692 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1693 return Context.DependentTy;
1694
John McCallb13c87f2009-11-05 09:23:39 +00001695 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1696
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001697 // C++0x 5.16p2
1698 // If either the second or the third operand has type (cv) void, ...
1699 QualType LTy = LHS->getType();
1700 QualType RTy = RHS->getType();
1701 bool LVoid = LTy->isVoidType();
1702 bool RVoid = RTy->isVoidType();
1703 if (LVoid || RVoid) {
1704 // ... then the [l2r] conversions are performed on the second and third
1705 // operands ...
1706 DefaultFunctionArrayConversion(LHS);
1707 DefaultFunctionArrayConversion(RHS);
1708 LTy = LHS->getType();
1709 RTy = RHS->getType();
1710
1711 // ... and one of the following shall hold:
1712 // -- The second or the third operand (but not both) is a throw-
1713 // expression; the result is of the type of the other and is an rvalue.
1714 bool LThrow = isa<CXXThrowExpr>(LHS);
1715 bool RThrow = isa<CXXThrowExpr>(RHS);
1716 if (LThrow && !RThrow)
1717 return RTy;
1718 if (RThrow && !LThrow)
1719 return LTy;
1720
1721 // -- Both the second and third operands have type void; the result is of
1722 // type void and is an rvalue.
1723 if (LVoid && RVoid)
1724 return Context.VoidTy;
1725
1726 // Neither holds, error.
1727 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1728 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1729 << LHS->getSourceRange() << RHS->getSourceRange();
1730 return QualType();
1731 }
1732
1733 // Neither is void.
1734
1735 // C++0x 5.16p3
1736 // Otherwise, if the second and third operand have different types, and
1737 // either has (cv) class type, and attempt is made to convert each of those
1738 // operands to the other.
1739 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1740 (LTy->isRecordType() || RTy->isRecordType())) {
1741 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1742 // These return true if a single direction is already ambiguous.
1743 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1744 return QualType();
1745 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1746 return QualType();
1747
1748 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1749 ImplicitConversionSequence::BadConversion;
1750 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1751 ImplicitConversionSequence::BadConversion;
1752 // If both can be converted, [...] the program is ill-formed.
1753 if (HaveL2R && HaveR2L) {
1754 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1755 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1756 return QualType();
1757 }
1758
1759 // If exactly one conversion is possible, that conversion is applied to
1760 // the chosen operand and the converted operands are used in place of the
1761 // original operands for the remainder of this section.
1762 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001763 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001764 return QualType();
1765 LTy = LHS->getType();
1766 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001767 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001768 return QualType();
1769 RTy = RHS->getType();
1770 }
1771 }
1772
1773 // C++0x 5.16p4
1774 // If the second and third operands are lvalues and have the same type,
1775 // the result is of that type [...]
1776 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1777 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1778 RHS->isLvalue(Context) == Expr::LV_Valid)
1779 return LTy;
1780
1781 // C++0x 5.16p5
1782 // Otherwise, the result is an rvalue. If the second and third operands
1783 // do not have the same type, and either has (cv) class type, ...
1784 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1785 // ... overload resolution is used to determine the conversions (if any)
1786 // to be applied to the operands. If the overload resolution fails, the
1787 // program is ill-formed.
1788 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1789 return QualType();
1790 }
1791
1792 // C++0x 5.16p6
1793 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1794 // conversions are performed on the second and third operands.
1795 DefaultFunctionArrayConversion(LHS);
1796 DefaultFunctionArrayConversion(RHS);
1797 LTy = LHS->getType();
1798 RTy = RHS->getType();
1799
1800 // After those conversions, one of the following shall hold:
1801 // -- The second and third operands have the same type; the result
1802 // is of that type.
1803 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1804 return LTy;
1805
1806 // -- The second and third operands have arithmetic or enumeration type;
1807 // the usual arithmetic conversions are performed to bring them to a
1808 // common type, and the result is of that type.
1809 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1810 UsualArithmeticConversions(LHS, RHS);
1811 return LHS->getType();
1812 }
1813
1814 // -- The second and third operands have pointer type, or one has pointer
1815 // type and the other is a null pointer constant; pointer conversions
1816 // and qualification conversions are performed to bring them to their
1817 // composite pointer type. The result is of the composite pointer type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001818 QualType Composite = FindCompositePointerType(LHS, RHS);
1819 if (!Composite.isNull())
1820 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001821
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001822 // Fourth bullet is same for pointers-to-member. However, the possible
1823 // conversions are far more limited: we have null-to-pointer, upcast of
1824 // containing class, and second-level cv-ness.
1825 // cv-ness is not a union, but must match one of the two operands. (Which,
1826 // frankly, is stupid.)
Ted Kremenek6217b802009-07-29 21:53:49 +00001827 const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1828 const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
Douglas Gregorce940492009-09-25 04:25:58 +00001829 if (LMemPtr &&
1830 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001831 ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001832 return LTy;
1833 }
Douglas Gregorce940492009-09-25 04:25:58 +00001834 if (RMemPtr &&
1835 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001836 ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001837 return RTy;
1838 }
1839 if (LMemPtr && RMemPtr) {
1840 QualType LPointee = LMemPtr->getPointeeType();
1841 QualType RPointee = RMemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001842
1843 QualifierCollector LPQuals, RPQuals;
1844 const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1845 const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1846
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001847 // First, we check that the unqualified pointee type is the same. If it's
1848 // not, there's no conversion that will unify the two pointers.
John McCall0953e762009-09-24 19:53:00 +00001849 if (LPCan == RPCan) {
1850
1851 // Second, we take the greater of the two qualifications. If neither
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001852 // is greater than the other, the conversion is not possible.
John McCall0953e762009-09-24 19:53:00 +00001853
1854 Qualifiers MergedQuals = LPQuals + RPQuals;
1855
1856 bool CompatibleQuals = true;
1857 if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1858 MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1859 CompatibleQuals = false;
1860 else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1861 // FIXME:
1862 // C99 6.5.15 as modified by TR 18037:
1863 // If the second and third operands are pointers into different
1864 // address spaces, the address spaces must overlap.
1865 CompatibleQuals = false;
1866 // FIXME: GC qualifiers?
1867
1868 if (CompatibleQuals) {
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001869 // Third, we check if either of the container classes is derived from
1870 // the other.
1871 QualType LContainer(LMemPtr->getClass(), 0);
1872 QualType RContainer(RMemPtr->getClass(), 0);
1873 QualType MoreDerived;
1874 if (Context.getCanonicalType(LContainer) ==
1875 Context.getCanonicalType(RContainer))
1876 MoreDerived = LContainer;
1877 else if (IsDerivedFrom(LContainer, RContainer))
1878 MoreDerived = LContainer;
1879 else if (IsDerivedFrom(RContainer, LContainer))
1880 MoreDerived = RContainer;
1881
1882 if (!MoreDerived.isNull()) {
1883 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1884 // We don't use ImpCastExprToType here because this could still fail
1885 // for ambiguous or inaccessible conversions.
John McCall0953e762009-09-24 19:53:00 +00001886 LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1887 QualType Common
1888 = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
Sebastian Redl9bebfad2009-04-19 21:15:26 +00001889 if (PerformImplicitConversion(LHS, Common, "converting"))
1890 return QualType();
1891 if (PerformImplicitConversion(RHS, Common, "converting"))
1892 return QualType();
1893 return Common;
1894 }
1895 }
1896 }
1897 }
1898
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001899 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1900 << LHS->getType() << RHS->getType()
1901 << LHS->getSourceRange() << RHS->getSourceRange();
1902 return QualType();
1903}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001904
1905/// \brief Find a merged pointer type and convert the two expressions to it.
1906///
Douglas Gregor20b3e992009-08-24 17:42:35 +00001907/// This finds the composite pointer type (or member pointer type) for @p E1
1908/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1909/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001910/// It does not emit diagnostics.
1911QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1912 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1913 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Douglas Gregor20b3e992009-08-24 17:42:35 +00001915 if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1916 !T2->isPointerType() && !T2->isMemberPointerType())
1917 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001918
1919 // C++0x 5.9p2
1920 // Pointer conversions and qualification conversions are performed on
1921 // pointer operands to bring them to their composite pointer type. If
1922 // one operand is a null pointer constant, the composite pointer type is
1923 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00001924 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001925 if (T2->isMemberPointerType())
1926 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1927 else
1928 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001929 return T2;
1930 }
Douglas Gregorce940492009-09-25 04:25:58 +00001931 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00001932 if (T1->isMemberPointerType())
1933 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1934 else
1935 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001936 return T1;
1937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Douglas Gregor20b3e992009-08-24 17:42:35 +00001939 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001940 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1941 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00001942 return QualType();
1943
1944 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1945 // the other has type "pointer to cv2 T" and the composite pointer type is
1946 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1947 // Otherwise, the composite pointer type is a pointer type similar to the
1948 // type of one of the operands, with a cv-qualification signature that is
1949 // the union of the cv-qualification signatures of the operand types.
1950 // In practice, the first part here is redundant; it's subsumed by the second.
1951 // What we do here is, we build the two possible composite types, and try the
1952 // conversions in both directions. If only one works, or if the two composite
1953 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00001954 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00001955 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1956 QualifierVector QualifierUnion;
1957 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1958 ContainingClassVector;
1959 ContainingClassVector MemberOfClass;
1960 QualType Composite1 = Context.getCanonicalType(T1),
1961 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00001962 do {
1963 const PointerType *Ptr1, *Ptr2;
1964 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1965 (Ptr2 = Composite2->getAs<PointerType>())) {
1966 Composite1 = Ptr1->getPointeeType();
1967 Composite2 = Ptr2->getPointeeType();
1968 QualifierUnion.push_back(
1969 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1970 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1971 continue;
1972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Douglas Gregor20b3e992009-08-24 17:42:35 +00001974 const MemberPointerType *MemPtr1, *MemPtr2;
1975 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1976 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1977 Composite1 = MemPtr1->getPointeeType();
1978 Composite2 = MemPtr2->getPointeeType();
1979 QualifierUnion.push_back(
1980 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1981 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1982 MemPtr2->getClass()));
1983 continue;
1984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor20b3e992009-08-24 17:42:35 +00001986 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Douglas Gregor20b3e992009-08-24 17:42:35 +00001988 // Cannot unwrap any more types.
1989 break;
1990 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Douglas Gregor20b3e992009-08-24 17:42:35 +00001992 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00001993 ContainingClassVector::reverse_iterator MOC
1994 = MemberOfClass.rbegin();
1995 for (QualifierVector::reverse_iterator
1996 I = QualifierUnion.rbegin(),
1997 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00001998 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00001999 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002000 if (MOC->first && MOC->second) {
2001 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002002 Composite1 = Context.getMemberPointerType(
2003 Context.getQualifiedType(Composite1, Quals),
2004 MOC->first);
2005 Composite2 = Context.getMemberPointerType(
2006 Context.getQualifiedType(Composite2, Quals),
2007 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002008 } else {
2009 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002010 Composite1
2011 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2012 Composite2
2013 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002014 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002015 }
2016
Mike Stump1eb44332009-09-09 15:08:12 +00002017 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002018 TryImplicitConversion(E1, Composite1,
2019 /*SuppressUserConversions=*/false,
2020 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002021 /*ForceRValue=*/false,
2022 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002023 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002024 TryImplicitConversion(E2, Composite1,
2025 /*SuppressUserConversions=*/false,
2026 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002027 /*ForceRValue=*/false,
2028 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002030 ImplicitConversionSequence E1ToC2, E2ToC2;
2031 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2032 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2033 if (Context.getCanonicalType(Composite1) !=
2034 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002035 E1ToC2 = TryImplicitConversion(E1, Composite2,
2036 /*SuppressUserConversions=*/false,
2037 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002038 /*ForceRValue=*/false,
2039 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002040 E2ToC2 = TryImplicitConversion(E2, Composite2,
2041 /*SuppressUserConversions=*/false,
2042 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002043 /*ForceRValue=*/false,
2044 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002045 }
2046
2047 bool ToC1Viable = E1ToC1.ConversionKind !=
2048 ImplicitConversionSequence::BadConversion
2049 && E2ToC1.ConversionKind !=
2050 ImplicitConversionSequence::BadConversion;
2051 bool ToC2Viable = E1ToC2.ConversionKind !=
2052 ImplicitConversionSequence::BadConversion
2053 && E2ToC2.ConversionKind !=
2054 ImplicitConversionSequence::BadConversion;
2055 if (ToC1Viable && !ToC2Viable) {
2056 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2057 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2058 return Composite1;
2059 }
2060 if (ToC2Viable && !ToC1Viable) {
2061 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2062 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2063 return Composite2;
2064 }
2065 return QualType();
2066}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002067
Anders Carlssondef11992009-05-30 20:36:53 +00002068Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002069 if (!Context.getLangOptions().CPlusPlus)
2070 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Ted Kremenek6217b802009-07-29 21:53:49 +00002072 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002073 if (!RT)
2074 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Anders Carlssondef11992009-05-30 20:36:53 +00002076 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2077 if (RD->hasTrivialDestructor())
2078 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Anders Carlsson283e4d52009-09-14 01:30:44 +00002080 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2081 QualType Ty = CE->getCallee()->getType();
2082 if (const PointerType *PT = Ty->getAs<PointerType>())
2083 Ty = PT->getPointeeType();
2084
John McCall183700f2009-09-21 23:43:11 +00002085 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002086 if (FTy->getResultType()->isReferenceType())
2087 return Owned(E);
2088 }
Mike Stump1eb44332009-09-09 15:08:12 +00002089 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002090 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002091 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002092 if (CXXDestructorDecl *Destructor =
2093 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2094 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002095 // FIXME: Add the temporary to the temporaries vector.
2096 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2097}
2098
Mike Stump1eb44332009-09-09 15:08:12 +00002099Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002100 bool ShouldDestroyTemps) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002101 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002103 if (ExprTemporaries.empty())
2104 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002106 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002107 &ExprTemporaries[0],
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002108 ExprTemporaries.size(),
Anders Carlssonf54741e2009-06-16 03:37:31 +00002109 ShouldDestroyTemps);
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002110 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002112 return E;
2113}
2114
Mike Stump1eb44332009-09-09 15:08:12 +00002115Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002116Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2117 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2118 // Since this might be a postfix expression, get rid of ParenListExprs.
2119 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002121 Expr *BaseExpr = (Expr*)Base.get();
2122 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002124 QualType BaseType = BaseExpr->getType();
2125 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002126 // If we have a pointer to a dependent type and are using the -> operator,
2127 // the object type is the type that the pointer points to. We might still
2128 // have enough information about that type to do something useful.
2129 if (OpKind == tok::arrow)
2130 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2131 BaseType = Ptr->getPointeeType();
2132
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002133 ObjectType = BaseType.getAsOpaquePtr();
2134 return move(Base);
2135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002137 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002138 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002139 // returned, with the original second operand.
2140 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002141 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002142 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002143 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002144 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002145
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002146 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002147 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002148 BaseExpr = (Expr*)Base.get();
2149 if (BaseExpr == NULL)
2150 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002151 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002152 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002153 BaseType = BaseExpr->getType();
2154 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002155 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002156 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002157 for (unsigned i = 0; i < Locations.size(); i++)
2158 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002159 return ExprError();
2160 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002161 }
2162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002164 if (BaseType->isPointerType())
2165 BaseType = BaseType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002166
2167 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002168 // vector types or Objective-C interfaces. Just return early and let
2169 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002170 if (!BaseType->isRecordType()) {
2171 // C++ [basic.lookup.classref]p2:
2172 // [...] If the type of the object expression is of pointer to scalar
2173 // type, the unqualified-id is looked up in the context of the complete
2174 // postfix-expression.
2175 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002176 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002177 }
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Douglas Gregor03c57052009-11-17 05:17:33 +00002179 // The object type must be complete (or dependent).
2180 if (!BaseType->isDependentType() &&
2181 RequireCompleteType(OpLoc, BaseType,
2182 PDiag(diag::err_incomplete_member_access)))
2183 return ExprError();
2184
Douglas Gregorc68afe22009-09-03 21:38:09 +00002185 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002186 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002187 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002188 // type C (or of pointer to a class type C), the unqualified-id is looked
2189 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002190 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002191
Mike Stump1eb44332009-09-09 15:08:12 +00002192 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002193}
2194
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002195CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2196 CXXMethodDecl *Method) {
2197 MemberExpr *ME =
2198 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2199 SourceLocation(), Method->getType());
2200 QualType ResultType;
2201 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2202 ResultType = Conv->getConversionType().getNonReferenceType();
2203 else
2204 ResultType = Method->getResultType().getNonReferenceType();
2205
2206 CXXMemberCallExpr *CE =
2207 new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2208 ResultType,
Douglas Gregor00b98c22009-11-12 15:31:47 +00002209 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002210 return CE;
2211}
2212
Anders Carlsson0aebc812009-09-09 21:33:21 +00002213Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2214 QualType Ty,
2215 CastExpr::CastKind Kind,
2216 CXXMethodDecl *Method,
2217 ExprArg Arg) {
2218 Expr *From = Arg.takeAs<Expr>();
2219
2220 switch (Kind) {
2221 default: assert(0 && "Unhandled cast kind!");
2222 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002223 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2224
2225 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2226 MultiExprArg(*this, (void **)&From, 1),
2227 CastLoc, ConstructorArgs))
2228 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002229
2230 OwningExprResult Result =
2231 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2232 move_arg(ConstructorArgs));
2233 if (Result.isInvalid())
2234 return ExprError();
2235
2236 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002237 }
2238
2239 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002240 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2241
2242 // Cast to base if needed.
2243 if (PerformObjectArgumentInitialization(From, Method))
2244 return ExprError();
2245
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002246 // Create an implicit call expr that calls it.
2247 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002248 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002249 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002250 }
2251}
2252
Anders Carlsson165a0a02009-05-17 18:41:29 +00002253Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2254 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002255 if (FullExpr)
Mike Stump1eb44332009-09-09 15:08:12 +00002256 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
Anders Carlssonf54741e2009-06-16 03:37:31 +00002257 /*ShouldDestroyTemps=*/true);
Anders Carlsson165a0a02009-05-17 18:41:29 +00002258
Anders Carlssonec773872009-08-25 23:46:41 +00002259
Anders Carlsson165a0a02009-05-17 18:41:29 +00002260 return Owned(FullExpr);
2261}
Douglas Gregore961afb2009-10-22 07:08:30 +00002262
2263/// \brief Determine whether a reference to the given declaration in the
2264/// current context is an implicit member access
2265/// (C++ [class.mfct.non-static]p2).
2266///
2267/// FIXME: Should Objective-C also use this approach?
2268///
2269/// \param SS if non-NULL, the C++ nested-name-specifier that precedes the
2270/// name of the declaration referenced.
2271///
2272/// \param D the declaration being referenced from the current scope.
2273///
2274/// \param NameLoc the location of the name in the source.
2275///
2276/// \param ThisType if the reference to this declaration is an implicit member
2277/// access, will be set to the type of the "this" pointer to be used when
2278/// building that implicit member access.
2279///
2280/// \param MemberType if the reference to this declaration is an implicit
2281/// member access, will be set to the type of the member being referenced
2282/// (for use at the type of the resulting member access expression).
2283///
2284/// \returns true if this is an implicit member reference (in which case
2285/// \p ThisType and \p MemberType will be set), or false if it is not an
2286/// implicit member reference.
2287bool Sema::isImplicitMemberReference(const CXXScopeSpec *SS, NamedDecl *D,
2288 SourceLocation NameLoc, QualType &ThisType,
2289 QualType &MemberType) {
2290 // If this isn't a C++ method, then it isn't an implicit member reference.
2291 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2292 if (!MD || MD->isStatic())
2293 return false;
2294
2295 // C++ [class.mfct.nonstatic]p2:
2296 // [...] if name lookup (3.4.1) resolves the name in the
2297 // id-expression to a nonstatic nontype member of class X or of
2298 // a base class of X, the id-expression is transformed into a
2299 // class member access expression (5.2.5) using (*this) (9.3.2)
2300 // as the postfix-expression to the left of the '.' operator.
2301 DeclContext *Ctx = 0;
2302 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2303 Ctx = FD->getDeclContext();
2304 MemberType = FD->getType();
2305
2306 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
2307 MemberType = RefType->getPointeeType();
2308 else if (!FD->isMutable())
2309 MemberType
2310 = Context.getQualifiedType(MemberType,
2311 Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
2312 } else {
2313 for (OverloadIterator Ovl(D), OvlEnd; Ovl != OvlEnd; ++Ovl) {
2314 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl);
2315 FunctionTemplateDecl *FunTmpl = 0;
2316 if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)))
2317 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2318
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00002319 // FIXME: Do we have to know if there are explicit template arguments?
Douglas Gregore961afb2009-10-22 07:08:30 +00002320 if (Method && !Method->isStatic()) {
2321 Ctx = Method->getParent();
2322 if (isa<CXXMethodDecl>(D) && !FunTmpl)
2323 MemberType = Method->getType();
2324 else
2325 MemberType = Context.OverloadTy;
2326 break;
2327 }
2328 }
2329 }
2330
2331 if (!Ctx || !Ctx->isRecord())
2332 return false;
2333
2334 // Determine whether the declaration(s) we found are actually in a base
2335 // class. If not, this isn't an implicit member reference.
2336 ThisType = MD->getThisType(Context);
Douglas Gregor7a343142009-11-01 17:08:18 +00002337
2338 // If the type of "this" is dependent, we can't tell if the member is in a
2339 // base class or not, so treat this as a dependent implicit member reference.
2340 if (ThisType->isDependentType())
2341 return true;
2342
Douglas Gregore961afb2009-10-22 07:08:30 +00002343 QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2344 QualType ClassType
2345 = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2346 return Context.hasSameType(CtxType, ClassType) ||
2347 IsDerivedFrom(ClassType, CtxType);
2348}
2349