blob: 425fc2d15aa5331d9cc648055a1e77726c3212c0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor124b8782010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-02-16 19:09:40 +000033 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000135
Douglas Gregoredc90502010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000175
176 if (SearchType.isNull() || SearchType->isDependentType() ||
177 Context.hasSameUnqualifiedType(T, SearchType)) {
178 // We found our type!
179
180 return T.getAsOpaquePtr();
181 }
182 }
183
184 // If the name that we found is a class template name, and it is
185 // the same name as the template name in the last part of the
186 // nested-name-specifier (if present) or the object type, then
187 // this is the destructor for that class.
188 // FIXME: This is a workaround until we get real drafting for core
189 // issue 399, for which there isn't even an obvious direction.
190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191 QualType MemberOfType;
192 if (SS.isSet()) {
193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000197 }
198 }
199 if (MemberOfType.isNull())
200 MemberOfType = SearchType;
201
202 if (MemberOfType.isNull())
203 continue;
204
205 // We're referring into a class template specialization. If the
206 // class template we found is the same as the template being
207 // specialized, we found what we are looking for.
208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209 if (ClassTemplateSpecializationDecl *Spec
210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212 Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214 }
215
216 continue;
217 }
218
219 // We're referring to an unresolved class template
220 // specialization. Determine whether we class template we found
221 // is the same as the template being specialized or, if we don't
222 // know which template is being specialized, that it at least
223 // has the same name.
224 if (const TemplateSpecializationType *SpecType
225 = MemberOfType->getAs<TemplateSpecializationType>()) {
226 TemplateName SpecName = SpecType->getTemplateName();
227
228 // The class template we found is the same template being
229 // specialized.
230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232 return MemberOfType.getAsOpaquePtr();
233
234 continue;
235 }
236
237 // The class template we found has the same name as the
238 // (dependent) template name being specialized.
239 if (DependentTemplateName *DepTemplate
240 = SpecName.getAsDependentTemplateName()) {
241 if (DepTemplate->isIdentifier() &&
242 DepTemplate->getIdentifier() == Template->getIdentifier())
243 return MemberOfType.getAsOpaquePtr();
244
245 continue;
246 }
247 }
248 }
249 }
250
251 if (isDependent) {
252 // We didn't find our type, but that's okay: it's dependent
253 // anyway.
254 NestedNameSpecifier *NNS = 0;
255 SourceRange Range;
256 if (SS.isSet()) {
257 NNS = (NestedNameSpecifier *)SS.getScopeRep();
258 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259 } else {
260 NNS = NestedNameSpecifier::Create(Context, &II);
261 Range = SourceRange(NameLoc);
262 }
263
Douglas Gregor107de902010-04-24 15:35:55 +0000264 return CheckTypenameType(ETK_None, NNS, II, Range).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000265 }
266
267 if (ObjectTypePtr)
268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269 << &II;
270 else
271 Diag(NameLoc, diag::err_destructor_class_name);
272
273 return 0;
274}
275
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000276/// \brief Build a C++ typeid expression with a type operand.
277Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
278 SourceLocation TypeidLoc,
279 TypeSourceInfo *Operand,
280 SourceLocation RParenLoc) {
281 // C++ [expr.typeid]p4:
282 // The top-level cv-qualifiers of the lvalue expression or the type-id
283 // that is the operand of typeid are always ignored.
284 // If the type of the type-id is a class type or a reference to a class
285 // type, the class shall be completely-defined.
286 QualType T = Operand->getType().getNonReferenceType();
287 if (T->getAs<RecordType>() &&
288 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
289 return ExprError();
290
291 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
292 Operand,
293 SourceRange(TypeidLoc, RParenLoc)));
294}
295
296/// \brief Build a C++ typeid expression with an expression operand.
297Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
298 SourceLocation TypeidLoc,
299 ExprArg Operand,
300 SourceLocation RParenLoc) {
301 bool isUnevaluatedOperand = true;
302 Expr *E = static_cast<Expr *>(Operand.get());
303 if (E && !E->isTypeDependent()) {
304 QualType T = E->getType();
305 if (const RecordType *RecordT = T->getAs<RecordType>()) {
306 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
307 // C++ [expr.typeid]p3:
308 // [...] If the type of the expression is a class type, the class
309 // shall be completely-defined.
310 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
311 return ExprError();
312
313 // C++ [expr.typeid]p3:
314 // When typeid is applied to an expression other than an lvalue of a
315 // polymorphic class type [...] [the] expression is an unevaluated
316 // operand. [...]
317 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
318 isUnevaluatedOperand = false;
319 }
320
321 // C++ [expr.typeid]p4:
322 // [...] If the type of the type-id is a reference to a possibly
323 // cv-qualified type, the result of the typeid expression refers to a
324 // std::type_info object representing the cv-unqualified referenced
325 // type.
326 if (T.hasQualifiers()) {
327 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
328 E->isLvalue(Context));
329 Operand.release();
330 Operand = Owned(E);
331 }
332 }
333
334 // If this is an unevaluated operand, clear out the set of
335 // declaration references we have been computing and eliminate any
336 // temporaries introduced in its computation.
337 if (isUnevaluatedOperand)
338 ExprEvalContexts.back().Context = Unevaluated;
339
340 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
341 Operand.takeAs<Expr>(),
342 SourceRange(TypeidLoc, RParenLoc)));
343}
344
345/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000346Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000347Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
348 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000349 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000350 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000351 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000352
Chris Lattner572af492008-11-20 05:51:55 +0000353 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000354 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
355 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000356 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000357 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000358 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000359
Sebastian Redlc42e1182008-11-11 11:37:55 +0000360 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000361
362 if (isType) {
363 // The operand is a type; handle it as such.
364 TypeSourceInfo *TInfo = 0;
365 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
366 if (T.isNull())
367 return ExprError();
368
369 if (!TInfo)
370 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000371
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000375 // The operand is an expression.
376 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000377}
378
Steve Naroff1b273c42007-09-16 14:56:35 +0000379/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000380Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000381Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000382 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000384 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
385 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
Chris Lattner50dd2892008-02-26 00:51:44 +0000387
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000388/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
389Action::OwningExprResult
390Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
391 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
392}
393
Chris Lattner50dd2892008-02-26 00:51:44 +0000394/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395Action::OwningExprResult
396Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000397 Expr *Ex = E.takeAs<Expr>();
398 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
399 return ExprError();
400 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
401}
402
403/// CheckCXXThrowOperand - Validate the operand of a throw.
404bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
405 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000406 // A throw-expression initializes a temporary object, called the exception
407 // object, the type of which is determined by removing any top-level
408 // cv-qualifiers from the static type of the operand of throw and adjusting
409 // the type from "array of T" or "function returning T" to "pointer to T"
410 // or "pointer to function returning T", [...]
411 if (E->getType().hasQualifiers())
412 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
413 E->isLvalue(Context) == Expr::LV_Valid);
414
Sebastian Redl972041f2009-04-27 20:27:31 +0000415 DefaultFunctionArrayConversion(E);
416
417 // If the type of the exception would be an incomplete type or a pointer
418 // to an incomplete type other than (cv) void the program is ill-formed.
419 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000420 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000421 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000422 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000423 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000424 }
425 if (!isPointer || !Ty->isVoidType()) {
426 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000427 PDiag(isPointer ? diag::err_throw_incomplete_ptr
428 : diag::err_throw_incomplete)
429 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000430 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000431
Douglas Gregorbf422f92010-04-15 18:05:39 +0000432 if (RequireNonAbstractType(ThrowLoc, E->getType(),
433 PDiag(diag::err_throw_abstract_type)
434 << E->getSourceRange()))
435 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000436 }
437
John McCallac418162010-04-22 01:10:34 +0000438 // Initialize the exception result. This implicitly weeds out
439 // abstract types or types with inaccessible copy constructors.
440 InitializedEntity Entity =
441 InitializedEntity::InitializeException(ThrowLoc, E->getType());
442 OwningExprResult Res = PerformCopyInitialization(Entity,
443 SourceLocation(),
444 Owned(E));
445 if (Res.isInvalid())
446 return true;
447 E = Res.takeAs<Expr>();
Sebastian Redl972041f2009-04-27 20:27:31 +0000448 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000449}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000450
Sebastian Redlf53597f2009-03-15 17:47:39 +0000451Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000452 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
453 /// is a non-lvalue expression whose value is the address of the object for
454 /// which the function is called.
455
Sebastian Redlf53597f2009-03-15 17:47:39 +0000456 if (!isa<FunctionDecl>(CurContext))
457 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000458
459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
460 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000462 MD->getThisType(Context),
463 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000464
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000466}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000467
468/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
469/// Can be interpreted either as function-style casting ("int(x)")
470/// or class type construction ("ClassType(x,y,z)")
471/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000473Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
474 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000476 SourceLocation *CommaLocs,
477 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000478 if (!TypeRep)
479 return ExprError();
480
John McCall9d125032010-01-15 18:39:57 +0000481 TypeSourceInfo *TInfo;
482 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
483 if (!TInfo)
484 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485 unsigned NumExprs = exprs.size();
486 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000487 SourceLocation TyBeginLoc = TypeRange.getBegin();
488 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
489
Sebastian Redlf53597f2009-03-15 17:47:39 +0000490 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000491 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000492 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
494 return Owned(CXXUnresolvedConstructExpr::Create(Context,
495 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000496 LParenLoc,
497 Exprs, NumExprs,
498 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000499 }
500
Anders Carlssonbb60a502009-08-27 03:53:50 +0000501 if (Ty->isArrayType())
502 return ExprError(Diag(TyBeginLoc,
503 diag::err_value_init_for_array_type) << FullRange);
504 if (!Ty->isVoidType() &&
505 RequireCompleteType(TyBeginLoc, Ty,
506 PDiag(diag::err_invalid_incomplete_type_use)
507 << FullRange))
508 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000509
Anders Carlssonbb60a502009-08-27 03:53:50 +0000510 if (RequireNonAbstractType(TyBeginLoc, Ty,
511 diag::err_allocation_of_abstract_type))
512 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000513
514
Douglas Gregor506ae412009-01-16 18:33:17 +0000515 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000516 // If the expression list is a single expression, the type conversion
517 // expression is equivalent (in definedness, and if defined in meaning) to the
518 // corresponding cast expression.
519 //
520 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000521 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000522 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000523 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
524 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000525 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000526
527 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000528
529 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000530 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000531 Exprs[0], BasePath,
532 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000533 }
534
Ted Kremenek6217b802009-07-29 21:53:49 +0000535 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000536 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000537
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000539 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000540 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
541 InitializationKind Kind
542 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
543 LParenLoc, RParenLoc)
544 : InitializationKind::CreateValue(TypeRange.getBegin(),
545 LParenLoc, RParenLoc);
546 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
547 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
548 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000549
Eli Friedman6997aae2010-01-31 20:58:15 +0000550 // FIXME: Improve AST representation?
551 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000552 }
553
554 // Fall through to value-initialize an object of class type that
555 // doesn't have a user-declared default constructor.
556 }
557
558 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000559 // If the expression list specifies more than a single value, the type shall
560 // be a class with a suitably declared constructor.
561 //
562 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000563 return ExprError(Diag(CommaLocs[0],
564 diag::err_builtin_func_cast_more_than_one_arg)
565 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000566
567 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000568 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000569 // The expression T(), where T is a simple-type-specifier for a non-array
570 // complete object type or the (possibly cv-qualified) void type, creates an
571 // rvalue of the specified type, which is value-initialized.
572 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 exprs.release();
574 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000575}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000576
577
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000578/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
579/// @code new (memory) int[size][4] @endcode
580/// or
581/// @code ::new Foo(23, "hello") @endcode
582/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000583Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000584Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000585 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000586 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000587 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000588 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000589 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000590 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000591 // If the specified type is an array, unwrap it and save the expression.
592 if (D.getNumTypeObjects() > 0 &&
593 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
594 DeclaratorChunk &Chunk = D.getTypeObject(0);
595 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000596 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
597 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000598 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000599 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
600 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000601
602 if (ParenTypeId) {
603 // Can't have dynamic array size when the type-id is in parentheses.
604 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
605 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
606 !NumElts->isIntegerConstantExpr(Context)) {
607 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
608 << NumElts->getSourceRange();
609 return ExprError();
610 }
611 }
612
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000613 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000614 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000615 }
616
Douglas Gregor043cad22009-09-11 00:18:58 +0000617 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000618 if (ArraySize) {
619 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000620 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
621 break;
622
623 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
624 if (Expr *NumElts = (Expr *)Array.NumElts) {
625 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
626 !NumElts->isIntegerConstantExpr(Context)) {
627 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
628 << NumElts->getSourceRange();
629 return ExprError();
630 }
631 }
632 }
633 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000634
John McCalla93c9342009-12-07 02:54:59 +0000635 //FIXME: Store TypeSourceInfo in CXXNew expression.
636 TypeSourceInfo *TInfo = 0;
637 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000638 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000639 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000640
Mike Stump1eb44332009-09-09 15:08:12 +0000641 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000642 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000643 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000644 PlacementRParen,
645 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000646 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000647 D.getSourceRange().getBegin(),
648 D.getSourceRange(),
649 Owned(ArraySize),
650 ConstructorLParen,
651 move(ConstructorArgs),
652 ConstructorRParen);
653}
654
Mike Stump1eb44332009-09-09 15:08:12 +0000655Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000656Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
657 SourceLocation PlacementLParen,
658 MultiExprArg PlacementArgs,
659 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000660 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000661 QualType AllocType,
662 SourceLocation TypeLoc,
663 SourceRange TypeRange,
664 ExprArg ArraySizeE,
665 SourceLocation ConstructorLParen,
666 MultiExprArg ConstructorArgs,
667 SourceLocation ConstructorRParen) {
668 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000669 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000670
Douglas Gregor3433cf72009-05-21 00:00:09 +0000671 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000672
673 // That every array dimension except the first is constant was already
674 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000675
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000676 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
677 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000678 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000679 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680 QualType SizeType = ArraySize->getType();
681 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683 diag::err_array_size_not_integral)
684 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000685 // Let's see if this is a constant < 0. If so, we reject it out of hand.
686 // We don't care about special rules, so we tell the machinery it's not
687 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000688 if (!ArraySize->isValueDependent()) {
689 llvm::APSInt Value;
690 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
691 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000692 llvm::APInt::getNullValue(Value.getBitWidth()),
693 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000694 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
695 diag::err_typecheck_negative_array_size)
696 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000697 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000698 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000699
Eli Friedman73c39ab2009-10-20 08:27:19 +0000700 ImpCastExprToType(ArraySize, Context.getSizeType(),
701 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000702 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000703
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000704 FunctionDecl *OperatorNew = 0;
705 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000706 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
707 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000708
Sebastian Redl28507842009-02-26 14:39:58 +0000709 if (!AllocType->isDependentType() &&
710 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
711 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000712 SourceRange(PlacementLParen, PlacementRParen),
713 UseGlobal, AllocType, ArraySize, PlaceArgs,
714 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000715 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000716 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000717 if (OperatorNew) {
718 // Add default arguments, if any.
719 const FunctionProtoType *Proto =
720 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000721 VariadicCallType CallType =
722 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000723
724 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
725 Proto, 1, PlaceArgs, NumPlaceArgs,
726 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000727 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000728
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000729 NumPlaceArgs = AllPlaceArgs.size();
730 if (NumPlaceArgs > 0)
731 PlaceArgs = &AllPlaceArgs[0];
732 }
733
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000734 bool Init = ConstructorLParen.isValid();
735 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000736 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000737 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
738 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000739 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
740
Anders Carlsson48c95012010-05-03 15:45:23 +0000741 // Array 'new' can't have any initializers.
742 if (NumConsArgs && ArraySize) {
743 SourceRange InitRange(ConsArgs[0]->getLocStart(),
744 ConsArgs[NumConsArgs - 1]->getLocEnd());
745
746 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
747 return ExprError();
748 }
749
Douglas Gregor99a2e602009-12-16 01:38:02 +0000750 if (!AllocType->isDependentType() &&
751 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
752 // C++0x [expr.new]p15:
753 // A new-expression that creates an object of type T initializes that
754 // object as follows:
755 InitializationKind Kind
756 // - If the new-initializer is omitted, the object is default-
757 // initialized (8.5); if no initialization is performed,
758 // the object has indeterminate value
759 = !Init? InitializationKind::CreateDefault(TypeLoc)
760 // - Otherwise, the new-initializer is interpreted according to the
761 // initialization rules of 8.5 for direct-initialization.
762 : InitializationKind::CreateDirect(TypeLoc,
763 ConstructorLParen,
764 ConstructorRParen);
765
Douglas Gregor99a2e602009-12-16 01:38:02 +0000766 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000767 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000768 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000769 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
770 move(ConstructorArgs));
771 if (FullInit.isInvalid())
772 return ExprError();
773
774 // FullInit is our initializer; walk through it to determine if it's a
775 // constructor call, which CXXNewExpr handles directly.
776 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
777 if (CXXBindTemporaryExpr *Binder
778 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
779 FullInitExpr = Binder->getSubExpr();
780 if (CXXConstructExpr *Construct
781 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
782 Constructor = Construct->getConstructor();
783 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
784 AEnd = Construct->arg_end();
785 A != AEnd; ++A)
786 ConvertedConstructorArgs.push_back(A->Retain());
787 } else {
788 // Take the converted initializer.
789 ConvertedConstructorArgs.push_back(FullInit.release());
790 }
791 } else {
792 // No initialization required.
793 }
794
795 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000796 NumConsArgs = ConvertedConstructorArgs.size();
797 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000798 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000799
Douglas Gregor6d908702010-02-26 05:06:18 +0000800 // Mark the new and delete operators as referenced.
801 if (OperatorNew)
802 MarkDeclarationReferenced(StartLoc, OperatorNew);
803 if (OperatorDelete)
804 MarkDeclarationReferenced(StartLoc, OperatorDelete);
805
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000806 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000807
Sebastian Redlf53597f2009-03-15 17:47:39 +0000808 PlacementArgs.release();
809 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000810 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000811 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
812 PlaceArgs, NumPlaceArgs, ParenTypeId,
813 ArraySize, Constructor, Init,
814 ConsArgs, NumConsArgs, OperatorDelete,
815 ResultType, StartLoc,
816 Init ? ConstructorRParen :
817 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000818}
819
820/// CheckAllocatedType - Checks that a type is suitable as the allocated type
821/// in a new-expression.
822/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000823bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000824 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000825 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
826 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000827 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000828 return Diag(Loc, diag::err_bad_new_type)
829 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000830 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000831 return Diag(Loc, diag::err_bad_new_type)
832 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000833 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000834 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000835 PDiag(diag::err_new_incomplete_type)
836 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000837 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000838 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000839 diag::err_allocation_of_abstract_type))
840 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000841
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000842 return false;
843}
844
Douglas Gregor6d908702010-02-26 05:06:18 +0000845/// \brief Determine whether the given function is a non-placement
846/// deallocation function.
847static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
848 if (FD->isInvalidDecl())
849 return false;
850
851 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
852 return Method->isUsualDeallocationFunction();
853
854 return ((FD->getOverloadedOperator() == OO_Delete ||
855 FD->getOverloadedOperator() == OO_Array_Delete) &&
856 FD->getNumParams() == 1);
857}
858
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000859/// FindAllocationFunctions - Finds the overloads of operator new and delete
860/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000861bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
862 bool UseGlobal, QualType AllocType,
863 bool IsArray, Expr **PlaceArgs,
864 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000865 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000866 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000867 // --- Choosing an allocation function ---
868 // C++ 5.3.4p8 - 14 & 18
869 // 1) If UseGlobal is true, only look in the global scope. Else, also look
870 // in the scope of the allocated class.
871 // 2) If an array size is given, look for operator new[], else look for
872 // operator new.
873 // 3) The first argument is always size_t. Append the arguments from the
874 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000875
876 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
877 // We don't care about the actual value of this argument.
878 // FIXME: Should the Sema create the expression and embed it in the syntax
879 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000880 IntegerLiteral Size(llvm::APInt::getNullValue(
881 Context.Target.getPointerWidth(0)),
882 Context.getSizeType(),
883 SourceLocation());
884 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000885 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
886
Douglas Gregor6d908702010-02-26 05:06:18 +0000887 // C++ [expr.new]p8:
888 // If the allocated type is a non-array type, the allocation
889 // function’s name is operator new and the deallocation function’s
890 // name is operator delete. If the allocated type is an array
891 // type, the allocation function’s name is operator new[] and the
892 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000893 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
894 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000895 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
896 IsArray ? OO_Array_Delete : OO_Delete);
897
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000898 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000899 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000900 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000901 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000902 AllocArgs.size(), Record, /*AllowMissing=*/true,
903 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000904 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000905 }
906 if (!OperatorNew) {
907 // Didn't find a member overload. Look for a global one.
908 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000909 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000910 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000911 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
912 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000913 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000914 }
915
John McCall9c82afc2010-04-20 02:18:25 +0000916 // We don't need an operator delete if we're running under
917 // -fno-exceptions.
918 if (!getLangOptions().Exceptions) {
919 OperatorDelete = 0;
920 return false;
921 }
922
Anders Carlssond9583892009-05-31 20:26:12 +0000923 // FindAllocationOverload can change the passed in arguments, so we need to
924 // copy them back.
925 if (NumPlaceArgs > 0)
926 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregor6d908702010-02-26 05:06:18 +0000928 // C++ [expr.new]p19:
929 //
930 // If the new-expression begins with a unary :: operator, the
931 // deallocation function’s name is looked up in the global
932 // scope. Otherwise, if the allocated type is a class type T or an
933 // array thereof, the deallocation function’s name is looked up in
934 // the scope of T. If this lookup fails to find the name, or if
935 // the allocated type is not a class type or array thereof, the
936 // deallocation function’s name is looked up in the global scope.
937 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
938 if (AllocType->isRecordType() && !UseGlobal) {
939 CXXRecordDecl *RD
940 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
941 LookupQualifiedName(FoundDelete, RD);
942 }
John McCall90c8c572010-03-18 08:19:33 +0000943 if (FoundDelete.isAmbiguous())
944 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000945
946 if (FoundDelete.empty()) {
947 DeclareGlobalNewDelete();
948 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
949 }
950
951 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000952
953 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
954
John McCall90c8c572010-03-18 08:19:33 +0000955 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000956 // C++ [expr.new]p20:
957 // A declaration of a placement deallocation function matches the
958 // declaration of a placement allocation function if it has the
959 // same number of parameters and, after parameter transformations
960 // (8.3.5), all parameter types except the first are
961 // identical. [...]
962 //
963 // To perform this comparison, we compute the function type that
964 // the deallocation function should have, and use that type both
965 // for template argument deduction and for comparison purposes.
966 QualType ExpectedFunctionType;
967 {
968 const FunctionProtoType *Proto
969 = OperatorNew->getType()->getAs<FunctionProtoType>();
970 llvm::SmallVector<QualType, 4> ArgTypes;
971 ArgTypes.push_back(Context.VoidPtrTy);
972 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
973 ArgTypes.push_back(Proto->getArgType(I));
974
975 ExpectedFunctionType
976 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
977 ArgTypes.size(),
978 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000979 0, false, false, 0, 0,
980 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000981 }
982
983 for (LookupResult::iterator D = FoundDelete.begin(),
984 DEnd = FoundDelete.end();
985 D != DEnd; ++D) {
986 FunctionDecl *Fn = 0;
987 if (FunctionTemplateDecl *FnTmpl
988 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
989 // Perform template argument deduction to try to match the
990 // expected function type.
991 TemplateDeductionInfo Info(Context, StartLoc);
992 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
993 continue;
994 } else
995 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
996
997 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +0000998 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000999 }
1000 } else {
1001 // C++ [expr.new]p20:
1002 // [...] Any non-placement deallocation function matches a
1003 // non-placement allocation function. [...]
1004 for (LookupResult::iterator D = FoundDelete.begin(),
1005 DEnd = FoundDelete.end();
1006 D != DEnd; ++D) {
1007 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1008 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001009 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001010 }
1011 }
1012
1013 // C++ [expr.new]p20:
1014 // [...] If the lookup finds a single matching deallocation
1015 // function, that function will be called; otherwise, no
1016 // deallocation function will be called.
1017 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001018 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001019
1020 // C++0x [expr.new]p20:
1021 // If the lookup finds the two-parameter form of a usual
1022 // deallocation function (3.7.4.2) and that function, considered
1023 // as a placement deallocation function, would have been
1024 // selected as a match for the allocation function, the program
1025 // is ill-formed.
1026 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1027 isNonPlacementDeallocationFunction(OperatorDelete)) {
1028 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1029 << SourceRange(PlaceArgs[0]->getLocStart(),
1030 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1031 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1032 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001033 } else {
1034 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001035 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001036 }
1037 }
1038
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001039 return false;
1040}
1041
Sebastian Redl7f662392008-12-04 22:20:51 +00001042/// FindAllocationOverload - Find an fitting overload for the allocation
1043/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001044bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1045 DeclarationName Name, Expr** Args,
1046 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001047 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001048 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1049 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001050 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001051 if (AllowMissing)
1052 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001053 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001054 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001055 }
1056
John McCall90c8c572010-03-18 08:19:33 +00001057 if (R.isAmbiguous())
1058 return true;
1059
1060 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001061
John McCall5769d612010-02-08 23:07:23 +00001062 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001063 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1064 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001065 // Even member operator new/delete are implicitly treated as
1066 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001067 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001068
John McCall9aa472c2010-03-19 07:35:19 +00001069 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1070 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001071 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1072 Candidates,
1073 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001074 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001075 }
1076
John McCall9aa472c2010-03-19 07:35:19 +00001077 FunctionDecl *Fn = cast<FunctionDecl>(D);
1078 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001079 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001080 }
1081
1082 // Do the resolution.
1083 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001084 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001085 case OR_Success: {
1086 // Got one!
1087 FunctionDecl *FnDecl = Best->Function;
1088 // The first argument is size_t, and the first parameter must be size_t,
1089 // too. This is checked on declaration and can be assumed. (It can't be
1090 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001091 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001092 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1093 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001094 OwningExprResult Result
1095 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1096 FnDecl->getParamDecl(i)),
1097 SourceLocation(),
1098 Owned(Args[i]->Retain()));
1099 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001100 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001101
1102 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001103 }
1104 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001105 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001106 return false;
1107 }
1108
1109 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001110 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001111 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001112 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001113 return true;
1114
1115 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001116 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001117 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001118 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001119 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001120
1121 case OR_Deleted:
1122 Diag(StartLoc, diag::err_ovl_deleted_call)
1123 << Best->Function->isDeleted()
1124 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001125 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001126 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001127 }
1128 assert(false && "Unreachable, bad result from BestViableFunction");
1129 return true;
1130}
1131
1132
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001133/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1134/// delete. These are:
1135/// @code
1136/// void* operator new(std::size_t) throw(std::bad_alloc);
1137/// void* operator new[](std::size_t) throw(std::bad_alloc);
1138/// void operator delete(void *) throw();
1139/// void operator delete[](void *) throw();
1140/// @endcode
1141/// Note that the placement and nothrow forms of new are *not* implicitly
1142/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001143void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001144 if (GlobalNewDeleteDeclared)
1145 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001146
1147 // C++ [basic.std.dynamic]p2:
1148 // [...] The following allocation and deallocation functions (18.4) are
1149 // implicitly declared in global scope in each translation unit of a
1150 // program
1151 //
1152 // void* operator new(std::size_t) throw(std::bad_alloc);
1153 // void* operator new[](std::size_t) throw(std::bad_alloc);
1154 // void operator delete(void*) throw();
1155 // void operator delete[](void*) throw();
1156 //
1157 // These implicit declarations introduce only the function names operator
1158 // new, operator new[], operator delete, operator delete[].
1159 //
1160 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1161 // "std" or "bad_alloc" as necessary to form the exception specification.
1162 // However, we do not make these implicit declarations visible to name
1163 // lookup.
1164 if (!StdNamespace) {
1165 // The "std" namespace has not yet been defined, so build one implicitly.
1166 StdNamespace = NamespaceDecl::Create(Context,
1167 Context.getTranslationUnitDecl(),
1168 SourceLocation(),
1169 &PP.getIdentifierTable().get("std"));
1170 StdNamespace->setImplicit(true);
1171 }
1172
1173 if (!StdBadAlloc) {
1174 // The "std::bad_alloc" class has not yet been declared, so build it
1175 // implicitly.
1176 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1177 StdNamespace,
1178 SourceLocation(),
1179 &PP.getIdentifierTable().get("bad_alloc"),
1180 SourceLocation(), 0);
1181 StdBadAlloc->setImplicit(true);
1182 }
1183
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001184 GlobalNewDeleteDeclared = true;
1185
1186 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1187 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001188 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001189
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001190 DeclareGlobalAllocationFunction(
1191 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001192 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001193 DeclareGlobalAllocationFunction(
1194 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001195 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001196 DeclareGlobalAllocationFunction(
1197 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1198 Context.VoidTy, VoidPtr);
1199 DeclareGlobalAllocationFunction(
1200 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1201 Context.VoidTy, VoidPtr);
1202}
1203
1204/// DeclareGlobalAllocationFunction - Declares a single implicit global
1205/// allocation function if it doesn't already exist.
1206void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001207 QualType Return, QualType Argument,
1208 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001209 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1210
1211 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001212 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001213 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001215 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001216 // Only look at non-template functions, as it is the predefined,
1217 // non-templated allocation function we are trying to declare here.
1218 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1219 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001220 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001221 Func->getParamDecl(0)->getType().getUnqualifiedType());
1222 // FIXME: Do we need to check for default arguments here?
1223 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1224 return;
1225 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001226 }
1227 }
1228
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001229 QualType BadAllocType;
1230 bool HasBadAllocExceptionSpec
1231 = (Name.getCXXOverloadedOperator() == OO_New ||
1232 Name.getCXXOverloadedOperator() == OO_Array_New);
1233 if (HasBadAllocExceptionSpec) {
1234 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1235 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1236 }
1237
1238 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1239 true, false,
1240 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001241 &BadAllocType,
1242 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001243 FunctionDecl *Alloc =
1244 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001245 FnType, /*TInfo=*/0, FunctionDecl::None,
1246 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001247 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001248
1249 if (AddMallocAttr)
1250 Alloc->addAttr(::new (Context) MallocAttr());
1251
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001252 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001253 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001254 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001255 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001256 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001257
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001258 // FIXME: Also add this declaration to the IdentifierResolver, but
1259 // make sure it is at the end of the chain to coincide with the
1260 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001261 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001262}
1263
Anders Carlsson78f74552009-11-15 18:45:20 +00001264bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1265 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001266 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001267 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001268 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001269 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001270
John McCalla24dc2e2009-11-17 02:14:36 +00001271 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001272 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001273
1274 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1275 F != FEnd; ++F) {
1276 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1277 if (Delete->isUsualDeallocationFunction()) {
1278 Operator = Delete;
1279 return false;
1280 }
1281 }
1282
1283 // We did find operator delete/operator delete[] declarations, but
1284 // none of them were suitable.
1285 if (!Found.empty()) {
1286 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1287 << Name << RD;
1288
1289 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1290 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001291 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001292 << Name;
1293 }
1294
1295 return true;
1296 }
1297
1298 // Look for a global declaration.
1299 DeclareGlobalNewDelete();
1300 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1301
1302 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1303 Expr* DeallocArgs[1];
1304 DeallocArgs[0] = &Null;
1305 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1306 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1307 Operator))
1308 return true;
1309
1310 assert(Operator && "Did not find a deallocation function!");
1311 return false;
1312}
1313
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001314/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1315/// @code ::delete ptr; @endcode
1316/// or
1317/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001318Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001319Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001320 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001321 // C++ [expr.delete]p1:
1322 // The operand shall have a pointer type, or a class type having a single
1323 // conversion function to a pointer type. The result has type void.
1324 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001325 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1326
Anders Carlssond67c4c32009-08-16 20:29:29 +00001327 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Sebastian Redlf53597f2009-03-15 17:47:39 +00001329 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001330 if (!Ex->isTypeDependent()) {
1331 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001332
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001333 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001334 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1335
Fariborz Jahanian53462782009-09-11 21:44:33 +00001336 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001337 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001338 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001339 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001340 NamedDecl *D = I.getDecl();
1341 if (isa<UsingShadowDecl>(D))
1342 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1343
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001344 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001345 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001346 continue;
1347
John McCall32daa422010-03-31 01:36:47 +00001348 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001349
1350 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1351 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1352 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001353 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001354 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001355 if (ObjectPtrConversions.size() == 1) {
1356 // We have a single conversion to a pointer-to-object type. Perform
1357 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001358 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001359 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001360 if (!PerformImplicitConversion(Ex,
1361 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001362 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001363 Operand = Owned(Ex);
1364 Type = Ex->getType();
1365 }
1366 }
1367 else if (ObjectPtrConversions.size() > 1) {
1368 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1369 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001370 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1371 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001372 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001373 }
Sebastian Redl28507842009-02-26 14:39:58 +00001374 }
1375
Sebastian Redlf53597f2009-03-15 17:47:39 +00001376 if (!Type->isPointerType())
1377 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1378 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001379
Ted Kremenek6217b802009-07-29 21:53:49 +00001380 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001381 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001382 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1383 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001384 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001385 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001386 PDiag(diag::warn_delete_incomplete)
1387 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001388 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001389
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001390 // C++ [expr.delete]p2:
1391 // [Note: a pointer to a const type can be the operand of a
1392 // delete-expression; it is not necessary to cast away the constness
1393 // (5.2.11) of the pointer expression before it is used as the operand
1394 // of the delete-expression. ]
1395 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1396 CastExpr::CK_NoOp);
1397
1398 // Update the operand.
1399 Operand.take();
1400 Operand = ExprArg(*this, Ex);
1401
Anders Carlssond67c4c32009-08-16 20:29:29 +00001402 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1403 ArrayForm ? OO_Array_Delete : OO_Delete);
1404
Anders Carlsson78f74552009-11-15 18:45:20 +00001405 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1406 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1407
1408 if (!UseGlobal &&
1409 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001410 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001411
Anders Carlsson78f74552009-11-15 18:45:20 +00001412 if (!RD->hasTrivialDestructor())
1413 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001414 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001415 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001416 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001417
Anders Carlssond67c4c32009-08-16 20:29:29 +00001418 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001419 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001420 DeclareGlobalNewDelete();
1421 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001422 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001423 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001424 OperatorDelete))
1425 return ExprError();
1426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
John McCall9c82afc2010-04-20 02:18:25 +00001428 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1429
Sebastian Redl28507842009-02-26 14:39:58 +00001430 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001431 }
1432
Sebastian Redlf53597f2009-03-15 17:47:39 +00001433 Operand.release();
1434 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001435 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001436}
1437
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001438/// \brief Check the use of the given variable as a C++ condition in an if,
1439/// while, do-while, or switch statement.
1440Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1441 QualType T = ConditionVar->getType();
1442
1443 // C++ [stmt.select]p2:
1444 // The declarator shall not specify a function or an array.
1445 if (T->isFunctionType())
1446 return ExprError(Diag(ConditionVar->getLocation(),
1447 diag::err_invalid_use_of_function_type)
1448 << ConditionVar->getSourceRange());
1449 else if (T->isArrayType())
1450 return ExprError(Diag(ConditionVar->getLocation(),
1451 diag::err_invalid_use_of_array_type)
1452 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001453
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001454 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1455 ConditionVar->getLocation(),
1456 ConditionVar->getType().getNonReferenceType()));
1457}
1458
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001459/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1460bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1461 // C++ 6.4p4:
1462 // The value of a condition that is an initialized declaration in a statement
1463 // other than a switch statement is the value of the declared variable
1464 // implicitly converted to type bool. If that conversion is ill-formed, the
1465 // program is ill-formed.
1466 // The value of a condition that is an expression is the value of the
1467 // expression, implicitly converted to bool.
1468 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001469 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001470}
Douglas Gregor77a52232008-09-12 00:47:35 +00001471
1472/// Helper function to determine whether this is the (deprecated) C++
1473/// conversion from a string literal to a pointer to non-const char or
1474/// non-const wchar_t (for narrow and wide string literals,
1475/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001476bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001477Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1478 // Look inside the implicit cast, if it exists.
1479 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1480 From = Cast->getSubExpr();
1481
1482 // A string literal (2.13.4) that is not a wide string literal can
1483 // be converted to an rvalue of type "pointer to char"; a wide
1484 // string literal can be converted to an rvalue of type "pointer
1485 // to wchar_t" (C++ 4.2p2).
1486 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001487 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001488 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001489 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001490 // This conversion is considered only when there is an
1491 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001492 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001493 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1494 (!StrLit->isWide() &&
1495 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1496 ToPointeeType->getKind() == BuiltinType::Char_S))))
1497 return true;
1498 }
1499
1500 return false;
1501}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001502
Douglas Gregorba70ab62010-04-16 22:17:36 +00001503static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1504 SourceLocation CastLoc,
1505 QualType Ty,
1506 CastExpr::CastKind Kind,
1507 CXXMethodDecl *Method,
1508 Sema::ExprArg Arg) {
1509 Expr *From = Arg.takeAs<Expr>();
1510
1511 switch (Kind) {
1512 default: assert(0 && "Unhandled cast kind!");
1513 case CastExpr::CK_ConstructorConversion: {
1514 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1515
1516 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1517 Sema::MultiExprArg(S, (void **)&From, 1),
1518 CastLoc, ConstructorArgs))
1519 return S.ExprError();
1520
1521 Sema::OwningExprResult Result =
1522 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1523 move_arg(ConstructorArgs));
1524 if (Result.isInvalid())
1525 return S.ExprError();
1526
1527 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1528 }
1529
1530 case CastExpr::CK_UserDefinedConversion: {
1531 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1532
1533 // Create an implicit call expr that calls it.
1534 // FIXME: pass the FoundDecl for the user-defined conversion here
1535 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1536 return S.MaybeBindToTemporary(CE);
1537 }
1538 }
1539}
1540
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001541/// PerformImplicitConversion - Perform an implicit conversion of the
1542/// expression From to the type ToType using the pre-computed implicit
1543/// conversion sequence ICS. Returns true if there was an error, false
1544/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001545/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001546/// used in the error message.
1547bool
1548Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1549 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001550 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001551 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001552 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001553 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001554 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001555 return true;
1556 break;
1557
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001558 case ImplicitConversionSequence::UserDefinedConversion: {
1559
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001560 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1561 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001562 QualType BeforeToType;
1563 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001564 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001565
1566 // If the user-defined conversion is specified by a conversion function,
1567 // the initial standard conversion sequence converts the source type to
1568 // the implicit object parameter of the conversion function.
1569 BeforeToType = Context.getTagDeclType(Conv->getParent());
1570 } else if (const CXXConstructorDecl *Ctor =
1571 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001572 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001573 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001574 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001575 // If the user-defined conversion is specified by a constructor, the
1576 // initial standard conversion sequence converts the source type to the
1577 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001578 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1579 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001580 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001581 else
1582 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001583 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001584 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001585 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001586 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001587 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001588 return true;
1589 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001590
Anders Carlsson0aebc812009-09-09 21:33:21 +00001591 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001592 = BuildCXXCastArgument(*this,
1593 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001594 ToType.getNonReferenceType(),
1595 CastKind, cast<CXXMethodDecl>(FD),
1596 Owned(From));
1597
1598 if (CastArg.isInvalid())
1599 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001600
1601 From = CastArg.takeAs<Expr>();
1602
Eli Friedmand8889622009-11-27 04:41:50 +00001603 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001604 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001605 }
John McCall1d318332010-01-12 00:44:57 +00001606
1607 case ImplicitConversionSequence::AmbiguousConversion:
1608 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1609 PDiag(diag::err_typecheck_ambiguous_condition)
1610 << From->getSourceRange());
1611 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001612
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001613 case ImplicitConversionSequence::EllipsisConversion:
1614 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001615 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001616
1617 case ImplicitConversionSequence::BadConversion:
1618 return true;
1619 }
1620
1621 // Everything went well.
1622 return false;
1623}
1624
1625/// PerformImplicitConversion - Perform an implicit conversion of the
1626/// expression From to the type ToType by following the standard
1627/// conversion sequence SCS. Returns true if there was an error, false
1628/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001629/// expression. Flavor is the context in which we're performing this
1630/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001631bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001632Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001633 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001634 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001635 // Overall FIXME: we are recomputing too many types here and doing far too
1636 // much extra work. What this means is that we need to keep track of more
1637 // information that is computed when we try the implicit conversion initially,
1638 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001639 QualType FromType = From->getType();
1640
Douglas Gregor225c41e2008-11-03 19:09:14 +00001641 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001642 // FIXME: When can ToType be a reference type?
1643 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001644 if (SCS.Second == ICK_Derived_To_Base) {
1645 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1646 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1647 MultiExprArg(*this, (void **)&From, 1),
1648 /*FIXME:ConstructLoc*/SourceLocation(),
1649 ConstructorArgs))
1650 return true;
1651 OwningExprResult FromResult =
1652 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1653 ToType, SCS.CopyConstructor,
1654 move_arg(ConstructorArgs));
1655 if (FromResult.isInvalid())
1656 return true;
1657 From = FromResult.takeAs<Expr>();
1658 return false;
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660 OwningExprResult FromResult =
1661 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1662 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001663 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001665 if (FromResult.isInvalid())
1666 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001668 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001669 return false;
1670 }
1671
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001672 // Resolve overloaded function references.
1673 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1674 DeclAccessPair Found;
1675 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1676 true, Found);
1677 if (!Fn)
1678 return true;
1679
1680 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1681 return true;
1682
1683 From = FixOverloadedFunctionReference(From, Found, Fn);
1684 FromType = From->getType();
1685 }
1686
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001687 // Perform the first implicit conversion.
1688 switch (SCS.First) {
1689 case ICK_Identity:
1690 case ICK_Lvalue_To_Rvalue:
1691 // Nothing to do.
1692 break;
1693
1694 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001695 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001696 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001697 break;
1698
1699 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001700 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001701 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001702 break;
1703
1704 default:
1705 assert(false && "Improper first standard conversion");
1706 break;
1707 }
1708
1709 // Perform the second implicit conversion
1710 switch (SCS.Second) {
1711 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001712 // If both sides are functions (or pointers/references to them), there could
1713 // be incompatible exception declarations.
1714 if (CheckExceptionSpecCompatibility(From, ToType))
1715 return true;
1716 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001717 break;
1718
Douglas Gregor43c79c22009-12-09 00:47:37 +00001719 case ICK_NoReturn_Adjustment:
1720 // If both sides are functions (or pointers/references to them), there could
1721 // be incompatible exception declarations.
1722 if (CheckExceptionSpecCompatibility(From, ToType))
1723 return true;
1724
1725 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1726 CastExpr::CK_NoOp);
1727 break;
1728
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001729 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001730 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001731 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1732 break;
1733
1734 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001735 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001736 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1737 break;
1738
1739 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001740 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001741 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1742 break;
1743
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001744 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001745 if (ToType->isFloatingType())
1746 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1747 else
1748 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1749 break;
1750
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001751 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001752 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1753 break;
1754
Douglas Gregorf9201e02009-02-11 23:02:49 +00001755 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001756 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001757 break;
1758
Anders Carlsson61faec12009-09-12 04:46:44 +00001759 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001760 if (SCS.IncompatibleObjC) {
1761 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001762 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001763 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001764 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001765 << From->getSourceRange();
1766 }
1767
Anders Carlsson61faec12009-09-12 04:46:44 +00001768
1769 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001770 CXXBaseSpecifierArray BasePath;
1771 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001772 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001773 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001774 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001775 }
1776
1777 case ICK_Pointer_Member: {
1778 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001779 CXXBaseSpecifierArray BasePath;
1780 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1781 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001782 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001783 if (CheckExceptionSpecCompatibility(From, ToType))
1784 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001785 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001786 break;
1787 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001788 case ICK_Boolean_Conversion: {
1789 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1790 if (FromType->isMemberPointerType())
1791 Kind = CastExpr::CK_MemberPointerToBoolean;
1792
1793 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001795 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001796
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001797 case ICK_Derived_To_Base:
1798 if (CheckDerivedToBaseConversion(From->getType(),
1799 ToType.getNonReferenceType(),
1800 From->getLocStart(),
Anders Carlssone25a96c2010-04-24 17:11:09 +00001801 From->getSourceRange(), 0,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001802 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001803 return true;
1804 ImpCastExprToType(From, ToType.getNonReferenceType(),
1805 CastExpr::CK_DerivedToBase);
1806 break;
1807
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001808 default:
1809 assert(false && "Improper second standard conversion");
1810 break;
1811 }
1812
1813 switch (SCS.Third) {
1814 case ICK_Identity:
1815 // Nothing to do.
1816 break;
1817
1818 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001819 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1820 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001821 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001822 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001823
1824 if (SCS.DeprecatedStringLiteralToCharPtr)
1825 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1826 << ToType.getNonReferenceType();
1827
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001828 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001829
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001830 default:
1831 assert(false && "Improper second standard conversion");
1832 break;
1833 }
1834
1835 return false;
1836}
1837
Sebastian Redl64b45f72009-01-05 20:52:13 +00001838Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1839 SourceLocation KWLoc,
1840 SourceLocation LParen,
1841 TypeTy *Ty,
1842 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001843 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001845 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1846 // all traits except __is_class, __is_enum and __is_union require a the type
1847 // to be complete.
1848 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001849 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001850 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001851 return ExprError();
1852 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001853
1854 // There is no point in eagerly computing the value. The traits are designed
1855 // to be used from type trait templates, so Ty will be a template parameter
1856 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001857 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1858 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001859}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001860
1861QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001862 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001863 const char *OpSpelling = isIndirect ? "->*" : ".*";
1864 // C++ 5.5p2
1865 // The binary operator .* [p3: ->*] binds its second operand, which shall
1866 // be of type "pointer to member of T" (where T is a completely-defined
1867 // class type) [...]
1868 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001869 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001870 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001871 Diag(Loc, diag::err_bad_memptr_rhs)
1872 << OpSpelling << RType << rex->getSourceRange();
1873 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001874 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001875
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001876 QualType Class(MemPtr->getClass(), 0);
1877
Sebastian Redl59fc2692010-04-10 10:14:54 +00001878 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1879 return QualType();
1880
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001881 // C++ 5.5p2
1882 // [...] to its first operand, which shall be of class T or of a class of
1883 // which T is an unambiguous and accessible base class. [p3: a pointer to
1884 // such a class]
1885 QualType LType = lex->getType();
1886 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001887 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001888 LType = Ptr->getPointeeType().getNonReferenceType();
1889 else {
1890 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001891 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001892 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001893 return QualType();
1894 }
1895 }
1896
Douglas Gregora4923eb2009-11-16 21:35:15 +00001897 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001898 // If we want to check the hierarchy, we need a complete type.
1899 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1900 << OpSpelling << (int)isIndirect)) {
1901 return QualType();
1902 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001903 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001904 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001905 // FIXME: Would it be useful to print full ambiguity paths, or is that
1906 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001907 if (!IsDerivedFrom(LType, Class, Paths) ||
1908 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1909 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001910 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001911 return QualType();
1912 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001913 // Cast LHS to type of use.
1914 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1915 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001916
1917 CXXBaseSpecifierArray BasePath;
1918 BuildBasePathArray(Paths, BasePath);
1919 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1920 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001921 }
1922
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001923 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001924 // Diagnose use of pointer-to-member type which when used as
1925 // the functional cast in a pointer-to-member expression.
1926 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1927 return QualType();
1928 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001929 // C++ 5.5p2
1930 // The result is an object or a function of the type specified by the
1931 // second operand.
1932 // The cv qualifiers are the union of those in the pointer and the left side,
1933 // in accordance with 5.5p5 and 5.2.5.
1934 // FIXME: This returns a dereferenced member function pointer as a normal
1935 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001936 // calling them. There's also a GCC extension to get a function pointer to the
1937 // thing, which is another complication, because this type - unlike the type
1938 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001939 // argument.
1940 // We probably need a "MemberFunctionClosureType" or something like that.
1941 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001942 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001943 return Result;
1944}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001945
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001946/// \brief Try to convert a type to another according to C++0x 5.16p3.
1947///
1948/// This is part of the parameter validation for the ? operator. If either
1949/// value operand is a class type, the two operands are attempted to be
1950/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001951/// It returns true if the program is ill-formed and has already been diagnosed
1952/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001953static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1954 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001955 bool &HaveConversion,
1956 QualType &ToType) {
1957 HaveConversion = false;
1958 ToType = To->getType();
1959
1960 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1961 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001962 // C++0x 5.16p3
1963 // The process for determining whether an operand expression E1 of type T1
1964 // can be converted to match an operand expression E2 of type T2 is defined
1965 // as follows:
1966 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001967 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1968 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001969 // E1 can be converted to match E2 if E1 can be implicitly converted to
1970 // type "lvalue reference to T2", subject to the constraint that in the
1971 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001972 QualType T = Self.Context.getLValueReferenceType(ToType);
1973 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1974
1975 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1976 if (InitSeq.isDirectReferenceBinding()) {
1977 ToType = T;
1978 HaveConversion = true;
1979 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001980 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001981
1982 if (InitSeq.isAmbiguous())
1983 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001984 }
John McCallb1bdc622010-02-25 01:37:24 +00001985
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001986 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1987 // -- if E1 and E2 have class type, and the underlying class types are
1988 // the same or one is a base class of the other:
1989 QualType FTy = From->getType();
1990 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001991 const RecordType *FRec = FTy->getAs<RecordType>();
1992 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001993 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1994 Self.IsDerivedFrom(FTy, TTy);
1995 if (FRec && TRec &&
1996 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001997 // E1 can be converted to match E2 if the class of T2 is the
1998 // same type as, or a base class of, the class of T1, and
1999 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002000 if (FRec == TRec || FDerivedFromT) {
2001 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002002 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2003 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2004 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2005 HaveConversion = true;
2006 return false;
2007 }
2008
2009 if (InitSeq.isAmbiguous())
2010 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2011 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002012 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002013
2014 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002015 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002016
2017 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2018 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002019 // if E2 were converted to an rvalue (or the type it has, if E2 is
2020 // an rvalue).
2021 //
2022 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2023 // to the array-to-pointer or function-to-pointer conversions.
2024 if (!TTy->getAs<TagType>())
2025 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002026
2027 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2028 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2029 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2030 ToType = TTy;
2031 if (InitSeq.isAmbiguous())
2032 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2033
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002034 return false;
2035}
2036
2037/// \brief Try to find a common type for two according to C++0x 5.16p5.
2038///
2039/// This is part of the parameter validation for the ? operator. If either
2040/// value operand is a class type, overload resolution is used to find a
2041/// conversion to a common type.
2042static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2043 SourceLocation Loc) {
2044 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002045 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002046 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002047
2048 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002049 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002050 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002051 // We found a match. Perform the conversions on the arguments and move on.
2052 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002053 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002054 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002055 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002056 break;
2057 return false;
2058
Douglas Gregor20093b42009-12-09 23:02:17 +00002059 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002060 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2061 << LHS->getType() << RHS->getType()
2062 << LHS->getSourceRange() << RHS->getSourceRange();
2063 return true;
2064
Douglas Gregor20093b42009-12-09 23:02:17 +00002065 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002066 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2067 << LHS->getType() << RHS->getType()
2068 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002069 // FIXME: Print the possible common types by printing the return types of
2070 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002071 break;
2072
Douglas Gregor20093b42009-12-09 23:02:17 +00002073 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002074 assert(false && "Conditional operator has only built-in overloads");
2075 break;
2076 }
2077 return true;
2078}
2079
Sebastian Redl76458502009-04-17 16:30:52 +00002080/// \brief Perform an "extended" implicit conversion as returned by
2081/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002082static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2083 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2084 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2085 SourceLocation());
2086 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2087 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2088 Sema::MultiExprArg(Self, (void **)&E, 1));
2089 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002090 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002091
2092 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002093 return false;
2094}
2095
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002096/// \brief Check the operands of ?: under C++ semantics.
2097///
2098/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2099/// extension. In this case, LHS == Cond. (But they're not aliases.)
2100QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2101 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002102 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2103 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002104
2105 // C++0x 5.16p1
2106 // The first expression is contextually converted to bool.
2107 if (!Cond->isTypeDependent()) {
2108 if (CheckCXXBooleanCondition(Cond))
2109 return QualType();
2110 }
2111
2112 // Either of the arguments dependent?
2113 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2114 return Context.DependentTy;
2115
John McCalld1b47bf2010-03-11 19:43:18 +00002116 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00002117
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002118 // C++0x 5.16p2
2119 // If either the second or the third operand has type (cv) void, ...
2120 QualType LTy = LHS->getType();
2121 QualType RTy = RHS->getType();
2122 bool LVoid = LTy->isVoidType();
2123 bool RVoid = RTy->isVoidType();
2124 if (LVoid || RVoid) {
2125 // ... then the [l2r] conversions are performed on the second and third
2126 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002127 DefaultFunctionArrayLvalueConversion(LHS);
2128 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002129 LTy = LHS->getType();
2130 RTy = RHS->getType();
2131
2132 // ... and one of the following shall hold:
2133 // -- The second or the third operand (but not both) is a throw-
2134 // expression; the result is of the type of the other and is an rvalue.
2135 bool LThrow = isa<CXXThrowExpr>(LHS);
2136 bool RThrow = isa<CXXThrowExpr>(RHS);
2137 if (LThrow && !RThrow)
2138 return RTy;
2139 if (RThrow && !LThrow)
2140 return LTy;
2141
2142 // -- Both the second and third operands have type void; the result is of
2143 // type void and is an rvalue.
2144 if (LVoid && RVoid)
2145 return Context.VoidTy;
2146
2147 // Neither holds, error.
2148 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2149 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2150 << LHS->getSourceRange() << RHS->getSourceRange();
2151 return QualType();
2152 }
2153
2154 // Neither is void.
2155
2156 // C++0x 5.16p3
2157 // Otherwise, if the second and third operand have different types, and
2158 // either has (cv) class type, and attempt is made to convert each of those
2159 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002160 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002161 (LTy->isRecordType() || RTy->isRecordType())) {
2162 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2163 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002164 QualType L2RType, R2LType;
2165 bool HaveL2R, HaveR2L;
2166 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002167 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002168 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002169 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002170
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002171 // If both can be converted, [...] the program is ill-formed.
2172 if (HaveL2R && HaveR2L) {
2173 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2174 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2175 return QualType();
2176 }
2177
2178 // If exactly one conversion is possible, that conversion is applied to
2179 // the chosen operand and the converted operands are used in place of the
2180 // original operands for the remainder of this section.
2181 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002182 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002183 return QualType();
2184 LTy = LHS->getType();
2185 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002186 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002187 return QualType();
2188 RTy = RHS->getType();
2189 }
2190 }
2191
2192 // C++0x 5.16p4
2193 // If the second and third operands are lvalues and have the same type,
2194 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002195 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002196 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2197 RHS->isLvalue(Context) == Expr::LV_Valid)
2198 return LTy;
2199
2200 // C++0x 5.16p5
2201 // Otherwise, the result is an rvalue. If the second and third operands
2202 // do not have the same type, and either has (cv) class type, ...
2203 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2204 // ... overload resolution is used to determine the conversions (if any)
2205 // to be applied to the operands. If the overload resolution fails, the
2206 // program is ill-formed.
2207 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2208 return QualType();
2209 }
2210
2211 // C++0x 5.16p6
2212 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2213 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002214 DefaultFunctionArrayLvalueConversion(LHS);
2215 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002216 LTy = LHS->getType();
2217 RTy = RHS->getType();
2218
2219 // After those conversions, one of the following shall hold:
2220 // -- The second and third operands have the same type; the result
2221 // is of that type.
2222 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2223 return LTy;
2224
2225 // -- The second and third operands have arithmetic or enumeration type;
2226 // the usual arithmetic conversions are performed to bring them to a
2227 // common type, and the result is of that type.
2228 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2229 UsualArithmeticConversions(LHS, RHS);
2230 return LHS->getType();
2231 }
2232
2233 // -- The second and third operands have pointer type, or one has pointer
2234 // type and the other is a null pointer constant; pointer conversions
2235 // and qualification conversions are performed to bring them to their
2236 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002237 // -- The second and third operands have pointer to member type, or one has
2238 // pointer to member type and the other is a null pointer constant;
2239 // pointer to member conversions and qualification conversions are
2240 // performed to bring them to a common type, whose cv-qualification
2241 // shall match the cv-qualification of either the second or the third
2242 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002243 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002244 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002245 isSFINAEContext()? 0 : &NonStandardCompositeType);
2246 if (!Composite.isNull()) {
2247 if (NonStandardCompositeType)
2248 Diag(QuestionLoc,
2249 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2250 << LTy << RTy << Composite
2251 << LHS->getSourceRange() << RHS->getSourceRange();
2252
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002253 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002254 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002255
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002256 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002257 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2258 if (!Composite.isNull())
2259 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002260
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002261 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2262 << LHS->getType() << RHS->getType()
2263 << LHS->getSourceRange() << RHS->getSourceRange();
2264 return QualType();
2265}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002266
2267/// \brief Find a merged pointer type and convert the two expressions to it.
2268///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002269/// This finds the composite pointer type (or member pointer type) for @p E1
2270/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2271/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002272/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002273///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002274/// \param Loc The location of the operator requiring these two expressions to
2275/// be converted to the composite pointer type.
2276///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002277/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2278/// a non-standard (but still sane) composite type to which both expressions
2279/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2280/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002281QualType Sema::FindCompositePointerType(SourceLocation Loc,
2282 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002283 bool *NonStandardCompositeType) {
2284 if (NonStandardCompositeType)
2285 *NonStandardCompositeType = false;
2286
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002287 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2288 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002290 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2291 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002292 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002293
2294 // C++0x 5.9p2
2295 // Pointer conversions and qualification conversions are performed on
2296 // pointer operands to bring them to their composite pointer type. If
2297 // one operand is a null pointer constant, the composite pointer type is
2298 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002299 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002300 if (T2->isMemberPointerType())
2301 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2302 else
2303 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002304 return T2;
2305 }
Douglas Gregorce940492009-09-25 04:25:58 +00002306 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002307 if (T1->isMemberPointerType())
2308 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2309 else
2310 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002311 return T1;
2312 }
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Douglas Gregor20b3e992009-08-24 17:42:35 +00002314 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002315 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2316 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002317 return QualType();
2318
2319 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2320 // the other has type "pointer to cv2 T" and the composite pointer type is
2321 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2322 // Otherwise, the composite pointer type is a pointer type similar to the
2323 // type of one of the operands, with a cv-qualification signature that is
2324 // the union of the cv-qualification signatures of the operand types.
2325 // In practice, the first part here is redundant; it's subsumed by the second.
2326 // What we do here is, we build the two possible composite types, and try the
2327 // conversions in both directions. If only one works, or if the two composite
2328 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002329 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002330 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2331 QualifierVector QualifierUnion;
2332 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2333 ContainingClassVector;
2334 ContainingClassVector MemberOfClass;
2335 QualType Composite1 = Context.getCanonicalType(T1),
2336 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002337 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002338 do {
2339 const PointerType *Ptr1, *Ptr2;
2340 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2341 (Ptr2 = Composite2->getAs<PointerType>())) {
2342 Composite1 = Ptr1->getPointeeType();
2343 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002344
2345 // If we're allowed to create a non-standard composite type, keep track
2346 // of where we need to fill in additional 'const' qualifiers.
2347 if (NonStandardCompositeType &&
2348 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2349 NeedConstBefore = QualifierUnion.size();
2350
Douglas Gregor20b3e992009-08-24 17:42:35 +00002351 QualifierUnion.push_back(
2352 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2353 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2354 continue;
2355 }
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Douglas Gregor20b3e992009-08-24 17:42:35 +00002357 const MemberPointerType *MemPtr1, *MemPtr2;
2358 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2359 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2360 Composite1 = MemPtr1->getPointeeType();
2361 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002362
2363 // If we're allowed to create a non-standard composite type, keep track
2364 // of where we need to fill in additional 'const' qualifiers.
2365 if (NonStandardCompositeType &&
2366 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2367 NeedConstBefore = QualifierUnion.size();
2368
Douglas Gregor20b3e992009-08-24 17:42:35 +00002369 QualifierUnion.push_back(
2370 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2371 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2372 MemPtr2->getClass()));
2373 continue;
2374 }
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Douglas Gregor20b3e992009-08-24 17:42:35 +00002376 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Douglas Gregor20b3e992009-08-24 17:42:35 +00002378 // Cannot unwrap any more types.
2379 break;
2380 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002382 if (NeedConstBefore && NonStandardCompositeType) {
2383 // Extension: Add 'const' to qualifiers that come before the first qualifier
2384 // mismatch, so that our (non-standard!) composite type meets the
2385 // requirements of C++ [conv.qual]p4 bullet 3.
2386 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2387 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2388 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2389 *NonStandardCompositeType = true;
2390 }
2391 }
2392 }
2393
Douglas Gregor20b3e992009-08-24 17:42:35 +00002394 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002395 ContainingClassVector::reverse_iterator MOC
2396 = MemberOfClass.rbegin();
2397 for (QualifierVector::reverse_iterator
2398 I = QualifierUnion.rbegin(),
2399 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002400 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002401 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002402 if (MOC->first && MOC->second) {
2403 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002404 Composite1 = Context.getMemberPointerType(
2405 Context.getQualifiedType(Composite1, Quals),
2406 MOC->first);
2407 Composite2 = Context.getMemberPointerType(
2408 Context.getQualifiedType(Composite2, Quals),
2409 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002410 } else {
2411 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002412 Composite1
2413 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2414 Composite2
2415 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002416 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002417 }
2418
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002419 // Try to convert to the first composite pointer type.
2420 InitializedEntity Entity1
2421 = InitializedEntity::InitializeTemporary(Composite1);
2422 InitializationKind Kind
2423 = InitializationKind::CreateCopy(Loc, SourceLocation());
2424 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2425 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002427 if (E1ToC1 && E2ToC1) {
2428 // Conversion to Composite1 is viable.
2429 if (!Context.hasSameType(Composite1, Composite2)) {
2430 // Composite2 is a different type from Composite1. Check whether
2431 // Composite2 is also viable.
2432 InitializedEntity Entity2
2433 = InitializedEntity::InitializeTemporary(Composite2);
2434 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2435 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2436 if (E1ToC2 && E2ToC2) {
2437 // Both Composite1 and Composite2 are viable and are different;
2438 // this is an ambiguity.
2439 return QualType();
2440 }
2441 }
2442
2443 // Convert E1 to Composite1
2444 OwningExprResult E1Result
2445 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2446 if (E1Result.isInvalid())
2447 return QualType();
2448 E1 = E1Result.takeAs<Expr>();
2449
2450 // Convert E2 to Composite1
2451 OwningExprResult E2Result
2452 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2453 if (E2Result.isInvalid())
2454 return QualType();
2455 E2 = E2Result.takeAs<Expr>();
2456
2457 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002458 }
2459
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002460 // Check whether Composite2 is viable.
2461 InitializedEntity Entity2
2462 = InitializedEntity::InitializeTemporary(Composite2);
2463 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2464 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2465 if (!E1ToC2 || !E2ToC2)
2466 return QualType();
2467
2468 // Convert E1 to Composite2
2469 OwningExprResult E1Result
2470 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2471 if (E1Result.isInvalid())
2472 return QualType();
2473 E1 = E1Result.takeAs<Expr>();
2474
2475 // Convert E2 to Composite2
2476 OwningExprResult E2Result
2477 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2478 if (E2Result.isInvalid())
2479 return QualType();
2480 E2 = E2Result.takeAs<Expr>();
2481
2482 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002483}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002484
Anders Carlssondef11992009-05-30 20:36:53 +00002485Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002486 if (!Context.getLangOptions().CPlusPlus)
2487 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Douglas Gregor51326552009-12-24 18:51:59 +00002489 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2490
Ted Kremenek6217b802009-07-29 21:53:49 +00002491 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002492 if (!RT)
2493 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002494
John McCall86ff3082010-02-04 22:26:26 +00002495 // If this is the result of a call expression, our source might
2496 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002497 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2498 QualType Ty = CE->getCallee()->getType();
2499 if (const PointerType *PT = Ty->getAs<PointerType>())
2500 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002501 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2502 Ty = BPT->getPointeeType();
2503
John McCall183700f2009-09-21 23:43:11 +00002504 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002505 if (FTy->getResultType()->isReferenceType())
2506 return Owned(E);
2507 }
John McCall86ff3082010-02-04 22:26:26 +00002508
2509 // That should be enough to guarantee that this type is complete.
2510 // If it has a trivial destructor, we can avoid the extra copy.
2511 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2512 if (RD->hasTrivialDestructor())
2513 return Owned(E);
2514
Mike Stump1eb44332009-09-09 15:08:12 +00002515 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002516 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002517 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002518 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002519 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002520 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002521 CheckDestructorAccess(E->getExprLoc(), Destructor,
2522 PDiag(diag::err_access_dtor_temp)
2523 << E->getType());
2524 }
Anders Carlssondef11992009-05-30 20:36:53 +00002525 // FIXME: Add the temporary to the temporaries vector.
2526 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2527}
2528
Anders Carlsson0ece4912009-12-15 20:51:39 +00002529Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002530 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002532 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2533 assert(ExprTemporaries.size() >= FirstTemporary);
2534 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002535 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002537 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002538 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002539 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002540 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2541 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002543 return E;
2544}
2545
Douglas Gregor90f93822009-12-22 22:17:25 +00002546Sema::OwningExprResult
2547Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2548 if (SubExpr.isInvalid())
2549 return ExprError();
2550
2551 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2552}
2553
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002554FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2555 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2556 assert(ExprTemporaries.size() >= FirstTemporary);
2557
2558 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2559 CXXTemporary **Temporaries =
2560 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2561
2562 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2563
2564 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2565 ExprTemporaries.end());
2566
2567 return E;
2568}
2569
Mike Stump1eb44332009-09-09 15:08:12 +00002570Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002571Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002572 tok::TokenKind OpKind, TypeTy *&ObjectType,
2573 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002574 // Since this might be a postfix expression, get rid of ParenListExprs.
2575 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002577 Expr *BaseExpr = (Expr*)Base.get();
2578 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002580 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002581 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002582 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002583 // If we have a pointer to a dependent type and are using the -> operator,
2584 // the object type is the type that the pointer points to. We might still
2585 // have enough information about that type to do something useful.
2586 if (OpKind == tok::arrow)
2587 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2588 BaseType = Ptr->getPointeeType();
2589
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002590 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002591 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002592 return move(Base);
2593 }
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002595 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002596 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002597 // returned, with the original second operand.
2598 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002599 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002600 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002601 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002602 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002603
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002604 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002605 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002606 BaseExpr = (Expr*)Base.get();
2607 if (BaseExpr == NULL)
2608 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002609 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002610 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002611 BaseType = BaseExpr->getType();
2612 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002613 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002614 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002615 for (unsigned i = 0; i < Locations.size(); i++)
2616 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002617 return ExprError();
2618 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002619 }
Mike Stump1eb44332009-09-09 15:08:12 +00002620
Douglas Gregor31658df2009-11-20 19:58:21 +00002621 if (BaseType->isPointerType())
2622 BaseType = BaseType->getPointeeType();
2623 }
Mike Stump1eb44332009-09-09 15:08:12 +00002624
2625 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002626 // vector types or Objective-C interfaces. Just return early and let
2627 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002628 if (!BaseType->isRecordType()) {
2629 // C++ [basic.lookup.classref]p2:
2630 // [...] If the type of the object expression is of pointer to scalar
2631 // type, the unqualified-id is looked up in the context of the complete
2632 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002633 //
2634 // This also indicates that we should be parsing a
2635 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002636 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002637 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002638 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002639 }
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Douglas Gregor03c57052009-11-17 05:17:33 +00002641 // The object type must be complete (or dependent).
2642 if (!BaseType->isDependentType() &&
2643 RequireCompleteType(OpLoc, BaseType,
2644 PDiag(diag::err_incomplete_member_access)))
2645 return ExprError();
2646
Douglas Gregorc68afe22009-09-03 21:38:09 +00002647 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002648 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002649 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002650 // type C (or of pointer to a class type C), the unqualified-id is looked
2651 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002652 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002653 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002654}
2655
Douglas Gregor77549082010-02-24 21:29:12 +00002656Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2657 ExprArg MemExpr) {
2658 Expr *E = (Expr *) MemExpr.get();
2659 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2660 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2661 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002662 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002663
2664 return ActOnCallExpr(/*Scope*/ 0,
2665 move(MemExpr),
2666 /*LPLoc*/ ExpectedLParenLoc,
2667 Sema::MultiExprArg(*this, 0, 0),
2668 /*CommaLocs*/ 0,
2669 /*RPLoc*/ ExpectedLParenLoc);
2670}
Douglas Gregord4dca082010-02-24 18:44:31 +00002671
Douglas Gregorb57fb492010-02-24 22:38:50 +00002672Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2673 SourceLocation OpLoc,
2674 tok::TokenKind OpKind,
2675 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002676 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002677 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002678 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002679 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002680 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002681 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002682
2683 // C++ [expr.pseudo]p2:
2684 // The left-hand side of the dot operator shall be of scalar type. The
2685 // left-hand side of the arrow operator shall be of pointer to scalar type.
2686 // This scalar type is the object type.
2687 Expr *BaseE = (Expr *)Base.get();
2688 QualType ObjectType = BaseE->getType();
2689 if (OpKind == tok::arrow) {
2690 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2691 ObjectType = Ptr->getPointeeType();
2692 } else if (!BaseE->isTypeDependent()) {
2693 // The user wrote "p->" when she probably meant "p."; fix it.
2694 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2695 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002696 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002697 if (isSFINAEContext())
2698 return ExprError();
2699
2700 OpKind = tok::period;
2701 }
2702 }
2703
2704 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2705 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2706 << ObjectType << BaseE->getSourceRange();
2707 return ExprError();
2708 }
2709
2710 // C++ [expr.pseudo]p2:
2711 // [...] The cv-unqualified versions of the object type and of the type
2712 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002713 if (DestructedTypeInfo) {
2714 QualType DestructedType = DestructedTypeInfo->getType();
2715 SourceLocation DestructedTypeStart
2716 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2717 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2718 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2719 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2720 << ObjectType << DestructedType << BaseE->getSourceRange()
2721 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2722
2723 // Recover by setting the destructed type to the object type.
2724 DestructedType = ObjectType;
2725 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2726 DestructedTypeStart);
2727 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2728 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002729 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002730
Douglas Gregorb57fb492010-02-24 22:38:50 +00002731 // C++ [expr.pseudo]p2:
2732 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2733 // form
2734 //
2735 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2736 //
2737 // shall designate the same scalar type.
2738 if (ScopeTypeInfo) {
2739 QualType ScopeType = ScopeTypeInfo->getType();
2740 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2741 !Context.hasSameType(ScopeType, ObjectType)) {
2742
2743 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2744 diag::err_pseudo_dtor_type_mismatch)
2745 << ObjectType << ScopeType << BaseE->getSourceRange()
2746 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2747
2748 ScopeType = QualType();
2749 ScopeTypeInfo = 0;
2750 }
2751 }
2752
2753 OwningExprResult Result
2754 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2755 Base.takeAs<Expr>(),
2756 OpKind == tok::arrow,
2757 OpLoc,
2758 (NestedNameSpecifier *) SS.getScopeRep(),
2759 SS.getRange(),
2760 ScopeTypeInfo,
2761 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002762 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002763 Destructed));
2764
Douglas Gregorb57fb492010-02-24 22:38:50 +00002765 if (HasTrailingLParen)
2766 return move(Result);
2767
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002768 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002769}
2770
2771Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2772 SourceLocation OpLoc,
2773 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002774 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002775 UnqualifiedId &FirstTypeName,
2776 SourceLocation CCLoc,
2777 SourceLocation TildeLoc,
2778 UnqualifiedId &SecondTypeName,
2779 bool HasTrailingLParen) {
2780 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2781 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2782 "Invalid first type name in pseudo-destructor");
2783 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2784 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2785 "Invalid second type name in pseudo-destructor");
2786
2787 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002788
2789 // C++ [expr.pseudo]p2:
2790 // The left-hand side of the dot operator shall be of scalar type. The
2791 // left-hand side of the arrow operator shall be of pointer to scalar type.
2792 // This scalar type is the object type.
2793 QualType ObjectType = BaseE->getType();
2794 if (OpKind == tok::arrow) {
2795 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2796 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002797 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002798 // The user wrote "p->" when she probably meant "p."; fix it.
2799 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002800 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002801 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002802 if (isSFINAEContext())
2803 return ExprError();
2804
2805 OpKind = tok::period;
2806 }
2807 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002808
2809 // Compute the object type that we should use for name lookup purposes. Only
2810 // record types and dependent types matter.
2811 void *ObjectTypePtrForLookup = 0;
2812 if (!SS.isSet()) {
2813 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2814 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2815 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2816 }
Douglas Gregor77549082010-02-24 21:29:12 +00002817
Douglas Gregorb57fb492010-02-24 22:38:50 +00002818 // Convert the name of the type being destructed (following the ~) into a
2819 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002820 QualType DestructedType;
2821 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002822 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002823 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2824 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2825 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002826 S, &SS, true, ObjectTypePtrForLookup);
2827 if (!T &&
2828 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2829 (!SS.isSet() && ObjectType->isDependentType()))) {
2830 // The name of the type being destroyed is a dependent name, and we
2831 // couldn't find anything useful in scope. Just store the identifier and
2832 // it's location, and we'll perform (qualified) name lookup again at
2833 // template instantiation time.
2834 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2835 SecondTypeName.StartLocation);
2836 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002837 Diag(SecondTypeName.StartLocation,
2838 diag::err_pseudo_dtor_destructor_non_type)
2839 << SecondTypeName.Identifier << ObjectType;
2840 if (isSFINAEContext())
2841 return ExprError();
2842
2843 // Recover by assuming we had the right type all along.
2844 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002845 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002846 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002847 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002848 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002849 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002850 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2851 TemplateId->getTemplateArgs(),
2852 TemplateId->NumArgs);
2853 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2854 TemplateId->TemplateNameLoc,
2855 TemplateId->LAngleLoc,
2856 TemplateArgsPtr,
2857 TemplateId->RAngleLoc);
2858 if (T.isInvalid() || !T.get()) {
2859 // Recover by assuming we had the right type all along.
2860 DestructedType = ObjectType;
2861 } else
2862 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002863 }
2864
Douglas Gregorb57fb492010-02-24 22:38:50 +00002865 // If we've performed some kind of recovery, (re-)build the type source
2866 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002867 if (!DestructedType.isNull()) {
2868 if (!DestructedTypeInfo)
2869 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002870 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002871 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2872 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002873
2874 // Convert the name of the scope type (the type prior to '::') into a type.
2875 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002876 QualType ScopeType;
2877 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2878 FirstTypeName.Identifier) {
2879 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2880 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2881 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002882 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002883 if (!T) {
2884 Diag(FirstTypeName.StartLocation,
2885 diag::err_pseudo_dtor_destructor_non_type)
2886 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002887
Douglas Gregorb57fb492010-02-24 22:38:50 +00002888 if (isSFINAEContext())
2889 return ExprError();
2890
2891 // Just drop this type. It's unnecessary anyway.
2892 ScopeType = QualType();
2893 } else
2894 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002895 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002896 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002897 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002898 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2899 TemplateId->getTemplateArgs(),
2900 TemplateId->NumArgs);
2901 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2902 TemplateId->TemplateNameLoc,
2903 TemplateId->LAngleLoc,
2904 TemplateArgsPtr,
2905 TemplateId->RAngleLoc);
2906 if (T.isInvalid() || !T.get()) {
2907 // Recover by dropping this type.
2908 ScopeType = QualType();
2909 } else
2910 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002911 }
2912 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002913
2914 if (!ScopeType.isNull() && !ScopeTypeInfo)
2915 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2916 FirstTypeName.StartLocation);
2917
2918
Douglas Gregorb57fb492010-02-24 22:38:50 +00002919 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002920 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002921 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002922}
2923
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002924CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00002925 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002926 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00002927 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2928 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002929 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2930
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002931 MemberExpr *ME =
2932 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2933 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002934 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002935 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2936 CXXMemberCallExpr *CE =
2937 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2938 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002939 return CE;
2940}
2941
Anders Carlsson165a0a02009-05-17 18:41:29 +00002942Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2943 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002944 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002945 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002946
Anders Carlsson165a0a02009-05-17 18:41:29 +00002947 return Owned(FullExpr);
2948}