blob: 8b17f8483d83aa3de2b398dc880b471b5ea0f9e0 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregore610ada2010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner29375652006-12-04 18:06:35 +000027using namespace clang;
28
Douglas Gregorfe17d252010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregorfe17d252010-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 Gregor46841e12010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregorfe17d252010-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 Gregor46841e12010-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 Gregorfe17d252010-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 Carruth8f254812010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregorfe17d252010-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 Gregor46841e12010-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 Gregorfe17d252010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000134 }
Douglas Gregor46841e12010-02-23 00:15:22 +0000135
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregorfe17d252010-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 Gregor678f90d2010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-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 Gregorfe17d252010-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 McCalle78aac42010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-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 Gregorbbdf20a2010-04-24 15:35:55 +0000264 return CheckTypenameType(ETK_None, NNS, II, Range).getAsOpaquePtr();
Douglas Gregorfe17d252010-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 Gregor9da64192010-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();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000290
Douglas Gregor9da64192010-04-26 22:37:10 +0000291 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. [...]
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000317 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregor9da64192010-04-26 22:37:10 +0000318 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 Redl6d4256c2009-03-15 17:47:39 +0000346Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000347Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
348 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000349 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000350 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000351 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000352
Chris Lattnerec7f7732008-11-20 05:51:55 +0000353 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000354 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
355 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000356 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000357 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000358 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000359
Sebastian Redlc4704762008-11-11 11:37:55 +0000360 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-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 Redlc4704762008-11-11 11:37:55 +0000371
Douglas Gregor9da64192010-04-26 22:37:10 +0000372 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000373 }
Mike Stump11289f42009-09-09 15:08:12 +0000374
Douglas Gregor9da64192010-04-26 22:37:10 +0000375 // The operand is an expression.
376 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000377}
378
Steve Naroff66356bd2007-09-16 14:56:35 +0000379/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000380Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000381Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000382 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000383 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000384 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
385 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000386}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000387
Sebastian Redl576fd422009-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 Lattnerb7e656b2008-02-26 00:51:44 +0000394/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000395Action::OwningExprResult
396Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-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 Gregor247894b2009-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 Redl4de47b42009-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 McCall2e6567a2010-04-22 01:10:34 +0000420 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000421 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000422 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000423 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000424 }
425 if (!isPointer || !Ty->isVoidType()) {
426 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000427 PDiag(isPointer ? diag::err_throw_incomplete_ptr
428 : diag::err_throw_incomplete)
429 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000430 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000431
Douglas Gregore8154332010-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 Redl4de47b42009-04-27 20:27:31 +0000436 }
437
John McCall2e6567a2010-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 Redl4de47b42009-04-27 20:27:31 +0000448 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000449}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000450
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000451Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-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 Redl6d4256c2009-03-15 17:47:39 +0000456 if (!isa<FunctionDecl>(CurContext))
457 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000458
459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
460 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000461 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000462 MD->getThisType(Context),
463 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000464
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000465 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000466}
Argyrios Kyrtzidis857fcc22008-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 Redl6d4256c2009-03-15 17:47:39 +0000472Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000473Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
474 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000475 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000476 SourceLocation *CommaLocs,
477 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000478 if (!TypeRep)
479 return ExprError();
480
John McCall97513962010-01-15 18:39:57 +0000481 TypeSourceInfo *TInfo;
482 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
483 if (!TInfo)
484 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000485 unsigned NumExprs = exprs.size();
486 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000487 SourceLocation TyBeginLoc = TypeRange.getBegin();
488 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
489
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000490 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000491 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000492 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000493
494 return Owned(CXXUnresolvedConstructExpr::Create(Context,
495 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000496 LParenLoc,
497 Exprs, NumExprs,
498 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000499 }
500
Anders Carlsson55243162009-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 Jahanian9a14b842009-10-23 21:01:39 +0000509
Anders Carlsson55243162009-08-27 03:53:50 +0000510 if (RequireNonAbstractType(TyBeginLoc, Ty,
511 diag::err_allocation_of_abstract_type))
512 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000513
514
Douglas Gregordd04d332009-01-16 18:33:17 +0000515 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-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 Carlssonf10e4142009-08-07 22:21:05 +0000521 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000522 CXXBaseSpecifierArray BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000523 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
524 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000525 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000526
527 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000528
529 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000530 TInfo, TyBeginLoc, Kind,
Anders Carlsson5d270e82010-04-24 18:38:56 +0000531 Exprs[0], BasePath,
532 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000533 }
534
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000535 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000536 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000537
Mike Stump11289f42009-09-09 15:08:12 +0000538 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000539 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-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 Gregordd04d332009-01-16 18:33:17 +0000549
Eli Friedmana6824272010-01-31 20:58:15 +0000550 // FIXME: Improve AST representation?
551 return move(Result);
Douglas Gregordd04d332009-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 Kyrtzidis857fcc22008-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 Redl6d4256c2009-03-15 17:47:39 +0000563 return ExprError(Diag(CommaLocs[0],
564 diag::err_builtin_func_cast_more_than_one_arg)
565 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000566
567 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000568 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-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 Redl6d4256c2009-03-15 17:47:39 +0000573 exprs.release();
574 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000575}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000576
577
Sebastian Redlbd150f42008-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 Redl6d4256c2009-03-15 17:47:39 +0000583Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000584Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000585 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000586 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000587 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000588 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000589 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000590 Expr *ArraySize = 0;
Sebastian Redl351bb782008-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 Redl6d4256c2009-03-15 17:47:39 +0000596 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
597 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000598 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000599 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
600 << D.getSourceRange());
Sebastian Redld7b3d7d2009-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 Redl351bb782008-12-02 14:43:59 +0000613 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000614 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000615 }
616
Douglas Gregor73341c42009-09-11 00:18:58 +0000617 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000618 if (ArraySize) {
619 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-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 Redld7b3d7d2009-10-25 21:45:37 +0000634
John McCallbcd03502009-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 Lattnerf6d1c9c2009-04-25 08:06:05 +0000638 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000639 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000640
Mike Stump11289f42009-09-09 15:08:12 +0000641 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000642 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000643 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000644 PlacementRParen,
645 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000646 AllocType,
Douglas Gregord0fefba2009-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 Stump11289f42009-09-09 15:08:12 +0000655Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000656Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
657 SourceLocation PlacementLParen,
658 MultiExprArg PlacementArgs,
659 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000660 bool ParenTypeId,
Douglas Gregord0fefba2009-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 Redl6d4256c2009-03-15 17:47:39 +0000669 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000670
Douglas Gregord0fefba2009-05-21 00:00:09 +0000671 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redlbd150f42008-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 Redl351bb782008-12-02 14:43:59 +0000675
Sebastian Redlbd150f42008-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 Gregord0fefba2009-05-21 00:00:09 +0000678 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000679 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000680 QualType SizeType = ArraySize->getType();
681 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000682 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683 diag::err_array_size_not_integral)
684 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-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 Redl8d2ccae2009-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 Carlsson8ab20bb2009-09-23 00:37:25 +0000692 llvm::APInt::getNullValue(Value.getBitWidth()),
693 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000694 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
695 diag::err_typecheck_negative_array_size)
696 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000697 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000698 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000699
Eli Friedman06ed2a52009-10-20 08:27:19 +0000700 ImpCastExprToType(ArraySize, Context.getSizeType(),
701 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000702 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000703
Sebastian Redlbd150f42008-11-21 19:14:01 +0000704 FunctionDecl *OperatorNew = 0;
705 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000706 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
707 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000708
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000709 if (!AllocType->isDependentType() &&
710 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
711 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000712 SourceRange(PlacementLParen, PlacementRParen),
713 UseGlobal, AllocType, ArraySize, PlaceArgs,
714 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000715 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000716 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000717 if (OperatorNew) {
718 // Add default arguments, if any.
719 const FunctionProtoType *Proto =
720 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000721 VariadicCallType CallType =
722 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000723
724 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
725 Proto, 1, PlaceArgs, NumPlaceArgs,
726 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000727 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000728
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000729 NumPlaceArgs = AllPlaceArgs.size();
730 if (NumPlaceArgs > 0)
731 PlaceArgs = &AllPlaceArgs[0];
732 }
733
Sebastian Redlbd150f42008-11-21 19:14:01 +0000734 bool Init = ConstructorLParen.isValid();
735 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000736 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000737 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
738 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000739 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
740
Anders Carlssonc6bb0e12010-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 Gregor85dabae2009-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 Gregor85dabae2009-12-16 01:38:02 +0000766 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000767 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000768 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-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 Gregor5d3507d2009-09-09 23:08:42 +0000796 NumConsArgs = ConvertedConstructorArgs.size();
797 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000798 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000799
Douglas Gregor6642ca22010-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 Redlbd150f42008-11-21 19:14:01 +0000806 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000807
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000808 PlacementArgs.release();
809 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000810 ArraySizeE.release();
Ted Kremenek9d6eb402010-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 Redlbd150f42008-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 Gregord0fefba2009-05-21 00:00:09 +0000823bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000824 SourceRange R) {
Sebastian Redlbd150f42008-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 Gregorac1fb652009-03-24 19:52:54 +0000827 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000828 return Diag(Loc, diag::err_bad_new_type)
829 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000830 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000831 return Diag(Loc, diag::err_bad_new_type)
832 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000833 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000834 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000835 PDiag(diag::err_new_incomplete_type)
836 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000837 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000838 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000839 diag::err_allocation_of_abstract_type))
840 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000841
Sebastian Redlbd150f42008-11-21 19:14:01 +0000842 return false;
843}
844
Douglas Gregor6642ca22010-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 Redlfaf68082008-12-03 20:26:15 +0000859/// FindAllocationFunctions - Finds the overloads of operator new and delete
860/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-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 Redlfaf68082008-12-03 20:26:15 +0000865 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000866 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-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 Redlfaf68082008-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 Carlssona471db02009-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 Redlfaf68082008-12-03 20:26:15 +0000885 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
886
Douglas Gregor6642ca22010-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 Redlfaf68082008-12-03 20:26:15 +0000893 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
894 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000895 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
896 IsArray ? OO_Array_Delete : OO_Delete);
897
Sebastian Redlfaf68082008-12-03 20:26:15 +0000898 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000899 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000900 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000901 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000902 AllocArgs.size(), Record, /*AllowMissing=*/true,
903 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000904 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000905 }
906 if (!OperatorNew) {
907 // Didn't find a member overload. Look for a global one.
908 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000909 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000910 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000911 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
912 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000913 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000914 }
915
John McCall0f55a032010-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 Carlsson6f9dabf2009-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 Stump11289f42009-09-09 15:08:12 +0000927
Douglas Gregor6642ca22010-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 McCallfb6f5262010-03-18 08:19:33 +0000943 if (FoundDelete.isAmbiguous())
944 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000945
946 if (FoundDelete.empty()) {
947 DeclareGlobalNewDelete();
948 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
949 }
950
951 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000952
953 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
954
John McCallfb6f5262010-03-18 08:19:33 +0000955 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-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 Espindolac50c27c2010-03-30 20:24:48 +0000979 0, false, false, 0, 0,
980 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-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 McCalla0296f72010-03-19 07:35:19 +0000998 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-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 McCalla0296f72010-03-19 07:35:19 +00001009 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-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 McCalla0296f72010-03-19 07:35:19 +00001018 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-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 McCallfb6f5262010-03-18 08:19:33 +00001033 } else {
1034 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001035 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001036 }
1037 }
1038
Sebastian Redlfaf68082008-12-03 20:26:15 +00001039 return false;
1040}
1041
Sebastian Redl33a31012008-12-04 22:20:51 +00001042/// FindAllocationOverload - Find an fitting overload for the allocation
1043/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001044bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1045 DeclarationName Name, Expr** Args,
1046 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001047 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001048 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1049 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001050 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001051 if (AllowMissing)
1052 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001053 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001054 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001055 }
1056
John McCallfb6f5262010-03-18 08:19:33 +00001057 if (R.isAmbiguous())
1058 return true;
1059
1060 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001061
John McCallbc077cf2010-02-08 23:07:23 +00001062 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001063 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1064 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001065 // Even member operator new/delete are implicitly treated as
1066 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001067 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001068
John McCalla0296f72010-03-19 07:35:19 +00001069 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1070 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001071 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1072 Candidates,
1073 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001074 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001075 }
1076
John McCalla0296f72010-03-19 07:35:19 +00001077 FunctionDecl *Fn = cast<FunctionDecl>(D);
1078 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001079 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001080 }
1081
1082 // Do the resolution.
1083 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001084 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-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 McCallfb6f5262010-03-18 08:19:33 +00001091 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001092 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1093 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-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 Redl33a31012008-12-04 22:20:51 +00001100 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001101
1102 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001103 }
1104 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001105 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001106 return false;
1107 }
1108
1109 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001110 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001111 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001112 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001113 return true;
1114
1115 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001116 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001117 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001118 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001119 return true;
Douglas Gregor171c45a2009-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 McCallad907772010-01-12 07:18:19 +00001125 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001126 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001127 }
1128 assert(false && "Unreachable, bad result from BestViableFunction");
1129 return true;
1130}
1131
1132
Sebastian Redlfaf68082008-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 Stump11289f42009-09-09 15:08:12 +00001143void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001144 if (GlobalNewDeleteDeclared)
1145 return;
Douglas Gregor87f54062009-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.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001176 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor87f54062009-09-15 22:30:29 +00001177 StdNamespace,
1178 SourceLocation(),
1179 &PP.getIdentifierTable().get("bad_alloc"),
1180 SourceLocation(), 0);
1181 StdBadAlloc->setImplicit(true);
1182 }
1183
Sebastian Redlfaf68082008-12-03 20:26:15 +00001184 GlobalNewDeleteDeclared = true;
1185
1186 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1187 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001188 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001189
Sebastian Redlfaf68082008-12-03 20:26:15 +00001190 DeclareGlobalAllocationFunction(
1191 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001192 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001193 DeclareGlobalAllocationFunction(
1194 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001195 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-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 Lopes13c88c72009-12-16 16:59:22 +00001207 QualType Return, QualType Argument,
1208 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001209 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1210
1211 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001212 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001213 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001214 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001215 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-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 Gregor684d7bd2009-12-22 23:42:49 +00001220 Context.getCanonicalType(
Chandler Carruth93538422010-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 Redlfaf68082008-12-03 20:26:15 +00001226 }
1227 }
1228
Douglas Gregor87f54062009-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 Espindolac50c27c2010-03-30 20:24:48 +00001241 &BadAllocType,
1242 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001243 FunctionDecl *Alloc =
1244 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001245 FnType, /*TInfo=*/0, FunctionDecl::None,
1246 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001247 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001248
1249 if (AddMallocAttr)
1250 Alloc->addAttr(::new (Context) MallocAttr());
1251
Sebastian Redlfaf68082008-12-03 20:26:15 +00001252 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001253 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001254 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001255 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001256 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001257
Douglas Gregor8b9ccca2008-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 Kyrtzidiscfbfe782009-06-30 02:36:12 +00001261 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001262}
1263
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001264bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1265 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001266 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001267 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001268 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001269 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001270
John McCall27b18f82009-11-17 02:14:36 +00001271 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001272 return true;
Anders Carlssone1d34ba02009-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 Gregor861eb802010-04-25 20:55:08 +00001291 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlssone1d34ba02009-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 Redlbd150f42008-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 Redl6d4256c2009-03-15 17:47:39 +00001318Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001319Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001320 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-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 Redlbd150f42008-11-21 19:14:01 +00001325 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1326
Anders Carlssona471db02009-08-16 20:29:29 +00001327 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001328
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001329 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001330 if (!Ex->isTypeDependent()) {
1331 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001332
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001333 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001334 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1335
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001336 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001337 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001338 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001339 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001340 NamedDecl *D = I.getDecl();
1341 if (isa<UsingShadowDecl>(D))
1342 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1343
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001344 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001345 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001346 continue;
1347
John McCallda4458e2010-03-31 01:36:47 +00001348 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-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 Jahanianadcea102009-09-15 22:15:23 +00001353 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001354 }
Fariborz Jahanianadcea102009-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 McCallda4458e2010-03-31 01:36:47 +00001358 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001359 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001360 if (!PerformImplicitConversion(Ex,
1361 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001362 AA_Converting)) {
Fariborz Jahanianadcea102009-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 McCallda4458e2010-03-31 01:36:47 +00001370 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1371 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001372 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001373 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001374 }
1375
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001376 if (!Type->isPointerType())
1377 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1378 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001379
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001380 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001381 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001382 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1383 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001384 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001385 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001386 PDiag(diag::warn_delete_incomplete)
1387 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001388 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001389
Douglas Gregor98496dc2009-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 Carlssona471db02009-08-16 20:29:29 +00001402 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1403 ArrayForm ? OO_Array_Delete : OO_Delete);
1404
Anders Carlssone1d34ba02009-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 Carlsson654e5c72009-11-14 03:17:38 +00001410 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001411
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001412 if (!RD->hasTrivialDestructor())
1413 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001414 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001415 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001416 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001417
Anders Carlssona471db02009-08-16 20:29:29 +00001418 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001419 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001420 DeclareGlobalNewDelete();
1421 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001422 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001423 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001424 OperatorDelete))
1425 return ExprError();
1426 }
Mike Stump11289f42009-09-09 15:08:12 +00001427
John McCall0f55a032010-04-20 02:18:25 +00001428 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1429
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001430 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001431 }
1432
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001433 Operand.release();
1434 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001435 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001436}
1437
Douglas Gregor633caca2009-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.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001440Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1441 SourceLocation StmtLoc,
1442 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001443 QualType T = ConditionVar->getType();
1444
1445 // C++ [stmt.select]p2:
1446 // The declarator shall not specify a function or an array.
1447 if (T->isFunctionType())
1448 return ExprError(Diag(ConditionVar->getLocation(),
1449 diag::err_invalid_use_of_function_type)
1450 << ConditionVar->getSourceRange());
1451 else if (T->isArrayType())
1452 return ExprError(Diag(ConditionVar->getLocation(),
1453 diag::err_invalid_use_of_array_type)
1454 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001455
Douglas Gregore60e41a2010-05-06 17:25:47 +00001456 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1457 ConditionVar->getLocation(),
1458 ConditionVar->getType().getNonReferenceType());
1459 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1460 Condition->Destroy(Context);
1461 return ExprError();
1462 }
1463
1464 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001465}
1466
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001467/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1468bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1469 // C++ 6.4p4:
1470 // The value of a condition that is an initialized declaration in a statement
1471 // other than a switch statement is the value of the declared variable
1472 // implicitly converted to type bool. If that conversion is ill-formed, the
1473 // program is ill-formed.
1474 // The value of a condition that is an expression is the value of the
1475 // expression, implicitly converted to bool.
1476 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001477 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001478}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001479
1480/// Helper function to determine whether this is the (deprecated) C++
1481/// conversion from a string literal to a pointer to non-const char or
1482/// non-const wchar_t (for narrow and wide string literals,
1483/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001484bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001485Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1486 // Look inside the implicit cast, if it exists.
1487 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1488 From = Cast->getSubExpr();
1489
1490 // A string literal (2.13.4) that is not a wide string literal can
1491 // be converted to an rvalue of type "pointer to char"; a wide
1492 // string literal can be converted to an rvalue of type "pointer
1493 // to wchar_t" (C++ 4.2p2).
1494 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001495 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001496 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001497 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001498 // This conversion is considered only when there is an
1499 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001500 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001501 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1502 (!StrLit->isWide() &&
1503 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1504 ToPointeeType->getKind() == BuiltinType::Char_S))))
1505 return true;
1506 }
1507
1508 return false;
1509}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001510
Douglas Gregora4253922010-04-16 22:17:36 +00001511static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1512 SourceLocation CastLoc,
1513 QualType Ty,
1514 CastExpr::CastKind Kind,
1515 CXXMethodDecl *Method,
1516 Sema::ExprArg Arg) {
1517 Expr *From = Arg.takeAs<Expr>();
1518
1519 switch (Kind) {
1520 default: assert(0 && "Unhandled cast kind!");
1521 case CastExpr::CK_ConstructorConversion: {
1522 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1523
1524 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1525 Sema::MultiExprArg(S, (void **)&From, 1),
1526 CastLoc, ConstructorArgs))
1527 return S.ExprError();
1528
1529 Sema::OwningExprResult Result =
1530 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1531 move_arg(ConstructorArgs));
1532 if (Result.isInvalid())
1533 return S.ExprError();
1534
1535 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1536 }
1537
1538 case CastExpr::CK_UserDefinedConversion: {
1539 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1540
1541 // Create an implicit call expr that calls it.
1542 // FIXME: pass the FoundDecl for the user-defined conversion here
1543 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1544 return S.MaybeBindToTemporary(CE);
1545 }
1546 }
1547}
1548
Douglas Gregor5fb53972009-01-14 15:45:31 +00001549/// PerformImplicitConversion - Perform an implicit conversion of the
1550/// expression From to the type ToType using the pre-computed implicit
1551/// conversion sequence ICS. Returns true if there was an error, false
1552/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001553/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001554/// used in the error message.
1555bool
1556Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1557 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001558 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001559 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001560 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001561 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001562 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001563 return true;
1564 break;
1565
Anders Carlsson110b07b2009-09-15 06:28:28 +00001566 case ImplicitConversionSequence::UserDefinedConversion: {
1567
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001568 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1569 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001570 QualType BeforeToType;
1571 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001572 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001573
1574 // If the user-defined conversion is specified by a conversion function,
1575 // the initial standard conversion sequence converts the source type to
1576 // the implicit object parameter of the conversion function.
1577 BeforeToType = Context.getTagDeclType(Conv->getParent());
1578 } else if (const CXXConstructorDecl *Ctor =
1579 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001580 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001581 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001582 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001583 // If the user-defined conversion is specified by a constructor, the
1584 // initial standard conversion sequence converts the source type to the
1585 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001586 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1587 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001588 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001589 else
1590 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001591 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001592 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001593 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001594 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001595 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001596 return true;
1597 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001598
Anders Carlssone9766d52009-09-09 21:33:21 +00001599 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001600 = BuildCXXCastArgument(*this,
1601 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001602 ToType.getNonReferenceType(),
1603 CastKind, cast<CXXMethodDecl>(FD),
1604 Owned(From));
1605
1606 if (CastArg.isInvalid())
1607 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001608
1609 From = CastArg.takeAs<Expr>();
1610
Eli Friedmane96f1d32009-11-27 04:41:50 +00001611 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001612 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001613 }
John McCall0d1da222010-01-12 00:44:57 +00001614
1615 case ImplicitConversionSequence::AmbiguousConversion:
1616 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1617 PDiag(diag::err_typecheck_ambiguous_condition)
1618 << From->getSourceRange());
1619 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001620
Douglas Gregor39c16d42008-10-24 04:54:22 +00001621 case ImplicitConversionSequence::EllipsisConversion:
1622 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001624
1625 case ImplicitConversionSequence::BadConversion:
1626 return true;
1627 }
1628
1629 // Everything went well.
1630 return false;
1631}
1632
1633/// PerformImplicitConversion - Perform an implicit conversion of the
1634/// expression From to the type ToType by following the standard
1635/// conversion sequence SCS. Returns true if there was an error, false
1636/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001637/// expression. Flavor is the context in which we're performing this
1638/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001639bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001640Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001641 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001642 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001643 // Overall FIXME: we are recomputing too many types here and doing far too
1644 // much extra work. What this means is that we need to keep track of more
1645 // information that is computed when we try the implicit conversion initially,
1646 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001647 QualType FromType = From->getType();
1648
Douglas Gregor2fe98832008-11-03 19:09:14 +00001649 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001650 // FIXME: When can ToType be a reference type?
1651 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001652 if (SCS.Second == ICK_Derived_To_Base) {
1653 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1654 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1655 MultiExprArg(*this, (void **)&From, 1),
1656 /*FIXME:ConstructLoc*/SourceLocation(),
1657 ConstructorArgs))
1658 return true;
1659 OwningExprResult FromResult =
1660 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1661 ToType, SCS.CopyConstructor,
1662 move_arg(ConstructorArgs));
1663 if (FromResult.isInvalid())
1664 return true;
1665 From = FromResult.takeAs<Expr>();
1666 return false;
1667 }
Mike Stump11289f42009-09-09 15:08:12 +00001668 OwningExprResult FromResult =
1669 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1670 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001671 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001672
Anders Carlsson6eb55572009-08-25 05:12:04 +00001673 if (FromResult.isInvalid())
1674 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001675
Anders Carlsson6eb55572009-08-25 05:12:04 +00001676 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001677 return false;
1678 }
1679
Douglas Gregor980fb162010-04-29 18:24:40 +00001680 // Resolve overloaded function references.
1681 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1682 DeclAccessPair Found;
1683 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1684 true, Found);
1685 if (!Fn)
1686 return true;
1687
1688 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1689 return true;
1690
1691 From = FixOverloadedFunctionReference(From, Found, Fn);
1692 FromType = From->getType();
1693 }
1694
Douglas Gregor39c16d42008-10-24 04:54:22 +00001695 // Perform the first implicit conversion.
1696 switch (SCS.First) {
1697 case ICK_Identity:
1698 case ICK_Lvalue_To_Rvalue:
1699 // Nothing to do.
1700 break;
1701
1702 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001703 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001704 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001705 break;
1706
1707 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001708 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001709 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001710 break;
1711
1712 default:
1713 assert(false && "Improper first standard conversion");
1714 break;
1715 }
1716
1717 // Perform the second implicit conversion
1718 switch (SCS.Second) {
1719 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001720 // 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 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001725 break;
1726
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001727 case ICK_NoReturn_Adjustment:
1728 // If both sides are functions (or pointers/references to them), there could
1729 // be incompatible exception declarations.
1730 if (CheckExceptionSpecCompatibility(From, ToType))
1731 return true;
1732
1733 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1734 CastExpr::CK_NoOp);
1735 break;
1736
Douglas Gregor39c16d42008-10-24 04:54:22 +00001737 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001738 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001739 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1740 break;
1741
1742 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001743 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001744 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1745 break;
1746
1747 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001748 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001749 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1750 break;
1751
Douglas Gregor39c16d42008-10-24 04:54:22 +00001752 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001753 if (ToType->isFloatingType())
1754 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1755 else
1756 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1757 break;
1758
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001759 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001760 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1761 break;
1762
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001763 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001764 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001765 break;
1766
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001767 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001768 if (SCS.IncompatibleObjC) {
1769 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001770 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001771 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001772 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001773 << From->getSourceRange();
1774 }
1775
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001776
1777 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssona70cff62010-04-24 19:06:50 +00001778 CXXBaseSpecifierArray BasePath;
1779 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001780 return true;
Anders Carlssona70cff62010-04-24 19:06:50 +00001781 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001782 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001783 }
1784
1785 case ICK_Pointer_Member: {
1786 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001787 CXXBaseSpecifierArray BasePath;
1788 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1789 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001790 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001791 if (CheckExceptionSpecCompatibility(From, ToType))
1792 return true;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001793 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001794 break;
1795 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001796 case ICK_Boolean_Conversion: {
1797 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1798 if (FromType->isMemberPointerType())
1799 Kind = CastExpr::CK_MemberPointerToBoolean;
1800
1801 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001802 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001803 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001804
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001805 case ICK_Derived_To_Base:
1806 if (CheckDerivedToBaseConversion(From->getType(),
1807 ToType.getNonReferenceType(),
1808 From->getLocStart(),
Anders Carlsson7afe4242010-04-24 17:11:09 +00001809 From->getSourceRange(), 0,
Sebastian Redl7c353682009-11-14 21:15:49 +00001810 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001811 return true;
1812 ImpCastExprToType(From, ToType.getNonReferenceType(),
1813 CastExpr::CK_DerivedToBase);
1814 break;
1815
Douglas Gregor39c16d42008-10-24 04:54:22 +00001816 default:
1817 assert(false && "Improper second standard conversion");
1818 break;
1819 }
1820
1821 switch (SCS.Third) {
1822 case ICK_Identity:
1823 // Nothing to do.
1824 break;
1825
1826 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001827 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1828 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001829 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00001830 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001831
1832 if (SCS.DeprecatedStringLiteralToCharPtr)
1833 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1834 << ToType.getNonReferenceType();
1835
Douglas Gregor39c16d42008-10-24 04:54:22 +00001836 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001837
Douglas Gregor39c16d42008-10-24 04:54:22 +00001838 default:
1839 assert(false && "Improper second standard conversion");
1840 break;
1841 }
1842
1843 return false;
1844}
1845
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001846Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1847 SourceLocation KWLoc,
1848 SourceLocation LParen,
1849 TypeTy *Ty,
1850 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001851 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001852
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001853 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1854 // all traits except __is_class, __is_enum and __is_union require a the type
1855 // to be complete.
1856 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001857 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001858 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001859 return ExprError();
1860 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001861
1862 // There is no point in eagerly computing the value. The traits are designed
1863 // to be used from type trait templates, so Ty will be a template parameter
1864 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001865 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1866 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001867}
Sebastian Redl5822f082009-02-07 20:10:22 +00001868
1869QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001870 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001871 const char *OpSpelling = isIndirect ? "->*" : ".*";
1872 // C++ 5.5p2
1873 // The binary operator .* [p3: ->*] binds its second operand, which shall
1874 // be of type "pointer to member of T" (where T is a completely-defined
1875 // class type) [...]
1876 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001877 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001878 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001879 Diag(Loc, diag::err_bad_memptr_rhs)
1880 << OpSpelling << RType << rex->getSourceRange();
1881 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001882 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001883
Sebastian Redl5822f082009-02-07 20:10:22 +00001884 QualType Class(MemPtr->getClass(), 0);
1885
Sebastian Redlc72350e2010-04-10 10:14:54 +00001886 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1887 return QualType();
1888
Sebastian Redl5822f082009-02-07 20:10:22 +00001889 // C++ 5.5p2
1890 // [...] to its first operand, which shall be of class T or of a class of
1891 // which T is an unambiguous and accessible base class. [p3: a pointer to
1892 // such a class]
1893 QualType LType = lex->getType();
1894 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001895 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001896 LType = Ptr->getPointeeType().getNonReferenceType();
1897 else {
1898 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001899 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001900 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001901 return QualType();
1902 }
1903 }
1904
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001905 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001906 // If we want to check the hierarchy, we need a complete type.
1907 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1908 << OpSpelling << (int)isIndirect)) {
1909 return QualType();
1910 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001911 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001912 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001913 // FIXME: Would it be useful to print full ambiguity paths, or is that
1914 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001915 if (!IsDerivedFrom(LType, Class, Paths) ||
1916 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1917 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001918 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001919 return QualType();
1920 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001921 // Cast LHS to type of use.
1922 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1923 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlssona70cff62010-04-24 19:06:50 +00001924
1925 CXXBaseSpecifierArray BasePath;
1926 BuildBasePathArray(Paths, BasePath);
1927 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1928 BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00001929 }
1930
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001931 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001932 // Diagnose use of pointer-to-member type which when used as
1933 // the functional cast in a pointer-to-member expression.
1934 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1935 return QualType();
1936 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001937 // C++ 5.5p2
1938 // The result is an object or a function of the type specified by the
1939 // second operand.
1940 // The cv qualifiers are the union of those in the pointer and the left side,
1941 // in accordance with 5.5p5 and 5.2.5.
1942 // FIXME: This returns a dereferenced member function pointer as a normal
1943 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001944 // calling them. There's also a GCC extension to get a function pointer to the
1945 // thing, which is another complication, because this type - unlike the type
1946 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001947 // argument.
1948 // We probably need a "MemberFunctionClosureType" or something like that.
1949 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001950 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001951 return Result;
1952}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001953
Sebastian Redl1a99f442009-04-16 17:51:27 +00001954/// \brief Try to convert a type to another according to C++0x 5.16p3.
1955///
1956/// This is part of the parameter validation for the ? operator. If either
1957/// value operand is a class type, the two operands are attempted to be
1958/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001959/// It returns true if the program is ill-formed and has already been diagnosed
1960/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001961static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1962 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00001963 bool &HaveConversion,
1964 QualType &ToType) {
1965 HaveConversion = false;
1966 ToType = To->getType();
1967
1968 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1969 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00001970 // C++0x 5.16p3
1971 // The process for determining whether an operand expression E1 of type T1
1972 // can be converted to match an operand expression E2 of type T2 is defined
1973 // as follows:
1974 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00001975 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1976 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00001977 // E1 can be converted to match E2 if E1 can be implicitly converted to
1978 // type "lvalue reference to T2", subject to the constraint that in the
1979 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001980 QualType T = Self.Context.getLValueReferenceType(ToType);
1981 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1982
1983 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1984 if (InitSeq.isDirectReferenceBinding()) {
1985 ToType = T;
1986 HaveConversion = true;
1987 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00001988 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00001989
1990 if (InitSeq.isAmbiguous())
1991 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00001992 }
John McCall65eb8792010-02-25 01:37:24 +00001993
Sebastian Redl1a99f442009-04-16 17:51:27 +00001994 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1995 // -- if E1 and E2 have class type, and the underlying class types are
1996 // the same or one is a base class of the other:
1997 QualType FTy = From->getType();
1998 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001999 const RecordType *FRec = FTy->getAs<RecordType>();
2000 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002001 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2002 Self.IsDerivedFrom(FTy, TTy);
2003 if (FRec && TRec &&
2004 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002005 // E1 can be converted to match E2 if the class of T2 is the
2006 // same type as, or a base class of, the class of T1, and
2007 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002008 if (FRec == TRec || FDerivedFromT) {
2009 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002010 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2011 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2012 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2013 HaveConversion = true;
2014 return false;
2015 }
2016
2017 if (InitSeq.isAmbiguous())
2018 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2019 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002020 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002021
2022 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002023 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002024
2025 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2026 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002027 // if E2 were converted to an rvalue (or the type it has, if E2 is
2028 // an rvalue).
2029 //
2030 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2031 // to the array-to-pointer or function-to-pointer conversions.
2032 if (!TTy->getAs<TagType>())
2033 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002034
2035 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2036 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2037 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2038 ToType = TTy;
2039 if (InitSeq.isAmbiguous())
2040 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2041
Sebastian Redl1a99f442009-04-16 17:51:27 +00002042 return false;
2043}
2044
2045/// \brief Try to find a common type for two according to C++0x 5.16p5.
2046///
2047/// This is part of the parameter validation for the ? operator. If either
2048/// value operand is a class type, overload resolution is used to find a
2049/// conversion to a common type.
2050static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2051 SourceLocation Loc) {
2052 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002053 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002054 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002055
2056 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002057 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002058 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002059 // We found a match. Perform the conversions on the arguments and move on.
2060 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002061 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002062 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002063 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002064 break;
2065 return false;
2066
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002067 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002068 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2069 << LHS->getType() << RHS->getType()
2070 << LHS->getSourceRange() << RHS->getSourceRange();
2071 return true;
2072
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002073 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002074 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2075 << LHS->getType() << RHS->getType()
2076 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002077 // FIXME: Print the possible common types by printing the return types of
2078 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002079 break;
2080
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002081 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002082 assert(false && "Conditional operator has only built-in overloads");
2083 break;
2084 }
2085 return true;
2086}
2087
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002088/// \brief Perform an "extended" implicit conversion as returned by
2089/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002090static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2091 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2092 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2093 SourceLocation());
2094 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2095 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2096 Sema::MultiExprArg(Self, (void **)&E, 1));
2097 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002098 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002099
2100 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002101 return false;
2102}
2103
Sebastian Redl1a99f442009-04-16 17:51:27 +00002104/// \brief Check the operands of ?: under C++ semantics.
2105///
2106/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2107/// extension. In this case, LHS == Cond. (But they're not aliases.)
2108QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2109 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002110 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2111 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002112
2113 // C++0x 5.16p1
2114 // The first expression is contextually converted to bool.
2115 if (!Cond->isTypeDependent()) {
2116 if (CheckCXXBooleanCondition(Cond))
2117 return QualType();
2118 }
2119
2120 // Either of the arguments dependent?
2121 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2122 return Context.DependentTy;
2123
2124 // C++0x 5.16p2
2125 // If either the second or the third operand has type (cv) void, ...
2126 QualType LTy = LHS->getType();
2127 QualType RTy = RHS->getType();
2128 bool LVoid = LTy->isVoidType();
2129 bool RVoid = RTy->isVoidType();
2130 if (LVoid || RVoid) {
2131 // ... then the [l2r] conversions are performed on the second and third
2132 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002133 DefaultFunctionArrayLvalueConversion(LHS);
2134 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002135 LTy = LHS->getType();
2136 RTy = RHS->getType();
2137
2138 // ... and one of the following shall hold:
2139 // -- The second or the third operand (but not both) is a throw-
2140 // expression; the result is of the type of the other and is an rvalue.
2141 bool LThrow = isa<CXXThrowExpr>(LHS);
2142 bool RThrow = isa<CXXThrowExpr>(RHS);
2143 if (LThrow && !RThrow)
2144 return RTy;
2145 if (RThrow && !LThrow)
2146 return LTy;
2147
2148 // -- Both the second and third operands have type void; the result is of
2149 // type void and is an rvalue.
2150 if (LVoid && RVoid)
2151 return Context.VoidTy;
2152
2153 // Neither holds, error.
2154 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2155 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2156 << LHS->getSourceRange() << RHS->getSourceRange();
2157 return QualType();
2158 }
2159
2160 // Neither is void.
2161
2162 // C++0x 5.16p3
2163 // Otherwise, if the second and third operand have different types, and
2164 // either has (cv) class type, and attempt is made to convert each of those
2165 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002166 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002167 (LTy->isRecordType() || RTy->isRecordType())) {
2168 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2169 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002170 QualType L2RType, R2LType;
2171 bool HaveL2R, HaveR2L;
2172 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002173 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002174 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002175 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002176
Sebastian Redl1a99f442009-04-16 17:51:27 +00002177 // If both can be converted, [...] the program is ill-formed.
2178 if (HaveL2R && HaveR2L) {
2179 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2180 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2181 return QualType();
2182 }
2183
2184 // If exactly one conversion is possible, that conversion is applied to
2185 // the chosen operand and the converted operands are used in place of the
2186 // original operands for the remainder of this section.
2187 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002188 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002189 return QualType();
2190 LTy = LHS->getType();
2191 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002192 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002193 return QualType();
2194 RTy = RHS->getType();
2195 }
2196 }
2197
2198 // C++0x 5.16p4
2199 // If the second and third operands are lvalues and have the same type,
2200 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002201 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002202 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2203 RHS->isLvalue(Context) == Expr::LV_Valid)
2204 return LTy;
2205
2206 // C++0x 5.16p5
2207 // Otherwise, the result is an rvalue. If the second and third operands
2208 // do not have the same type, and either has (cv) class type, ...
2209 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2210 // ... overload resolution is used to determine the conversions (if any)
2211 // to be applied to the operands. If the overload resolution fails, the
2212 // program is ill-formed.
2213 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2214 return QualType();
2215 }
2216
2217 // C++0x 5.16p6
2218 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2219 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002220 DefaultFunctionArrayLvalueConversion(LHS);
2221 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002222 LTy = LHS->getType();
2223 RTy = RHS->getType();
2224
2225 // After those conversions, one of the following shall hold:
2226 // -- The second and third operands have the same type; the result
2227 // is of that type.
2228 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2229 return LTy;
2230
2231 // -- The second and third operands have arithmetic or enumeration type;
2232 // the usual arithmetic conversions are performed to bring them to a
2233 // common type, and the result is of that type.
2234 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2235 UsualArithmeticConversions(LHS, RHS);
2236 return LHS->getType();
2237 }
2238
2239 // -- The second and third operands have pointer type, or one has pointer
2240 // type and the other is a null pointer constant; pointer conversions
2241 // and qualification conversions are performed to bring them to their
2242 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002243 // -- The second and third operands have pointer to member type, or one has
2244 // pointer to member type and the other is a null pointer constant;
2245 // pointer to member conversions and qualification conversions are
2246 // performed to bring them to a common type, whose cv-qualification
2247 // shall match the cv-qualification of either the second or the third
2248 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002249 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002250 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002251 isSFINAEContext()? 0 : &NonStandardCompositeType);
2252 if (!Composite.isNull()) {
2253 if (NonStandardCompositeType)
2254 Diag(QuestionLoc,
2255 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2256 << LTy << RTy << Composite
2257 << LHS->getSourceRange() << RHS->getSourceRange();
2258
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002259 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002260 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002261
Douglas Gregor697a3912010-04-01 22:47:07 +00002262 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002263 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2264 if (!Composite.isNull())
2265 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002266
Sebastian Redl1a99f442009-04-16 17:51:27 +00002267 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2268 << LHS->getType() << RHS->getType()
2269 << LHS->getSourceRange() << RHS->getSourceRange();
2270 return QualType();
2271}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002272
2273/// \brief Find a merged pointer type and convert the two expressions to it.
2274///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002275/// This finds the composite pointer type (or member pointer type) for @p E1
2276/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2277/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002278/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002279///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002280/// \param Loc The location of the operator requiring these two expressions to
2281/// be converted to the composite pointer type.
2282///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002283/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2284/// a non-standard (but still sane) composite type to which both expressions
2285/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2286/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002287QualType Sema::FindCompositePointerType(SourceLocation Loc,
2288 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002289 bool *NonStandardCompositeType) {
2290 if (NonStandardCompositeType)
2291 *NonStandardCompositeType = false;
2292
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002293 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2294 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002295
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002296 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2297 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002298 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002299
2300 // C++0x 5.9p2
2301 // Pointer conversions and qualification conversions are performed on
2302 // pointer operands to bring them to their composite pointer type. If
2303 // one operand is a null pointer constant, the composite pointer type is
2304 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002305 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002306 if (T2->isMemberPointerType())
2307 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2308 else
2309 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002310 return T2;
2311 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002312 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002313 if (T1->isMemberPointerType())
2314 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2315 else
2316 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002317 return T1;
2318 }
Mike Stump11289f42009-09-09 15:08:12 +00002319
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002320 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002321 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2322 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002323 return QualType();
2324
2325 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2326 // the other has type "pointer to cv2 T" and the composite pointer type is
2327 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2328 // Otherwise, the composite pointer type is a pointer type similar to the
2329 // type of one of the operands, with a cv-qualification signature that is
2330 // the union of the cv-qualification signatures of the operand types.
2331 // In practice, the first part here is redundant; it's subsumed by the second.
2332 // What we do here is, we build the two possible composite types, and try the
2333 // conversions in both directions. If only one works, or if the two composite
2334 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002335 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002336 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2337 QualifierVector QualifierUnion;
2338 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2339 ContainingClassVector;
2340 ContainingClassVector MemberOfClass;
2341 QualType Composite1 = Context.getCanonicalType(T1),
2342 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002343 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002344 do {
2345 const PointerType *Ptr1, *Ptr2;
2346 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2347 (Ptr2 = Composite2->getAs<PointerType>())) {
2348 Composite1 = Ptr1->getPointeeType();
2349 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002350
2351 // If we're allowed to create a non-standard composite type, keep track
2352 // of where we need to fill in additional 'const' qualifiers.
2353 if (NonStandardCompositeType &&
2354 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2355 NeedConstBefore = QualifierUnion.size();
2356
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002357 QualifierUnion.push_back(
2358 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2359 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2360 continue;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002363 const MemberPointerType *MemPtr1, *MemPtr2;
2364 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2365 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2366 Composite1 = MemPtr1->getPointeeType();
2367 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002368
2369 // If we're allowed to create a non-standard composite type, keep track
2370 // of where we need to fill in additional 'const' qualifiers.
2371 if (NonStandardCompositeType &&
2372 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2373 NeedConstBefore = QualifierUnion.size();
2374
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002375 QualifierUnion.push_back(
2376 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2377 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2378 MemPtr2->getClass()));
2379 continue;
2380 }
Mike Stump11289f42009-09-09 15:08:12 +00002381
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002382 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002383
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002384 // Cannot unwrap any more types.
2385 break;
2386 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002387
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002388 if (NeedConstBefore && NonStandardCompositeType) {
2389 // Extension: Add 'const' to qualifiers that come before the first qualifier
2390 // mismatch, so that our (non-standard!) composite type meets the
2391 // requirements of C++ [conv.qual]p4 bullet 3.
2392 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2393 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2394 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2395 *NonStandardCompositeType = true;
2396 }
2397 }
2398 }
2399
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002400 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002401 ContainingClassVector::reverse_iterator MOC
2402 = MemberOfClass.rbegin();
2403 for (QualifierVector::reverse_iterator
2404 I = QualifierUnion.rbegin(),
2405 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002406 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002407 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002408 if (MOC->first && MOC->second) {
2409 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002410 Composite1 = Context.getMemberPointerType(
2411 Context.getQualifiedType(Composite1, Quals),
2412 MOC->first);
2413 Composite2 = Context.getMemberPointerType(
2414 Context.getQualifiedType(Composite2, Quals),
2415 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002416 } else {
2417 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002418 Composite1
2419 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2420 Composite2
2421 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002422 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002423 }
2424
Douglas Gregor19175ff2010-04-16 23:20:25 +00002425 // Try to convert to the first composite pointer type.
2426 InitializedEntity Entity1
2427 = InitializedEntity::InitializeTemporary(Composite1);
2428 InitializationKind Kind
2429 = InitializationKind::CreateCopy(Loc, SourceLocation());
2430 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2431 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Douglas Gregor19175ff2010-04-16 23:20:25 +00002433 if (E1ToC1 && E2ToC1) {
2434 // Conversion to Composite1 is viable.
2435 if (!Context.hasSameType(Composite1, Composite2)) {
2436 // Composite2 is a different type from Composite1. Check whether
2437 // Composite2 is also viable.
2438 InitializedEntity Entity2
2439 = InitializedEntity::InitializeTemporary(Composite2);
2440 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2441 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2442 if (E1ToC2 && E2ToC2) {
2443 // Both Composite1 and Composite2 are viable and are different;
2444 // this is an ambiguity.
2445 return QualType();
2446 }
2447 }
2448
2449 // Convert E1 to Composite1
2450 OwningExprResult E1Result
2451 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2452 if (E1Result.isInvalid())
2453 return QualType();
2454 E1 = E1Result.takeAs<Expr>();
2455
2456 // Convert E2 to Composite1
2457 OwningExprResult E2Result
2458 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2459 if (E2Result.isInvalid())
2460 return QualType();
2461 E2 = E2Result.takeAs<Expr>();
2462
2463 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002464 }
2465
Douglas Gregor19175ff2010-04-16 23:20:25 +00002466 // Check whether Composite2 is viable.
2467 InitializedEntity Entity2
2468 = InitializedEntity::InitializeTemporary(Composite2);
2469 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2470 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2471 if (!E1ToC2 || !E2ToC2)
2472 return QualType();
2473
2474 // Convert E1 to Composite2
2475 OwningExprResult E1Result
2476 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2477 if (E1Result.isInvalid())
2478 return QualType();
2479 E1 = E1Result.takeAs<Expr>();
2480
2481 // Convert E2 to Composite2
2482 OwningExprResult E2Result
2483 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2484 if (E2Result.isInvalid())
2485 return QualType();
2486 E2 = E2Result.takeAs<Expr>();
2487
2488 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002489}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002490
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002491Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002492 if (!Context.getLangOptions().CPlusPlus)
2493 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002494
Douglas Gregor363b1512009-12-24 18:51:59 +00002495 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2496
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002497 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002498 if (!RT)
2499 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002500
John McCall67da35c2010-02-04 22:26:26 +00002501 // If this is the result of a call expression, our source might
2502 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002503 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2504 QualType Ty = CE->getCallee()->getType();
2505 if (const PointerType *PT = Ty->getAs<PointerType>())
2506 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002507 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2508 Ty = BPT->getPointeeType();
2509
John McCall9dd450b2009-09-21 23:43:11 +00002510 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002511 if (FTy->getResultType()->isReferenceType())
2512 return Owned(E);
2513 }
John McCall67da35c2010-02-04 22:26:26 +00002514
2515 // That should be enough to guarantee that this type is complete.
2516 // If it has a trivial destructor, we can avoid the extra copy.
2517 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2518 if (RD->hasTrivialDestructor())
2519 return Owned(E);
2520
Mike Stump11289f42009-09-09 15:08:12 +00002521 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002522 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002523 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002524 if (CXXDestructorDecl *Destructor =
John McCall8e36d532010-04-07 00:41:46 +00002525 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002526 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002527 CheckDestructorAccess(E->getExprLoc(), Destructor,
2528 PDiag(diag::err_access_dtor_temp)
2529 << E->getType());
2530 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002531 // FIXME: Add the temporary to the temporaries vector.
2532 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2533}
2534
Anders Carlsson6e997b22009-12-15 20:51:39 +00002535Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002536 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002537
John McCallcc7e5bf2010-05-06 08:58:33 +00002538 // Check any implicit conversions within the expression.
2539 CheckImplicitConversions(SubExpr);
2540
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002541 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2542 assert(ExprTemporaries.size() >= FirstTemporary);
2543 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002544 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002545
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002546 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002547 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002548 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002549 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2550 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002551
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002552 return E;
2553}
2554
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002555Sema::OwningExprResult
2556Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2557 if (SubExpr.isInvalid())
2558 return ExprError();
2559
2560 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2561}
2562
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002563FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2564 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2565 assert(ExprTemporaries.size() >= FirstTemporary);
2566
2567 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2568 CXXTemporary **Temporaries =
2569 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2570
2571 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2572
2573 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2574 ExprTemporaries.end());
2575
2576 return E;
2577}
2578
Mike Stump11289f42009-09-09 15:08:12 +00002579Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002580Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002581 tok::TokenKind OpKind, TypeTy *&ObjectType,
2582 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002583 // Since this might be a postfix expression, get rid of ParenListExprs.
2584 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002586 Expr *BaseExpr = (Expr*)Base.get();
2587 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002589 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002590 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002591 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002592 // If we have a pointer to a dependent type and are using the -> operator,
2593 // the object type is the type that the pointer points to. We might still
2594 // have enough information about that type to do something useful.
2595 if (OpKind == tok::arrow)
2596 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2597 BaseType = Ptr->getPointeeType();
2598
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002599 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002600 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002601 return move(Base);
2602 }
Mike Stump11289f42009-09-09 15:08:12 +00002603
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002604 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002605 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002606 // returned, with the original second operand.
2607 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002608 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002609 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002610 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002611 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002612
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002613 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002614 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002615 BaseExpr = (Expr*)Base.get();
2616 if (BaseExpr == NULL)
2617 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002618 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002619 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002620 BaseType = BaseExpr->getType();
2621 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002622 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002623 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002624 for (unsigned i = 0; i < Locations.size(); i++)
2625 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002626 return ExprError();
2627 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002628 }
Mike Stump11289f42009-09-09 15:08:12 +00002629
Douglas Gregore4f764f2009-11-20 19:58:21 +00002630 if (BaseType->isPointerType())
2631 BaseType = BaseType->getPointeeType();
2632 }
Mike Stump11289f42009-09-09 15:08:12 +00002633
2634 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002635 // vector types or Objective-C interfaces. Just return early and let
2636 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002637 if (!BaseType->isRecordType()) {
2638 // C++ [basic.lookup.classref]p2:
2639 // [...] If the type of the object expression is of pointer to scalar
2640 // type, the unqualified-id is looked up in the context of the complete
2641 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002642 //
2643 // This also indicates that we should be parsing a
2644 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002645 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002646 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002647 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
Douglas Gregor3fad6172009-11-17 05:17:33 +00002650 // The object type must be complete (or dependent).
2651 if (!BaseType->isDependentType() &&
2652 RequireCompleteType(OpLoc, BaseType,
2653 PDiag(diag::err_incomplete_member_access)))
2654 return ExprError();
2655
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002656 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002657 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002658 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002659 // type C (or of pointer to a class type C), the unqualified-id is looked
2660 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002661 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002662 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002663}
2664
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002665Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2666 ExprArg MemExpr) {
2667 Expr *E = (Expr *) MemExpr.get();
2668 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2669 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2670 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002671 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002672
2673 return ActOnCallExpr(/*Scope*/ 0,
2674 move(MemExpr),
2675 /*LPLoc*/ ExpectedLParenLoc,
2676 Sema::MultiExprArg(*this, 0, 0),
2677 /*CommaLocs*/ 0,
2678 /*RPLoc*/ ExpectedLParenLoc);
2679}
Douglas Gregore610ada2010-02-24 18:44:31 +00002680
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002681Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2682 SourceLocation OpLoc,
2683 tok::TokenKind OpKind,
2684 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002685 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002686 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002687 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002688 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002689 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002690 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002691
2692 // C++ [expr.pseudo]p2:
2693 // The left-hand side of the dot operator shall be of scalar type. The
2694 // left-hand side of the arrow operator shall be of pointer to scalar type.
2695 // This scalar type is the object type.
2696 Expr *BaseE = (Expr *)Base.get();
2697 QualType ObjectType = BaseE->getType();
2698 if (OpKind == tok::arrow) {
2699 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2700 ObjectType = Ptr->getPointeeType();
2701 } else if (!BaseE->isTypeDependent()) {
2702 // The user wrote "p->" when she probably meant "p."; fix it.
2703 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2704 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002705 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002706 if (isSFINAEContext())
2707 return ExprError();
2708
2709 OpKind = tok::period;
2710 }
2711 }
2712
2713 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2714 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2715 << ObjectType << BaseE->getSourceRange();
2716 return ExprError();
2717 }
2718
2719 // C++ [expr.pseudo]p2:
2720 // [...] The cv-unqualified versions of the object type and of the type
2721 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002722 if (DestructedTypeInfo) {
2723 QualType DestructedType = DestructedTypeInfo->getType();
2724 SourceLocation DestructedTypeStart
2725 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2726 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2727 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2728 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2729 << ObjectType << DestructedType << BaseE->getSourceRange()
2730 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2731
2732 // Recover by setting the destructed type to the object type.
2733 DestructedType = ObjectType;
2734 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2735 DestructedTypeStart);
2736 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2737 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002738 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002739
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002740 // C++ [expr.pseudo]p2:
2741 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2742 // form
2743 //
2744 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2745 //
2746 // shall designate the same scalar type.
2747 if (ScopeTypeInfo) {
2748 QualType ScopeType = ScopeTypeInfo->getType();
2749 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2750 !Context.hasSameType(ScopeType, ObjectType)) {
2751
2752 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2753 diag::err_pseudo_dtor_type_mismatch)
2754 << ObjectType << ScopeType << BaseE->getSourceRange()
2755 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2756
2757 ScopeType = QualType();
2758 ScopeTypeInfo = 0;
2759 }
2760 }
2761
2762 OwningExprResult Result
2763 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2764 Base.takeAs<Expr>(),
2765 OpKind == tok::arrow,
2766 OpLoc,
2767 (NestedNameSpecifier *) SS.getScopeRep(),
2768 SS.getRange(),
2769 ScopeTypeInfo,
2770 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002771 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002772 Destructed));
2773
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002774 if (HasTrailingLParen)
2775 return move(Result);
2776
Douglas Gregor678f90d2010-02-25 01:56:36 +00002777 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002778}
2779
2780Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2781 SourceLocation OpLoc,
2782 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002783 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002784 UnqualifiedId &FirstTypeName,
2785 SourceLocation CCLoc,
2786 SourceLocation TildeLoc,
2787 UnqualifiedId &SecondTypeName,
2788 bool HasTrailingLParen) {
2789 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2790 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2791 "Invalid first type name in pseudo-destructor");
2792 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2793 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2794 "Invalid second type name in pseudo-destructor");
2795
2796 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002797
2798 // C++ [expr.pseudo]p2:
2799 // The left-hand side of the dot operator shall be of scalar type. The
2800 // left-hand side of the arrow operator shall be of pointer to scalar type.
2801 // This scalar type is the object type.
2802 QualType ObjectType = BaseE->getType();
2803 if (OpKind == tok::arrow) {
2804 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2805 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002806 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002807 // The user wrote "p->" when she probably meant "p."; fix it.
2808 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002809 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002810 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002811 if (isSFINAEContext())
2812 return ExprError();
2813
2814 OpKind = tok::period;
2815 }
2816 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002817
2818 // Compute the object type that we should use for name lookup purposes. Only
2819 // record types and dependent types matter.
2820 void *ObjectTypePtrForLookup = 0;
2821 if (!SS.isSet()) {
2822 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2823 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2824 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2825 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002826
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002827 // Convert the name of the type being destructed (following the ~) into a
2828 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002829 QualType DestructedType;
2830 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002831 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002832 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2833 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2834 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002835 S, &SS, true, ObjectTypePtrForLookup);
2836 if (!T &&
2837 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2838 (!SS.isSet() && ObjectType->isDependentType()))) {
2839 // The name of the type being destroyed is a dependent name, and we
2840 // couldn't find anything useful in scope. Just store the identifier and
2841 // it's location, and we'll perform (qualified) name lookup again at
2842 // template instantiation time.
2843 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2844 SecondTypeName.StartLocation);
2845 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002846 Diag(SecondTypeName.StartLocation,
2847 diag::err_pseudo_dtor_destructor_non_type)
2848 << SecondTypeName.Identifier << ObjectType;
2849 if (isSFINAEContext())
2850 return ExprError();
2851
2852 // Recover by assuming we had the right type all along.
2853 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002854 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002855 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002856 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002857 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002858 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002859 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2860 TemplateId->getTemplateArgs(),
2861 TemplateId->NumArgs);
2862 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2863 TemplateId->TemplateNameLoc,
2864 TemplateId->LAngleLoc,
2865 TemplateArgsPtr,
2866 TemplateId->RAngleLoc);
2867 if (T.isInvalid() || !T.get()) {
2868 // Recover by assuming we had the right type all along.
2869 DestructedType = ObjectType;
2870 } else
2871 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002872 }
2873
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002874 // If we've performed some kind of recovery, (re-)build the type source
2875 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002876 if (!DestructedType.isNull()) {
2877 if (!DestructedTypeInfo)
2878 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002879 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002880 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2881 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002882
2883 // Convert the name of the scope type (the type prior to '::') into a type.
2884 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002885 QualType ScopeType;
2886 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2887 FirstTypeName.Identifier) {
2888 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2889 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2890 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002891 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002892 if (!T) {
2893 Diag(FirstTypeName.StartLocation,
2894 diag::err_pseudo_dtor_destructor_non_type)
2895 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002896
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002897 if (isSFINAEContext())
2898 return ExprError();
2899
2900 // Just drop this type. It's unnecessary anyway.
2901 ScopeType = QualType();
2902 } else
2903 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002904 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002905 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002906 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002907 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2908 TemplateId->getTemplateArgs(),
2909 TemplateId->NumArgs);
2910 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2911 TemplateId->TemplateNameLoc,
2912 TemplateId->LAngleLoc,
2913 TemplateArgsPtr,
2914 TemplateId->RAngleLoc);
2915 if (T.isInvalid() || !T.get()) {
2916 // Recover by dropping this type.
2917 ScopeType = QualType();
2918 } else
2919 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002920 }
2921 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00002922
2923 if (!ScopeType.isNull() && !ScopeTypeInfo)
2924 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2925 FirstTypeName.StartLocation);
2926
2927
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002928 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002929 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002930 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00002931}
2932
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002933CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00002934 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002935 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00002936 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2937 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00002938 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2939
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002940 MemberExpr *ME =
2941 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2942 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002943 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002944 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2945 CXXMemberCallExpr *CE =
2946 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2947 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002948 return CE;
2949}
2950
Anders Carlsson85a307d2009-05-17 18:41:29 +00002951Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2952 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002953 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002954 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00002955 else
2956 return ExprError();
2957
Anders Carlsson85a307d2009-05-17 18:41:29 +00002958 return Owned(FullExpr);
2959}