blob: f337a429ca7294fddefcf49e8406fb140340554e [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. [...]
Douglas Gregor88d292c2010-05-13 16:44:06 +0000317 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000318 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000319
320 // We require a vtable to query the type at run time.
321 MarkVTableUsed(TypeidLoc, RecordD);
322 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000323 }
324
325 // C++ [expr.typeid]p4:
326 // [...] If the type of the type-id is a reference to a possibly
327 // cv-qualified type, the result of the typeid expression refers to a
328 // std::type_info object representing the cv-unqualified referenced
329 // type.
330 if (T.hasQualifiers()) {
331 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
332 E->isLvalue(Context));
333 Operand.release();
334 Operand = Owned(E);
335 }
336 }
337
338 // If this is an unevaluated operand, clear out the set of
339 // declaration references we have been computing and eliminate any
340 // temporaries introduced in its computation.
341 if (isUnevaluatedOperand)
342 ExprEvalContexts.back().Context = Unevaluated;
343
344 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
345 Operand.takeAs<Expr>(),
346 SourceRange(TypeidLoc, RParenLoc)));
347}
348
349/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000350Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000351Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
352 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000353 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000354 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000355 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000356
Chris Lattnerec7f7732008-11-20 05:51:55 +0000357 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000358 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
359 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000360 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000361 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000362 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000363
Sebastian Redlc4704762008-11-11 11:37:55 +0000364 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000365
366 if (isType) {
367 // The operand is a type; handle it as such.
368 TypeSourceInfo *TInfo = 0;
369 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
370 if (T.isNull())
371 return ExprError();
372
373 if (!TInfo)
374 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000375
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Douglas Gregor9da64192010-04-26 22:37:10 +0000379 // The operand is an expression.
380 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000381}
382
Steve Naroff66356bd2007-09-16 14:56:35 +0000383/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000384Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000385Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000386 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000387 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000388 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
389 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000390}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000391
Sebastian Redl576fd422009-05-10 18:38:11 +0000392/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
393Action::OwningExprResult
394Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
395 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
396}
397
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000398/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000399Action::OwningExprResult
400Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000401 Expr *Ex = E.takeAs<Expr>();
402 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
403 return ExprError();
404 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
405}
406
407/// CheckCXXThrowOperand - Validate the operand of a throw.
408bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
409 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000410 // A throw-expression initializes a temporary object, called the exception
411 // object, the type of which is determined by removing any top-level
412 // cv-qualifiers from the static type of the operand of throw and adjusting
413 // the type from "array of T" or "function returning T" to "pointer to T"
414 // or "pointer to function returning T", [...]
415 if (E->getType().hasQualifiers())
416 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
417 E->isLvalue(Context) == Expr::LV_Valid);
418
Sebastian Redl4de47b42009-04-27 20:27:31 +0000419 DefaultFunctionArrayConversion(E);
420
421 // If the type of the exception would be an incomplete type or a pointer
422 // to an incomplete type other than (cv) void the program is ill-formed.
423 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000424 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000425 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000426 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000427 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000428 }
429 if (!isPointer || !Ty->isVoidType()) {
430 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000431 PDiag(isPointer ? diag::err_throw_incomplete_ptr
432 : diag::err_throw_incomplete)
433 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000434 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000435
Douglas Gregore8154332010-04-15 18:05:39 +0000436 if (RequireNonAbstractType(ThrowLoc, E->getType(),
437 PDiag(diag::err_throw_abstract_type)
438 << E->getSourceRange()))
439 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000440 }
441
John McCall2e6567a2010-04-22 01:10:34 +0000442 // Initialize the exception result. This implicitly weeds out
443 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000444 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000445 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000446 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
447 /*NRVO=*/false);
John McCall2e6567a2010-04-22 01:10:34 +0000448 OwningExprResult Res = PerformCopyInitialization(Entity,
449 SourceLocation(),
450 Owned(E));
451 if (Res.isInvalid())
452 return true;
453 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000454
455 // If we are throwing a polymorphic class type or pointer thereof,
456 // exception handling will make use of the vtable.
457 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
458 MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl()));
459
Sebastian Redl4de47b42009-04-27 20:27:31 +0000460 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000461}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000462
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000463Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000464 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
465 /// is a non-lvalue expression whose value is the address of the object for
466 /// which the function is called.
467
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000468 if (!isa<FunctionDecl>(CurContext))
469 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000470
471 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
472 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000473 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000474 MD->getThisType(Context),
475 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000476
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000477 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000478}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000479
480/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
481/// Can be interpreted either as function-style casting ("int(x)")
482/// or class type construction ("ClassType(x,y,z)")
483/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000484Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000485Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
486 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000487 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000488 SourceLocation *CommaLocs,
489 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000490 if (!TypeRep)
491 return ExprError();
492
John McCall97513962010-01-15 18:39:57 +0000493 TypeSourceInfo *TInfo;
494 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
495 if (!TInfo)
496 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000497 unsigned NumExprs = exprs.size();
498 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000499 SourceLocation TyBeginLoc = TypeRange.getBegin();
500 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
501
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000502 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000503 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000504 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000505
506 return Owned(CXXUnresolvedConstructExpr::Create(Context,
507 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000508 LParenLoc,
509 Exprs, NumExprs,
510 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000511 }
512
Anders Carlsson55243162009-08-27 03:53:50 +0000513 if (Ty->isArrayType())
514 return ExprError(Diag(TyBeginLoc,
515 diag::err_value_init_for_array_type) << FullRange);
516 if (!Ty->isVoidType() &&
517 RequireCompleteType(TyBeginLoc, Ty,
518 PDiag(diag::err_invalid_incomplete_type_use)
519 << FullRange))
520 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000521
Anders Carlsson55243162009-08-27 03:53:50 +0000522 if (RequireNonAbstractType(TyBeginLoc, Ty,
523 diag::err_allocation_of_abstract_type))
524 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000525
526
Douglas Gregordd04d332009-01-16 18:33:17 +0000527 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000528 // If the expression list is a single expression, the type conversion
529 // expression is equivalent (in definedness, and if defined in meaning) to the
530 // corresponding cast expression.
531 //
532 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000533 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000534 CXXBaseSpecifierArray BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000535 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
536 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000537 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000538
539 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000540
541 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000542 TInfo, TyBeginLoc, Kind,
Anders Carlsson5d270e82010-04-24 18:38:56 +0000543 Exprs[0], BasePath,
544 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000545 }
546
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000547 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000548 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000549
Mike Stump11289f42009-09-09 15:08:12 +0000550 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000551 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000552 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
553 InitializationKind Kind
554 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
555 LParenLoc, RParenLoc)
556 : InitializationKind::CreateValue(TypeRange.getBegin(),
557 LParenLoc, RParenLoc);
558 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
559 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
560 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000561
Eli Friedmana6824272010-01-31 20:58:15 +0000562 // FIXME: Improve AST representation?
563 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000564 }
565
566 // Fall through to value-initialize an object of class type that
567 // doesn't have a user-declared default constructor.
568 }
569
570 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000571 // If the expression list specifies more than a single value, the type shall
572 // be a class with a suitably declared constructor.
573 //
574 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000575 return ExprError(Diag(CommaLocs[0],
576 diag::err_builtin_func_cast_more_than_one_arg)
577 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000578
579 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000580 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000581 // The expression T(), where T is a simple-type-specifier for a non-array
582 // complete object type or the (possibly cv-qualified) void type, creates an
583 // rvalue of the specified type, which is value-initialized.
584 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000585 exprs.release();
586 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000587}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000588
589
Sebastian Redlbd150f42008-11-21 19:14:01 +0000590/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
591/// @code new (memory) int[size][4] @endcode
592/// or
593/// @code ::new Foo(23, "hello") @endcode
594/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000595Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000596Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000597 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000598 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000599 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000600 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000601 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000602 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000603 // If the specified type is an array, unwrap it and save the expression.
604 if (D.getNumTypeObjects() > 0 &&
605 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
606 DeclaratorChunk &Chunk = D.getTypeObject(0);
607 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000608 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
609 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000610 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000611 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
612 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000613
614 if (ParenTypeId) {
615 // Can't have dynamic array size when the type-id is in parentheses.
616 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
617 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
618 !NumElts->isIntegerConstantExpr(Context)) {
619 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
620 << NumElts->getSourceRange();
621 return ExprError();
622 }
623 }
624
Sebastian Redl351bb782008-12-02 14:43:59 +0000625 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000626 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000627 }
628
Douglas Gregor73341c42009-09-11 00:18:58 +0000629 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000630 if (ArraySize) {
631 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000632 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
633 break;
634
635 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
636 if (Expr *NumElts = (Expr *)Array.NumElts) {
637 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
638 !NumElts->isIntegerConstantExpr(Context)) {
639 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
640 << NumElts->getSourceRange();
641 return ExprError();
642 }
643 }
644 }
645 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000646
John McCallbcd03502009-12-07 02:54:59 +0000647 //FIXME: Store TypeSourceInfo in CXXNew expression.
648 TypeSourceInfo *TInfo = 0;
649 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000650 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000651 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000652
Mike Stump11289f42009-09-09 15:08:12 +0000653 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000654 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000655 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000656 PlacementRParen,
657 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000658 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000659 D.getSourceRange().getBegin(),
660 D.getSourceRange(),
661 Owned(ArraySize),
662 ConstructorLParen,
663 move(ConstructorArgs),
664 ConstructorRParen);
665}
666
Mike Stump11289f42009-09-09 15:08:12 +0000667Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000668Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
669 SourceLocation PlacementLParen,
670 MultiExprArg PlacementArgs,
671 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000672 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000673 QualType AllocType,
674 SourceLocation TypeLoc,
675 SourceRange TypeRange,
676 ExprArg ArraySizeE,
677 SourceLocation ConstructorLParen,
678 MultiExprArg ConstructorArgs,
679 SourceLocation ConstructorRParen) {
680 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000681 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000682
Douglas Gregorcda95f42010-05-16 16:01:03 +0000683 // Per C++0x [expr.new]p5, the type being constructed may be a
684 // typedef of an array type.
685 if (!ArraySizeE.get()) {
686 if (const ConstantArrayType *Array
687 = Context.getAsConstantArrayType(AllocType)) {
688 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
689 Context.getSizeType(),
690 TypeRange.getEnd()));
691 AllocType = Array->getElementType();
692 }
693 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000694
Douglas Gregorcda95f42010-05-16 16:01:03 +0000695 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000696
Sebastian Redlbd150f42008-11-21 19:14:01 +0000697 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
698 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000699 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000700 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000701 QualType SizeType = ArraySize->getType();
702 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000703 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
704 diag::err_array_size_not_integral)
705 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000706 // Let's see if this is a constant < 0. If so, we reject it out of hand.
707 // We don't care about special rules, so we tell the machinery it's not
708 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000709 if (!ArraySize->isValueDependent()) {
710 llvm::APSInt Value;
711 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
712 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000713 llvm::APInt::getNullValue(Value.getBitWidth()),
714 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000715 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
716 diag::err_typecheck_negative_array_size)
717 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000718 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000719 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000720
Eli Friedman06ed2a52009-10-20 08:27:19 +0000721 ImpCastExprToType(ArraySize, Context.getSizeType(),
722 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000723 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000724
Sebastian Redlbd150f42008-11-21 19:14:01 +0000725 FunctionDecl *OperatorNew = 0;
726 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000727 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
728 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000729
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000730 if (!AllocType->isDependentType() &&
731 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
732 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000733 SourceRange(PlacementLParen, PlacementRParen),
734 UseGlobal, AllocType, ArraySize, PlaceArgs,
735 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000736 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000737 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000738 if (OperatorNew) {
739 // Add default arguments, if any.
740 const FunctionProtoType *Proto =
741 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000742 VariadicCallType CallType =
743 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000744
745 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
746 Proto, 1, PlaceArgs, NumPlaceArgs,
747 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000748 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000749
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000750 NumPlaceArgs = AllPlaceArgs.size();
751 if (NumPlaceArgs > 0)
752 PlaceArgs = &AllPlaceArgs[0];
753 }
754
Sebastian Redlbd150f42008-11-21 19:14:01 +0000755 bool Init = ConstructorLParen.isValid();
756 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000757 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000758 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
759 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000760 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
761
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000762 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000763 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000764 SourceRange InitRange(ConsArgs[0]->getLocStart(),
765 ConsArgs[NumConsArgs - 1]->getLocEnd());
766
767 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
768 return ExprError();
769 }
770
Douglas Gregor85dabae2009-12-16 01:38:02 +0000771 if (!AllocType->isDependentType() &&
772 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
773 // C++0x [expr.new]p15:
774 // A new-expression that creates an object of type T initializes that
775 // object as follows:
776 InitializationKind Kind
777 // - If the new-initializer is omitted, the object is default-
778 // initialized (8.5); if no initialization is performed,
779 // the object has indeterminate value
780 = !Init? InitializationKind::CreateDefault(TypeLoc)
781 // - Otherwise, the new-initializer is interpreted according to the
782 // initialization rules of 8.5 for direct-initialization.
783 : InitializationKind::CreateDirect(TypeLoc,
784 ConstructorLParen,
785 ConstructorRParen);
786
Douglas Gregor85dabae2009-12-16 01:38:02 +0000787 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000788 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000789 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000790 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
791 move(ConstructorArgs));
792 if (FullInit.isInvalid())
793 return ExprError();
794
795 // FullInit is our initializer; walk through it to determine if it's a
796 // constructor call, which CXXNewExpr handles directly.
797 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
798 if (CXXBindTemporaryExpr *Binder
799 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
800 FullInitExpr = Binder->getSubExpr();
801 if (CXXConstructExpr *Construct
802 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
803 Constructor = Construct->getConstructor();
804 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
805 AEnd = Construct->arg_end();
806 A != AEnd; ++A)
807 ConvertedConstructorArgs.push_back(A->Retain());
808 } else {
809 // Take the converted initializer.
810 ConvertedConstructorArgs.push_back(FullInit.release());
811 }
812 } else {
813 // No initialization required.
814 }
815
816 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000817 NumConsArgs = ConvertedConstructorArgs.size();
818 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000819 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000820
Douglas Gregor6642ca22010-02-26 05:06:18 +0000821 // Mark the new and delete operators as referenced.
822 if (OperatorNew)
823 MarkDeclarationReferenced(StartLoc, OperatorNew);
824 if (OperatorDelete)
825 MarkDeclarationReferenced(StartLoc, OperatorDelete);
826
Sebastian Redlbd150f42008-11-21 19:14:01 +0000827 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000828
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000829 PlacementArgs.release();
830 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000831 ArraySizeE.release();
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000832 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
833 PlaceArgs, NumPlaceArgs, ParenTypeId,
834 ArraySize, Constructor, Init,
835 ConsArgs, NumConsArgs, OperatorDelete,
836 ResultType, StartLoc,
837 Init ? ConstructorRParen :
838 SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000839}
840
841/// CheckAllocatedType - Checks that a type is suitable as the allocated type
842/// in a new-expression.
843/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000844bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000845 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000846 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
847 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000848 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000849 return Diag(Loc, diag::err_bad_new_type)
850 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000851 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000852 return Diag(Loc, diag::err_bad_new_type)
853 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000854 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000855 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000856 PDiag(diag::err_new_incomplete_type)
857 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000858 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000859 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000860 diag::err_allocation_of_abstract_type))
861 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000862
Sebastian Redlbd150f42008-11-21 19:14:01 +0000863 return false;
864}
865
Douglas Gregor6642ca22010-02-26 05:06:18 +0000866/// \brief Determine whether the given function is a non-placement
867/// deallocation function.
868static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
869 if (FD->isInvalidDecl())
870 return false;
871
872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
873 return Method->isUsualDeallocationFunction();
874
875 return ((FD->getOverloadedOperator() == OO_Delete ||
876 FD->getOverloadedOperator() == OO_Array_Delete) &&
877 FD->getNumParams() == 1);
878}
879
Sebastian Redlfaf68082008-12-03 20:26:15 +0000880/// FindAllocationFunctions - Finds the overloads of operator new and delete
881/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000882bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
883 bool UseGlobal, QualType AllocType,
884 bool IsArray, Expr **PlaceArgs,
885 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000886 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000887 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000888 // --- Choosing an allocation function ---
889 // C++ 5.3.4p8 - 14 & 18
890 // 1) If UseGlobal is true, only look in the global scope. Else, also look
891 // in the scope of the allocated class.
892 // 2) If an array size is given, look for operator new[], else look for
893 // operator new.
894 // 3) The first argument is always size_t. Append the arguments from the
895 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000896
897 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
898 // We don't care about the actual value of this argument.
899 // FIXME: Should the Sema create the expression and embed it in the syntax
900 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000901 IntegerLiteral Size(llvm::APInt::getNullValue(
902 Context.Target.getPointerWidth(0)),
903 Context.getSizeType(),
904 SourceLocation());
905 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000906 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
907
Douglas Gregor6642ca22010-02-26 05:06:18 +0000908 // C++ [expr.new]p8:
909 // If the allocated type is a non-array type, the allocation
910 // function’s name is operator new and the deallocation function’s
911 // name is operator delete. If the allocated type is an array
912 // type, the allocation function’s name is operator new[] and the
913 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000914 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
915 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000916 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
917 IsArray ? OO_Array_Delete : OO_Delete);
918
Sebastian Redlfaf68082008-12-03 20:26:15 +0000919 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000920 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000921 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000922 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000923 AllocArgs.size(), Record, /*AllowMissing=*/true,
924 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000925 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000926 }
927 if (!OperatorNew) {
928 // Didn't find a member overload. Look for a global one.
929 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000930 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000931 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000932 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
933 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000934 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000935 }
936
John McCall0f55a032010-04-20 02:18:25 +0000937 // We don't need an operator delete if we're running under
938 // -fno-exceptions.
939 if (!getLangOptions().Exceptions) {
940 OperatorDelete = 0;
941 return false;
942 }
943
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000944 // FindAllocationOverload can change the passed in arguments, so we need to
945 // copy them back.
946 if (NumPlaceArgs > 0)
947 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000948
Douglas Gregor6642ca22010-02-26 05:06:18 +0000949 // C++ [expr.new]p19:
950 //
951 // If the new-expression begins with a unary :: operator, the
952 // deallocation function’s name is looked up in the global
953 // scope. Otherwise, if the allocated type is a class type T or an
954 // array thereof, the deallocation function’s name is looked up in
955 // the scope of T. If this lookup fails to find the name, or if
956 // the allocated type is not a class type or array thereof, the
957 // deallocation function’s name is looked up in the global scope.
958 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
959 if (AllocType->isRecordType() && !UseGlobal) {
960 CXXRecordDecl *RD
961 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
962 LookupQualifiedName(FoundDelete, RD);
963 }
John McCallfb6f5262010-03-18 08:19:33 +0000964 if (FoundDelete.isAmbiguous())
965 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000966
967 if (FoundDelete.empty()) {
968 DeclareGlobalNewDelete();
969 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
970 }
971
972 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000973
974 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
975
John McCallfb6f5262010-03-18 08:19:33 +0000976 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000977 // C++ [expr.new]p20:
978 // A declaration of a placement deallocation function matches the
979 // declaration of a placement allocation function if it has the
980 // same number of parameters and, after parameter transformations
981 // (8.3.5), all parameter types except the first are
982 // identical. [...]
983 //
984 // To perform this comparison, we compute the function type that
985 // the deallocation function should have, and use that type both
986 // for template argument deduction and for comparison purposes.
987 QualType ExpectedFunctionType;
988 {
989 const FunctionProtoType *Proto
990 = OperatorNew->getType()->getAs<FunctionProtoType>();
991 llvm::SmallVector<QualType, 4> ArgTypes;
992 ArgTypes.push_back(Context.VoidPtrTy);
993 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
994 ArgTypes.push_back(Proto->getArgType(I));
995
996 ExpectedFunctionType
997 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
998 ArgTypes.size(),
999 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001000 0, false, false, 0, 0,
1001 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001002 }
1003
1004 for (LookupResult::iterator D = FoundDelete.begin(),
1005 DEnd = FoundDelete.end();
1006 D != DEnd; ++D) {
1007 FunctionDecl *Fn = 0;
1008 if (FunctionTemplateDecl *FnTmpl
1009 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1010 // Perform template argument deduction to try to match the
1011 // expected function type.
1012 TemplateDeductionInfo Info(Context, StartLoc);
1013 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1014 continue;
1015 } else
1016 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1017
1018 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001019 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001020 }
1021 } else {
1022 // C++ [expr.new]p20:
1023 // [...] Any non-placement deallocation function matches a
1024 // non-placement allocation function. [...]
1025 for (LookupResult::iterator D = FoundDelete.begin(),
1026 DEnd = FoundDelete.end();
1027 D != DEnd; ++D) {
1028 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1029 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001030 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001031 }
1032 }
1033
1034 // C++ [expr.new]p20:
1035 // [...] If the lookup finds a single matching deallocation
1036 // function, that function will be called; otherwise, no
1037 // deallocation function will be called.
1038 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001039 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001040
1041 // C++0x [expr.new]p20:
1042 // If the lookup finds the two-parameter form of a usual
1043 // deallocation function (3.7.4.2) and that function, considered
1044 // as a placement deallocation function, would have been
1045 // selected as a match for the allocation function, the program
1046 // is ill-formed.
1047 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1048 isNonPlacementDeallocationFunction(OperatorDelete)) {
1049 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1050 << SourceRange(PlaceArgs[0]->getLocStart(),
1051 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1052 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1053 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001054 } else {
1055 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001056 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001057 }
1058 }
1059
Sebastian Redlfaf68082008-12-03 20:26:15 +00001060 return false;
1061}
1062
Sebastian Redl33a31012008-12-04 22:20:51 +00001063/// FindAllocationOverload - Find an fitting overload for the allocation
1064/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001065bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1066 DeclarationName Name, Expr** Args,
1067 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001068 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001069 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1070 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001071 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001072 if (AllowMissing)
1073 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001074 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001075 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001076 }
1077
John McCallfb6f5262010-03-18 08:19:33 +00001078 if (R.isAmbiguous())
1079 return true;
1080
1081 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001082
John McCallbc077cf2010-02-08 23:07:23 +00001083 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001084 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1085 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001086 // Even member operator new/delete are implicitly treated as
1087 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001088 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001089
John McCalla0296f72010-03-19 07:35:19 +00001090 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1091 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001092 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1093 Candidates,
1094 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001095 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001096 }
1097
John McCalla0296f72010-03-19 07:35:19 +00001098 FunctionDecl *Fn = cast<FunctionDecl>(D);
1099 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001100 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001101 }
1102
1103 // Do the resolution.
1104 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001105 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001106 case OR_Success: {
1107 // Got one!
1108 FunctionDecl *FnDecl = Best->Function;
1109 // The first argument is size_t, and the first parameter must be size_t,
1110 // too. This is checked on declaration and can be assumed. (It can't be
1111 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001112 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001113 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1114 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001115 OwningExprResult Result
1116 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1117 FnDecl->getParamDecl(i)),
1118 SourceLocation(),
1119 Owned(Args[i]->Retain()));
1120 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001121 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001122
1123 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001124 }
1125 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001126 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001127 return false;
1128 }
1129
1130 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001131 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001132 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001133 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001134 return true;
1135
1136 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001137 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001138 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001139 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001140 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001141
1142 case OR_Deleted:
1143 Diag(StartLoc, diag::err_ovl_deleted_call)
1144 << Best->Function->isDeleted()
1145 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001146 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001147 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001148 }
1149 assert(false && "Unreachable, bad result from BestViableFunction");
1150 return true;
1151}
1152
1153
Sebastian Redlfaf68082008-12-03 20:26:15 +00001154/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1155/// delete. These are:
1156/// @code
1157/// void* operator new(std::size_t) throw(std::bad_alloc);
1158/// void* operator new[](std::size_t) throw(std::bad_alloc);
1159/// void operator delete(void *) throw();
1160/// void operator delete[](void *) throw();
1161/// @endcode
1162/// Note that the placement and nothrow forms of new are *not* implicitly
1163/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001164void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001165 if (GlobalNewDeleteDeclared)
1166 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001167
1168 // C++ [basic.std.dynamic]p2:
1169 // [...] The following allocation and deallocation functions (18.4) are
1170 // implicitly declared in global scope in each translation unit of a
1171 // program
1172 //
1173 // void* operator new(std::size_t) throw(std::bad_alloc);
1174 // void* operator new[](std::size_t) throw(std::bad_alloc);
1175 // void operator delete(void*) throw();
1176 // void operator delete[](void*) throw();
1177 //
1178 // These implicit declarations introduce only the function names operator
1179 // new, operator new[], operator delete, operator delete[].
1180 //
1181 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1182 // "std" or "bad_alloc" as necessary to form the exception specification.
1183 // However, we do not make these implicit declarations visible to name
1184 // lookup.
1185 if (!StdNamespace) {
1186 // The "std" namespace has not yet been defined, so build one implicitly.
1187 StdNamespace = NamespaceDecl::Create(Context,
1188 Context.getTranslationUnitDecl(),
1189 SourceLocation(),
1190 &PP.getIdentifierTable().get("std"));
1191 StdNamespace->setImplicit(true);
1192 }
1193
1194 if (!StdBadAlloc) {
1195 // The "std::bad_alloc" class has not yet been declared, so build it
1196 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001197 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor87f54062009-09-15 22:30:29 +00001198 StdNamespace,
1199 SourceLocation(),
1200 &PP.getIdentifierTable().get("bad_alloc"),
1201 SourceLocation(), 0);
1202 StdBadAlloc->setImplicit(true);
1203 }
1204
Sebastian Redlfaf68082008-12-03 20:26:15 +00001205 GlobalNewDeleteDeclared = true;
1206
1207 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1208 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001209 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001210
Sebastian Redlfaf68082008-12-03 20:26:15 +00001211 DeclareGlobalAllocationFunction(
1212 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001213 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001214 DeclareGlobalAllocationFunction(
1215 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001216 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001217 DeclareGlobalAllocationFunction(
1218 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1219 Context.VoidTy, VoidPtr);
1220 DeclareGlobalAllocationFunction(
1221 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1222 Context.VoidTy, VoidPtr);
1223}
1224
1225/// DeclareGlobalAllocationFunction - Declares a single implicit global
1226/// allocation function if it doesn't already exist.
1227void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001228 QualType Return, QualType Argument,
1229 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001230 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1231
1232 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001233 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001234 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001235 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001236 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001237 // Only look at non-template functions, as it is the predefined,
1238 // non-templated allocation function we are trying to declare here.
1239 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1240 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001241 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001242 Func->getParamDecl(0)->getType().getUnqualifiedType());
1243 // FIXME: Do we need to check for default arguments here?
1244 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1245 return;
1246 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001247 }
1248 }
1249
Douglas Gregor87f54062009-09-15 22:30:29 +00001250 QualType BadAllocType;
1251 bool HasBadAllocExceptionSpec
1252 = (Name.getCXXOverloadedOperator() == OO_New ||
1253 Name.getCXXOverloadedOperator() == OO_Array_New);
1254 if (HasBadAllocExceptionSpec) {
1255 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1256 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1257 }
1258
1259 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1260 true, false,
1261 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001262 &BadAllocType,
1263 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001264 FunctionDecl *Alloc =
1265 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001266 FnType, /*TInfo=*/0, FunctionDecl::None,
1267 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001268 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001269
1270 if (AddMallocAttr)
1271 Alloc->addAttr(::new (Context) MallocAttr());
1272
Sebastian Redlfaf68082008-12-03 20:26:15 +00001273 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001274 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001275 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001276 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001277 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001278
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001279 // FIXME: Also add this declaration to the IdentifierResolver, but
1280 // make sure it is at the end of the chain to coincide with the
1281 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001282 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001283}
1284
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001285bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1286 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001287 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001288 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001289 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001290 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001291
John McCall27b18f82009-11-17 02:14:36 +00001292 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001293 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001294
1295 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1296 F != FEnd; ++F) {
1297 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1298 if (Delete->isUsualDeallocationFunction()) {
1299 Operator = Delete;
1300 return false;
1301 }
1302 }
1303
1304 // We did find operator delete/operator delete[] declarations, but
1305 // none of them were suitable.
1306 if (!Found.empty()) {
1307 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1308 << Name << RD;
1309
1310 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1311 F != FEnd; ++F) {
Douglas Gregor861eb802010-04-25 20:55:08 +00001312 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001313 << Name;
1314 }
1315
1316 return true;
1317 }
1318
1319 // Look for a global declaration.
1320 DeclareGlobalNewDelete();
1321 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1322
1323 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1324 Expr* DeallocArgs[1];
1325 DeallocArgs[0] = &Null;
1326 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1327 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1328 Operator))
1329 return true;
1330
1331 assert(Operator && "Did not find a deallocation function!");
1332 return false;
1333}
1334
Sebastian Redlbd150f42008-11-21 19:14:01 +00001335/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1336/// @code ::delete ptr; @endcode
1337/// or
1338/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001339Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001340Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001341 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001342 // C++ [expr.delete]p1:
1343 // The operand shall have a pointer type, or a class type having a single
1344 // conversion function to a pointer type. The result has type void.
1345 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001346 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1347
Anders Carlssona471db02009-08-16 20:29:29 +00001348 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001350 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001351 if (!Ex->isTypeDependent()) {
1352 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001353
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001354 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001355 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1356
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001357 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001358 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001359 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001360 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001361 NamedDecl *D = I.getDecl();
1362 if (isa<UsingShadowDecl>(D))
1363 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1364
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001365 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001366 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001367 continue;
1368
John McCallda4458e2010-03-31 01:36:47 +00001369 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001370
1371 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1372 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1373 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001374 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001375 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001376 if (ObjectPtrConversions.size() == 1) {
1377 // We have a single conversion to a pointer-to-object type. Perform
1378 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001379 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001380 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001381 if (!PerformImplicitConversion(Ex,
1382 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001383 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001384 Operand = Owned(Ex);
1385 Type = Ex->getType();
1386 }
1387 }
1388 else if (ObjectPtrConversions.size() > 1) {
1389 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1390 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001391 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1392 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001393 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001394 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001395 }
1396
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001397 if (!Type->isPointerType())
1398 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1399 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001400
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001401 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001402 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001403 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1404 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001405 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001406 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001407 PDiag(diag::warn_delete_incomplete)
1408 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001409 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001410
Douglas Gregor98496dc2009-09-29 21:38:53 +00001411 // C++ [expr.delete]p2:
1412 // [Note: a pointer to a const type can be the operand of a
1413 // delete-expression; it is not necessary to cast away the constness
1414 // (5.2.11) of the pointer expression before it is used as the operand
1415 // of the delete-expression. ]
1416 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1417 CastExpr::CK_NoOp);
1418
1419 // Update the operand.
1420 Operand.take();
1421 Operand = ExprArg(*this, Ex);
1422
Anders Carlssona471db02009-08-16 20:29:29 +00001423 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1424 ArrayForm ? OO_Array_Delete : OO_Delete);
1425
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001426 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1427 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1428
1429 if (!UseGlobal &&
1430 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001431 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001432
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001433 if (!RD->hasTrivialDestructor())
1434 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001435 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001436 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001437 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001438
Anders Carlssona471db02009-08-16 20:29:29 +00001439 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001440 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001441 DeclareGlobalNewDelete();
1442 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001443 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001444 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001445 OperatorDelete))
1446 return ExprError();
1447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
John McCall0f55a032010-04-20 02:18:25 +00001449 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1450
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001451 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001452 }
1453
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001454 Operand.release();
1455 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001456 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001457}
1458
Douglas Gregor633caca2009-11-23 23:44:04 +00001459/// \brief Check the use of the given variable as a C++ condition in an if,
1460/// while, do-while, or switch statement.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001461Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1462 SourceLocation StmtLoc,
1463 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001464 QualType T = ConditionVar->getType();
1465
1466 // C++ [stmt.select]p2:
1467 // The declarator shall not specify a function or an array.
1468 if (T->isFunctionType())
1469 return ExprError(Diag(ConditionVar->getLocation(),
1470 diag::err_invalid_use_of_function_type)
1471 << ConditionVar->getSourceRange());
1472 else if (T->isArrayType())
1473 return ExprError(Diag(ConditionVar->getLocation(),
1474 diag::err_invalid_use_of_array_type)
1475 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001476
Douglas Gregore60e41a2010-05-06 17:25:47 +00001477 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1478 ConditionVar->getLocation(),
1479 ConditionVar->getType().getNonReferenceType());
1480 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1481 Condition->Destroy(Context);
1482 return ExprError();
1483 }
1484
1485 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001486}
1487
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001488/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1489bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1490 // C++ 6.4p4:
1491 // The value of a condition that is an initialized declaration in a statement
1492 // other than a switch statement is the value of the declared variable
1493 // implicitly converted to type bool. If that conversion is ill-formed, the
1494 // program is ill-formed.
1495 // The value of a condition that is an expression is the value of the
1496 // expression, implicitly converted to bool.
1497 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001498 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001499}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001500
1501/// Helper function to determine whether this is the (deprecated) C++
1502/// conversion from a string literal to a pointer to non-const char or
1503/// non-const wchar_t (for narrow and wide string literals,
1504/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001505bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001506Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1507 // Look inside the implicit cast, if it exists.
1508 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1509 From = Cast->getSubExpr();
1510
1511 // A string literal (2.13.4) that is not a wide string literal can
1512 // be converted to an rvalue of type "pointer to char"; a wide
1513 // string literal can be converted to an rvalue of type "pointer
1514 // to wchar_t" (C++ 4.2p2).
1515 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001516 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001517 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001518 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001519 // This conversion is considered only when there is an
1520 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001521 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001522 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1523 (!StrLit->isWide() &&
1524 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1525 ToPointeeType->getKind() == BuiltinType::Char_S))))
1526 return true;
1527 }
1528
1529 return false;
1530}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001531
Douglas Gregora4253922010-04-16 22:17:36 +00001532static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1533 SourceLocation CastLoc,
1534 QualType Ty,
1535 CastExpr::CastKind Kind,
1536 CXXMethodDecl *Method,
1537 Sema::ExprArg Arg) {
1538 Expr *From = Arg.takeAs<Expr>();
1539
1540 switch (Kind) {
1541 default: assert(0 && "Unhandled cast kind!");
1542 case CastExpr::CK_ConstructorConversion: {
1543 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1544
1545 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1546 Sema::MultiExprArg(S, (void **)&From, 1),
1547 CastLoc, ConstructorArgs))
1548 return S.ExprError();
1549
1550 Sema::OwningExprResult Result =
1551 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1552 move_arg(ConstructorArgs));
1553 if (Result.isInvalid())
1554 return S.ExprError();
1555
1556 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1557 }
1558
1559 case CastExpr::CK_UserDefinedConversion: {
1560 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1561
1562 // Create an implicit call expr that calls it.
1563 // FIXME: pass the FoundDecl for the user-defined conversion here
1564 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1565 return S.MaybeBindToTemporary(CE);
1566 }
1567 }
1568}
1569
Douglas Gregor5fb53972009-01-14 15:45:31 +00001570/// PerformImplicitConversion - Perform an implicit conversion of the
1571/// expression From to the type ToType using the pre-computed implicit
1572/// conversion sequence ICS. Returns true if there was an error, false
1573/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001574/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001575/// used in the error message.
1576bool
1577Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1578 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001579 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001580 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001581 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001582 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001583 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001584 return true;
1585 break;
1586
Anders Carlsson110b07b2009-09-15 06:28:28 +00001587 case ImplicitConversionSequence::UserDefinedConversion: {
1588
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001589 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1590 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001591 QualType BeforeToType;
1592 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001593 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001594
1595 // If the user-defined conversion is specified by a conversion function,
1596 // the initial standard conversion sequence converts the source type to
1597 // the implicit object parameter of the conversion function.
1598 BeforeToType = Context.getTagDeclType(Conv->getParent());
1599 } else if (const CXXConstructorDecl *Ctor =
1600 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001601 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001602 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001603 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001604 // If the user-defined conversion is specified by a constructor, the
1605 // initial standard conversion sequence converts the source type to the
1606 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001607 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1608 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001609 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001610 else
1611 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001612 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001613 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001614 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001615 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001616 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001617 return true;
1618 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001619
Anders Carlssone9766d52009-09-09 21:33:21 +00001620 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001621 = BuildCXXCastArgument(*this,
1622 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001623 ToType.getNonReferenceType(),
1624 CastKind, cast<CXXMethodDecl>(FD),
1625 Owned(From));
1626
1627 if (CastArg.isInvalid())
1628 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001629
1630 From = CastArg.takeAs<Expr>();
1631
Eli Friedmane96f1d32009-11-27 04:41:50 +00001632 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001633 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001634 }
John McCall0d1da222010-01-12 00:44:57 +00001635
1636 case ImplicitConversionSequence::AmbiguousConversion:
1637 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1638 PDiag(diag::err_typecheck_ambiguous_condition)
1639 << From->getSourceRange());
1640 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001641
Douglas Gregor39c16d42008-10-24 04:54:22 +00001642 case ImplicitConversionSequence::EllipsisConversion:
1643 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001644 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001645
1646 case ImplicitConversionSequence::BadConversion:
1647 return true;
1648 }
1649
1650 // Everything went well.
1651 return false;
1652}
1653
1654/// PerformImplicitConversion - Perform an implicit conversion of the
1655/// expression From to the type ToType by following the standard
1656/// conversion sequence SCS. Returns true if there was an error, false
1657/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001658/// expression. Flavor is the context in which we're performing this
1659/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001660bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001661Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001662 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001663 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001664 // Overall FIXME: we are recomputing too many types here and doing far too
1665 // much extra work. What this means is that we need to keep track of more
1666 // information that is computed when we try the implicit conversion initially,
1667 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001668 QualType FromType = From->getType();
1669
Douglas Gregor2fe98832008-11-03 19:09:14 +00001670 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001671 // FIXME: When can ToType be a reference type?
1672 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001673 if (SCS.Second == ICK_Derived_To_Base) {
1674 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1675 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1676 MultiExprArg(*this, (void **)&From, 1),
1677 /*FIXME:ConstructLoc*/SourceLocation(),
1678 ConstructorArgs))
1679 return true;
1680 OwningExprResult FromResult =
1681 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1682 ToType, SCS.CopyConstructor,
1683 move_arg(ConstructorArgs));
1684 if (FromResult.isInvalid())
1685 return true;
1686 From = FromResult.takeAs<Expr>();
1687 return false;
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689 OwningExprResult FromResult =
1690 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1691 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001692 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001693
Anders Carlsson6eb55572009-08-25 05:12:04 +00001694 if (FromResult.isInvalid())
1695 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001696
Anders Carlsson6eb55572009-08-25 05:12:04 +00001697 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001698 return false;
1699 }
1700
Douglas Gregor980fb162010-04-29 18:24:40 +00001701 // Resolve overloaded function references.
1702 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1703 DeclAccessPair Found;
1704 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1705 true, Found);
1706 if (!Fn)
1707 return true;
1708
1709 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1710 return true;
1711
1712 From = FixOverloadedFunctionReference(From, Found, Fn);
1713 FromType = From->getType();
1714 }
1715
Douglas Gregor39c16d42008-10-24 04:54:22 +00001716 // Perform the first implicit conversion.
1717 switch (SCS.First) {
1718 case ICK_Identity:
1719 case ICK_Lvalue_To_Rvalue:
1720 // Nothing to do.
1721 break;
1722
1723 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001724 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001725 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001726 break;
1727
1728 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001729 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001730 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001731 break;
1732
1733 default:
1734 assert(false && "Improper first standard conversion");
1735 break;
1736 }
1737
1738 // Perform the second implicit conversion
1739 switch (SCS.Second) {
1740 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001741 // If both sides are functions (or pointers/references to them), there could
1742 // be incompatible exception declarations.
1743 if (CheckExceptionSpecCompatibility(From, ToType))
1744 return true;
1745 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001746 break;
1747
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001748 case ICK_NoReturn_Adjustment:
1749 // If both sides are functions (or pointers/references to them), there could
1750 // be incompatible exception declarations.
1751 if (CheckExceptionSpecCompatibility(From, ToType))
1752 return true;
1753
1754 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1755 CastExpr::CK_NoOp);
1756 break;
1757
Douglas Gregor39c16d42008-10-24 04:54:22 +00001758 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001759 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001760 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1761 break;
1762
1763 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001764 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001765 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1766 break;
1767
1768 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001769 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001770 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1771 break;
1772
Douglas Gregor39c16d42008-10-24 04:54:22 +00001773 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001774 if (ToType->isFloatingType())
1775 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1776 else
1777 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1778 break;
1779
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001780 case ICK_Complex_Real:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001781 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1782 break;
1783
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001784 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001785 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001786 break;
1787
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001788 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001789 if (SCS.IncompatibleObjC) {
1790 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001791 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001792 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001793 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001794 << From->getSourceRange();
1795 }
1796
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001797
1798 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssona70cff62010-04-24 19:06:50 +00001799 CXXBaseSpecifierArray BasePath;
1800 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001801 return true;
Anders Carlssona70cff62010-04-24 19:06:50 +00001802 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001803 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001804 }
1805
1806 case ICK_Pointer_Member: {
1807 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001808 CXXBaseSpecifierArray BasePath;
1809 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1810 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001811 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001812 if (CheckExceptionSpecCompatibility(From, ToType))
1813 return true;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001814 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001815 break;
1816 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001817 case ICK_Boolean_Conversion: {
1818 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1819 if (FromType->isMemberPointerType())
1820 Kind = CastExpr::CK_MemberPointerToBoolean;
1821
1822 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001823 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001824 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001825
Douglas Gregor88d292c2010-05-13 16:44:06 +00001826 case ICK_Derived_To_Base: {
1827 CXXBaseSpecifierArray BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001828 if (CheckDerivedToBaseConversion(From->getType(),
1829 ToType.getNonReferenceType(),
1830 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001831 From->getSourceRange(),
1832 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001833 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001834 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001835
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001836 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001837 CastExpr::CK_DerivedToBase,
1838 /*isLvalue=*/(From->getType()->isRecordType() &&
1839 From->isLvalue(Context) == Expr::LV_Valid),
1840 BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001841 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001842 }
1843
Douglas Gregor39c16d42008-10-24 04:54:22 +00001844 default:
1845 assert(false && "Improper second standard conversion");
1846 break;
1847 }
1848
1849 switch (SCS.Third) {
1850 case ICK_Identity:
1851 // Nothing to do.
1852 break;
1853
1854 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001855 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1856 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001857 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00001858 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001859
1860 if (SCS.DeprecatedStringLiteralToCharPtr)
1861 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1862 << ToType.getNonReferenceType();
1863
Douglas Gregor39c16d42008-10-24 04:54:22 +00001864 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001865
Douglas Gregor39c16d42008-10-24 04:54:22 +00001866 default:
1867 assert(false && "Improper second standard conversion");
1868 break;
1869 }
1870
1871 return false;
1872}
1873
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001874Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1875 SourceLocation KWLoc,
1876 SourceLocation LParen,
1877 TypeTy *Ty,
1878 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001879 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001880
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001881 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1882 // all traits except __is_class, __is_enum and __is_union require a the type
1883 // to be complete.
1884 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001885 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001886 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001887 return ExprError();
1888 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001889
1890 // There is no point in eagerly computing the value. The traits are designed
1891 // to be used from type trait templates, so Ty will be a template parameter
1892 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001893 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1894 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001895}
Sebastian Redl5822f082009-02-07 20:10:22 +00001896
1897QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001898 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001899 const char *OpSpelling = isIndirect ? "->*" : ".*";
1900 // C++ 5.5p2
1901 // The binary operator .* [p3: ->*] binds its second operand, which shall
1902 // be of type "pointer to member of T" (where T is a completely-defined
1903 // class type) [...]
1904 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001905 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001906 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001907 Diag(Loc, diag::err_bad_memptr_rhs)
1908 << OpSpelling << RType << rex->getSourceRange();
1909 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001910 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001911
Sebastian Redl5822f082009-02-07 20:10:22 +00001912 QualType Class(MemPtr->getClass(), 0);
1913
Sebastian Redlc72350e2010-04-10 10:14:54 +00001914 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1915 return QualType();
1916
Sebastian Redl5822f082009-02-07 20:10:22 +00001917 // C++ 5.5p2
1918 // [...] to its first operand, which shall be of class T or of a class of
1919 // which T is an unambiguous and accessible base class. [p3: a pointer to
1920 // such a class]
1921 QualType LType = lex->getType();
1922 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001923 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001924 LType = Ptr->getPointeeType().getNonReferenceType();
1925 else {
1926 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001927 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001928 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001929 return QualType();
1930 }
1931 }
1932
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001933 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001934 // If we want to check the hierarchy, we need a complete type.
1935 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1936 << OpSpelling << (int)isIndirect)) {
1937 return QualType();
1938 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001939 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001940 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001941 // FIXME: Would it be useful to print full ambiguity paths, or is that
1942 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001943 if (!IsDerivedFrom(LType, Class, Paths) ||
1944 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1945 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001946 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001947 return QualType();
1948 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001949 // Cast LHS to type of use.
1950 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1951 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlssona70cff62010-04-24 19:06:50 +00001952
1953 CXXBaseSpecifierArray BasePath;
1954 BuildBasePathArray(Paths, BasePath);
1955 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1956 BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00001957 }
1958
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001959 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001960 // Diagnose use of pointer-to-member type which when used as
1961 // the functional cast in a pointer-to-member expression.
1962 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1963 return QualType();
1964 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001965 // C++ 5.5p2
1966 // The result is an object or a function of the type specified by the
1967 // second operand.
1968 // The cv qualifiers are the union of those in the pointer and the left side,
1969 // in accordance with 5.5p5 and 5.2.5.
1970 // FIXME: This returns a dereferenced member function pointer as a normal
1971 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001972 // calling them. There's also a GCC extension to get a function pointer to the
1973 // thing, which is another complication, because this type - unlike the type
1974 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001975 // argument.
1976 // We probably need a "MemberFunctionClosureType" or something like that.
1977 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001978 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001979 return Result;
1980}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001981
Sebastian Redl1a99f442009-04-16 17:51:27 +00001982/// \brief Try to convert a type to another according to C++0x 5.16p3.
1983///
1984/// This is part of the parameter validation for the ? operator. If either
1985/// value operand is a class type, the two operands are attempted to be
1986/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00001987/// It returns true if the program is ill-formed and has already been diagnosed
1988/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00001989static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1990 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00001991 bool &HaveConversion,
1992 QualType &ToType) {
1993 HaveConversion = false;
1994 ToType = To->getType();
1995
1996 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1997 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00001998 // C++0x 5.16p3
1999 // The process for determining whether an operand expression E1 of type T1
2000 // can be converted to match an operand expression E2 of type T2 is defined
2001 // as follows:
2002 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002003 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2004 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002005 // E1 can be converted to match E2 if E1 can be implicitly converted to
2006 // type "lvalue reference to T2", subject to the constraint that in the
2007 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002008 QualType T = Self.Context.getLValueReferenceType(ToType);
2009 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2010
2011 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2012 if (InitSeq.isDirectReferenceBinding()) {
2013 ToType = T;
2014 HaveConversion = true;
2015 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002016 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002017
2018 if (InitSeq.isAmbiguous())
2019 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002020 }
John McCall65eb8792010-02-25 01:37:24 +00002021
Sebastian Redl1a99f442009-04-16 17:51:27 +00002022 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2023 // -- if E1 and E2 have class type, and the underlying class types are
2024 // the same or one is a base class of the other:
2025 QualType FTy = From->getType();
2026 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002027 const RecordType *FRec = FTy->getAs<RecordType>();
2028 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002029 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2030 Self.IsDerivedFrom(FTy, TTy);
2031 if (FRec && TRec &&
2032 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002033 // E1 can be converted to match E2 if the class of T2 is the
2034 // same type as, or a base class of, the class of T1, and
2035 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002036 if (FRec == TRec || FDerivedFromT) {
2037 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002038 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2039 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2040 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2041 HaveConversion = true;
2042 return false;
2043 }
2044
2045 if (InitSeq.isAmbiguous())
2046 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2047 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002048 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002049
2050 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002051 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002052
2053 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2054 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002055 // if E2 were converted to an rvalue (or the type it has, if E2 is
2056 // an rvalue).
2057 //
2058 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2059 // to the array-to-pointer or function-to-pointer conversions.
2060 if (!TTy->getAs<TagType>())
2061 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002062
2063 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2064 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2065 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2066 ToType = TTy;
2067 if (InitSeq.isAmbiguous())
2068 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2069
Sebastian Redl1a99f442009-04-16 17:51:27 +00002070 return false;
2071}
2072
2073/// \brief Try to find a common type for two according to C++0x 5.16p5.
2074///
2075/// This is part of the parameter validation for the ? operator. If either
2076/// value operand is a class type, overload resolution is used to find a
2077/// conversion to a common type.
2078static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2079 SourceLocation Loc) {
2080 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002081 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002082 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002083
2084 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002085 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002086 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002087 // We found a match. Perform the conversions on the arguments and move on.
2088 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002089 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002090 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002091 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002092 break;
2093 return false;
2094
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002095 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002096 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2097 << LHS->getType() << RHS->getType()
2098 << LHS->getSourceRange() << RHS->getSourceRange();
2099 return true;
2100
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002101 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002102 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2103 << LHS->getType() << RHS->getType()
2104 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002105 // FIXME: Print the possible common types by printing the return types of
2106 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002107 break;
2108
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002109 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002110 assert(false && "Conditional operator has only built-in overloads");
2111 break;
2112 }
2113 return true;
2114}
2115
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002116/// \brief Perform an "extended" implicit conversion as returned by
2117/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002118static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2119 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2120 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2121 SourceLocation());
2122 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2123 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2124 Sema::MultiExprArg(Self, (void **)&E, 1));
2125 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002126 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002127
2128 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002129 return false;
2130}
2131
Sebastian Redl1a99f442009-04-16 17:51:27 +00002132/// \brief Check the operands of ?: under C++ semantics.
2133///
2134/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2135/// extension. In this case, LHS == Cond. (But they're not aliases.)
2136QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2137 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002138 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2139 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002140
2141 // C++0x 5.16p1
2142 // The first expression is contextually converted to bool.
2143 if (!Cond->isTypeDependent()) {
2144 if (CheckCXXBooleanCondition(Cond))
2145 return QualType();
2146 }
2147
2148 // Either of the arguments dependent?
2149 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2150 return Context.DependentTy;
2151
2152 // C++0x 5.16p2
2153 // If either the second or the third operand has type (cv) void, ...
2154 QualType LTy = LHS->getType();
2155 QualType RTy = RHS->getType();
2156 bool LVoid = LTy->isVoidType();
2157 bool RVoid = RTy->isVoidType();
2158 if (LVoid || RVoid) {
2159 // ... then the [l2r] conversions are performed on the second and third
2160 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002161 DefaultFunctionArrayLvalueConversion(LHS);
2162 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002163 LTy = LHS->getType();
2164 RTy = RHS->getType();
2165
2166 // ... and one of the following shall hold:
2167 // -- The second or the third operand (but not both) is a throw-
2168 // expression; the result is of the type of the other and is an rvalue.
2169 bool LThrow = isa<CXXThrowExpr>(LHS);
2170 bool RThrow = isa<CXXThrowExpr>(RHS);
2171 if (LThrow && !RThrow)
2172 return RTy;
2173 if (RThrow && !LThrow)
2174 return LTy;
2175
2176 // -- Both the second and third operands have type void; the result is of
2177 // type void and is an rvalue.
2178 if (LVoid && RVoid)
2179 return Context.VoidTy;
2180
2181 // Neither holds, error.
2182 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2183 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2184 << LHS->getSourceRange() << RHS->getSourceRange();
2185 return QualType();
2186 }
2187
2188 // Neither is void.
2189
2190 // C++0x 5.16p3
2191 // Otherwise, if the second and third operand have different types, and
2192 // either has (cv) class type, and attempt is made to convert each of those
2193 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002194 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002195 (LTy->isRecordType() || RTy->isRecordType())) {
2196 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2197 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002198 QualType L2RType, R2LType;
2199 bool HaveL2R, HaveR2L;
2200 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002201 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002202 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002203 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002204
Sebastian Redl1a99f442009-04-16 17:51:27 +00002205 // If both can be converted, [...] the program is ill-formed.
2206 if (HaveL2R && HaveR2L) {
2207 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2208 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2209 return QualType();
2210 }
2211
2212 // If exactly one conversion is possible, that conversion is applied to
2213 // the chosen operand and the converted operands are used in place of the
2214 // original operands for the remainder of this section.
2215 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002216 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002217 return QualType();
2218 LTy = LHS->getType();
2219 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002220 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002221 return QualType();
2222 RTy = RHS->getType();
2223 }
2224 }
2225
2226 // C++0x 5.16p4
2227 // If the second and third operands are lvalues and have the same type,
2228 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002229 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002230 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2231 RHS->isLvalue(Context) == Expr::LV_Valid)
2232 return LTy;
2233
2234 // C++0x 5.16p5
2235 // Otherwise, the result is an rvalue. If the second and third operands
2236 // do not have the same type, and either has (cv) class type, ...
2237 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2238 // ... overload resolution is used to determine the conversions (if any)
2239 // to be applied to the operands. If the overload resolution fails, the
2240 // program is ill-formed.
2241 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2242 return QualType();
2243 }
2244
2245 // C++0x 5.16p6
2246 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2247 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002248 DefaultFunctionArrayLvalueConversion(LHS);
2249 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002250 LTy = LHS->getType();
2251 RTy = RHS->getType();
2252
2253 // After those conversions, one of the following shall hold:
2254 // -- The second and third operands have the same type; the result
2255 // is of that type.
2256 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2257 return LTy;
2258
2259 // -- The second and third operands have arithmetic or enumeration type;
2260 // the usual arithmetic conversions are performed to bring them to a
2261 // common type, and the result is of that type.
2262 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2263 UsualArithmeticConversions(LHS, RHS);
2264 return LHS->getType();
2265 }
2266
2267 // -- The second and third operands have pointer type, or one has pointer
2268 // type and the other is a null pointer constant; pointer conversions
2269 // and qualification conversions are performed to bring them to their
2270 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002271 // -- The second and third operands have pointer to member type, or one has
2272 // pointer to member type and the other is a null pointer constant;
2273 // pointer to member conversions and qualification conversions are
2274 // performed to bring them to a common type, whose cv-qualification
2275 // shall match the cv-qualification of either the second or the third
2276 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002277 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002278 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002279 isSFINAEContext()? 0 : &NonStandardCompositeType);
2280 if (!Composite.isNull()) {
2281 if (NonStandardCompositeType)
2282 Diag(QuestionLoc,
2283 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2284 << LTy << RTy << Composite
2285 << LHS->getSourceRange() << RHS->getSourceRange();
2286
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002287 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002288 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002289
Douglas Gregor697a3912010-04-01 22:47:07 +00002290 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002291 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2292 if (!Composite.isNull())
2293 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002294
Sebastian Redl1a99f442009-04-16 17:51:27 +00002295 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2296 << LHS->getType() << RHS->getType()
2297 << LHS->getSourceRange() << RHS->getSourceRange();
2298 return QualType();
2299}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002300
2301/// \brief Find a merged pointer type and convert the two expressions to it.
2302///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002303/// This finds the composite pointer type (or member pointer type) for @p E1
2304/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2305/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002306/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002307///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002308/// \param Loc The location of the operator requiring these two expressions to
2309/// be converted to the composite pointer type.
2310///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002311/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2312/// a non-standard (but still sane) composite type to which both expressions
2313/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2314/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002315QualType Sema::FindCompositePointerType(SourceLocation Loc,
2316 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002317 bool *NonStandardCompositeType) {
2318 if (NonStandardCompositeType)
2319 *NonStandardCompositeType = false;
2320
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002321 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2322 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002323
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002324 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2325 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002326 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002327
2328 // C++0x 5.9p2
2329 // Pointer conversions and qualification conversions are performed on
2330 // pointer operands to bring them to their composite pointer type. If
2331 // one operand is a null pointer constant, the composite pointer type is
2332 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002333 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002334 if (T2->isMemberPointerType())
2335 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2336 else
2337 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002338 return T2;
2339 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002340 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002341 if (T1->isMemberPointerType())
2342 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2343 else
2344 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002345 return T1;
2346 }
Mike Stump11289f42009-09-09 15:08:12 +00002347
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002348 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002349 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2350 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002351 return QualType();
2352
2353 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2354 // the other has type "pointer to cv2 T" and the composite pointer type is
2355 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2356 // Otherwise, the composite pointer type is a pointer type similar to the
2357 // type of one of the operands, with a cv-qualification signature that is
2358 // the union of the cv-qualification signatures of the operand types.
2359 // In practice, the first part here is redundant; it's subsumed by the second.
2360 // What we do here is, we build the two possible composite types, and try the
2361 // conversions in both directions. If only one works, or if the two composite
2362 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002363 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002364 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2365 QualifierVector QualifierUnion;
2366 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2367 ContainingClassVector;
2368 ContainingClassVector MemberOfClass;
2369 QualType Composite1 = Context.getCanonicalType(T1),
2370 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002371 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002372 do {
2373 const PointerType *Ptr1, *Ptr2;
2374 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2375 (Ptr2 = Composite2->getAs<PointerType>())) {
2376 Composite1 = Ptr1->getPointeeType();
2377 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002378
2379 // If we're allowed to create a non-standard composite type, keep track
2380 // of where we need to fill in additional 'const' qualifiers.
2381 if (NonStandardCompositeType &&
2382 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2383 NeedConstBefore = QualifierUnion.size();
2384
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002385 QualifierUnion.push_back(
2386 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2387 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2388 continue;
2389 }
Mike Stump11289f42009-09-09 15:08:12 +00002390
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002391 const MemberPointerType *MemPtr1, *MemPtr2;
2392 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2393 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2394 Composite1 = MemPtr1->getPointeeType();
2395 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002396
2397 // If we're allowed to create a non-standard composite type, keep track
2398 // of where we need to fill in additional 'const' qualifiers.
2399 if (NonStandardCompositeType &&
2400 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2401 NeedConstBefore = QualifierUnion.size();
2402
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002403 QualifierUnion.push_back(
2404 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2405 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2406 MemPtr2->getClass()));
2407 continue;
2408 }
Mike Stump11289f42009-09-09 15:08:12 +00002409
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002410 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002411
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002412 // Cannot unwrap any more types.
2413 break;
2414 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002415
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002416 if (NeedConstBefore && NonStandardCompositeType) {
2417 // Extension: Add 'const' to qualifiers that come before the first qualifier
2418 // mismatch, so that our (non-standard!) composite type meets the
2419 // requirements of C++ [conv.qual]p4 bullet 3.
2420 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2421 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2422 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2423 *NonStandardCompositeType = true;
2424 }
2425 }
2426 }
2427
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002428 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002429 ContainingClassVector::reverse_iterator MOC
2430 = MemberOfClass.rbegin();
2431 for (QualifierVector::reverse_iterator
2432 I = QualifierUnion.rbegin(),
2433 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002434 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002435 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002436 if (MOC->first && MOC->second) {
2437 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002438 Composite1 = Context.getMemberPointerType(
2439 Context.getQualifiedType(Composite1, Quals),
2440 MOC->first);
2441 Composite2 = Context.getMemberPointerType(
2442 Context.getQualifiedType(Composite2, Quals),
2443 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002444 } else {
2445 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002446 Composite1
2447 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2448 Composite2
2449 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002450 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002451 }
2452
Douglas Gregor19175ff2010-04-16 23:20:25 +00002453 // Try to convert to the first composite pointer type.
2454 InitializedEntity Entity1
2455 = InitializedEntity::InitializeTemporary(Composite1);
2456 InitializationKind Kind
2457 = InitializationKind::CreateCopy(Loc, SourceLocation());
2458 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2459 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002460
Douglas Gregor19175ff2010-04-16 23:20:25 +00002461 if (E1ToC1 && E2ToC1) {
2462 // Conversion to Composite1 is viable.
2463 if (!Context.hasSameType(Composite1, Composite2)) {
2464 // Composite2 is a different type from Composite1. Check whether
2465 // Composite2 is also viable.
2466 InitializedEntity Entity2
2467 = InitializedEntity::InitializeTemporary(Composite2);
2468 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2469 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2470 if (E1ToC2 && E2ToC2) {
2471 // Both Composite1 and Composite2 are viable and are different;
2472 // this is an ambiguity.
2473 return QualType();
2474 }
2475 }
2476
2477 // Convert E1 to Composite1
2478 OwningExprResult E1Result
2479 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2480 if (E1Result.isInvalid())
2481 return QualType();
2482 E1 = E1Result.takeAs<Expr>();
2483
2484 // Convert E2 to Composite1
2485 OwningExprResult E2Result
2486 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2487 if (E2Result.isInvalid())
2488 return QualType();
2489 E2 = E2Result.takeAs<Expr>();
2490
2491 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002492 }
2493
Douglas Gregor19175ff2010-04-16 23:20:25 +00002494 // Check whether Composite2 is viable.
2495 InitializedEntity Entity2
2496 = InitializedEntity::InitializeTemporary(Composite2);
2497 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2498 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2499 if (!E1ToC2 || !E2ToC2)
2500 return QualType();
2501
2502 // Convert E1 to Composite2
2503 OwningExprResult E1Result
2504 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2505 if (E1Result.isInvalid())
2506 return QualType();
2507 E1 = E1Result.takeAs<Expr>();
2508
2509 // Convert E2 to Composite2
2510 OwningExprResult E2Result
2511 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2512 if (E2Result.isInvalid())
2513 return QualType();
2514 E2 = E2Result.takeAs<Expr>();
2515
2516 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002517}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002518
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002519Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002520 if (!Context.getLangOptions().CPlusPlus)
2521 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002522
Douglas Gregor363b1512009-12-24 18:51:59 +00002523 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2524
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002525 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002526 if (!RT)
2527 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002528
John McCall67da35c2010-02-04 22:26:26 +00002529 // If this is the result of a call expression, our source might
2530 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002531 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2532 QualType Ty = CE->getCallee()->getType();
2533 if (const PointerType *PT = Ty->getAs<PointerType>())
2534 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002535 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2536 Ty = BPT->getPointeeType();
2537
John McCall9dd450b2009-09-21 23:43:11 +00002538 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002539 if (FTy->getResultType()->isReferenceType())
2540 return Owned(E);
2541 }
John McCall67da35c2010-02-04 22:26:26 +00002542
2543 // That should be enough to guarantee that this type is complete.
2544 // If it has a trivial destructor, we can avoid the extra copy.
2545 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2546 if (RD->hasTrivialDestructor())
2547 return Owned(E);
2548
Mike Stump11289f42009-09-09 15:08:12 +00002549 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002550 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002551 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002552 if (CXXDestructorDecl *Destructor =
John McCall8e36d532010-04-07 00:41:46 +00002553 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002554 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002555 CheckDestructorAccess(E->getExprLoc(), Destructor,
2556 PDiag(diag::err_access_dtor_temp)
2557 << E->getType());
2558 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002559 // FIXME: Add the temporary to the temporaries vector.
2560 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2561}
2562
Anders Carlsson6e997b22009-12-15 20:51:39 +00002563Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002564 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002565
John McCallcc7e5bf2010-05-06 08:58:33 +00002566 // Check any implicit conversions within the expression.
2567 CheckImplicitConversions(SubExpr);
2568
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002569 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2570 assert(ExprTemporaries.size() >= FirstTemporary);
2571 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002572 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002573
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002574 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002575 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002576 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002577 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2578 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002579
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002580 return E;
2581}
2582
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002583Sema::OwningExprResult
2584Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2585 if (SubExpr.isInvalid())
2586 return ExprError();
2587
2588 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2589}
2590
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002591FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2592 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2593 assert(ExprTemporaries.size() >= FirstTemporary);
2594
2595 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2596 CXXTemporary **Temporaries =
2597 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2598
2599 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2600
2601 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2602 ExprTemporaries.end());
2603
2604 return E;
2605}
2606
Mike Stump11289f42009-09-09 15:08:12 +00002607Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002608Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002609 tok::TokenKind OpKind, TypeTy *&ObjectType,
2610 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002611 // Since this might be a postfix expression, get rid of ParenListExprs.
2612 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002613
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002614 Expr *BaseExpr = (Expr*)Base.get();
2615 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002616
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002617 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002618 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002619 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002620 // If we have a pointer to a dependent type and are using the -> operator,
2621 // the object type is the type that the pointer points to. We might still
2622 // have enough information about that type to do something useful.
2623 if (OpKind == tok::arrow)
2624 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2625 BaseType = Ptr->getPointeeType();
2626
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002627 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002628 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002629 return move(Base);
2630 }
Mike Stump11289f42009-09-09 15:08:12 +00002631
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002632 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002633 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002634 // returned, with the original second operand.
2635 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002636 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002637 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002638 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002639 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002640
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002641 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002642 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002643 BaseExpr = (Expr*)Base.get();
2644 if (BaseExpr == NULL)
2645 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002646 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002647 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002648 BaseType = BaseExpr->getType();
2649 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002650 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002651 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002652 for (unsigned i = 0; i < Locations.size(); i++)
2653 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002654 return ExprError();
2655 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002656 }
Mike Stump11289f42009-09-09 15:08:12 +00002657
Douglas Gregore4f764f2009-11-20 19:58:21 +00002658 if (BaseType->isPointerType())
2659 BaseType = BaseType->getPointeeType();
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
2662 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002663 // vector types or Objective-C interfaces. Just return early and let
2664 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002665 if (!BaseType->isRecordType()) {
2666 // C++ [basic.lookup.classref]p2:
2667 // [...] If the type of the object expression is of pointer to scalar
2668 // type, the unqualified-id is looked up in the context of the complete
2669 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002670 //
2671 // This also indicates that we should be parsing a
2672 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002673 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002674 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002675 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002676 }
Mike Stump11289f42009-09-09 15:08:12 +00002677
Douglas Gregor3fad6172009-11-17 05:17:33 +00002678 // The object type must be complete (or dependent).
2679 if (!BaseType->isDependentType() &&
2680 RequireCompleteType(OpLoc, BaseType,
2681 PDiag(diag::err_incomplete_member_access)))
2682 return ExprError();
2683
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002684 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002685 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002686 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002687 // type C (or of pointer to a class type C), the unqualified-id is looked
2688 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002689 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002690 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002691}
2692
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002693Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2694 ExprArg MemExpr) {
2695 Expr *E = (Expr *) MemExpr.get();
2696 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2697 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2698 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002699 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002700
2701 return ActOnCallExpr(/*Scope*/ 0,
2702 move(MemExpr),
2703 /*LPLoc*/ ExpectedLParenLoc,
2704 Sema::MultiExprArg(*this, 0, 0),
2705 /*CommaLocs*/ 0,
2706 /*RPLoc*/ ExpectedLParenLoc);
2707}
Douglas Gregore610ada2010-02-24 18:44:31 +00002708
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002709Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2710 SourceLocation OpLoc,
2711 tok::TokenKind OpKind,
2712 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002713 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002714 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002715 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002716 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002717 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002718 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002719
2720 // C++ [expr.pseudo]p2:
2721 // The left-hand side of the dot operator shall be of scalar type. The
2722 // left-hand side of the arrow operator shall be of pointer to scalar type.
2723 // This scalar type is the object type.
2724 Expr *BaseE = (Expr *)Base.get();
2725 QualType ObjectType = BaseE->getType();
2726 if (OpKind == tok::arrow) {
2727 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2728 ObjectType = Ptr->getPointeeType();
2729 } else if (!BaseE->isTypeDependent()) {
2730 // The user wrote "p->" when she probably meant "p."; fix it.
2731 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2732 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002733 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002734 if (isSFINAEContext())
2735 return ExprError();
2736
2737 OpKind = tok::period;
2738 }
2739 }
2740
2741 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2742 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2743 << ObjectType << BaseE->getSourceRange();
2744 return ExprError();
2745 }
2746
2747 // C++ [expr.pseudo]p2:
2748 // [...] The cv-unqualified versions of the object type and of the type
2749 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002750 if (DestructedTypeInfo) {
2751 QualType DestructedType = DestructedTypeInfo->getType();
2752 SourceLocation DestructedTypeStart
2753 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2754 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2755 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2756 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2757 << ObjectType << DestructedType << BaseE->getSourceRange()
2758 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2759
2760 // Recover by setting the destructed type to the object type.
2761 DestructedType = ObjectType;
2762 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2763 DestructedTypeStart);
2764 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2765 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002766 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002767
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002768 // C++ [expr.pseudo]p2:
2769 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2770 // form
2771 //
2772 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2773 //
2774 // shall designate the same scalar type.
2775 if (ScopeTypeInfo) {
2776 QualType ScopeType = ScopeTypeInfo->getType();
2777 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2778 !Context.hasSameType(ScopeType, ObjectType)) {
2779
2780 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2781 diag::err_pseudo_dtor_type_mismatch)
2782 << ObjectType << ScopeType << BaseE->getSourceRange()
2783 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2784
2785 ScopeType = QualType();
2786 ScopeTypeInfo = 0;
2787 }
2788 }
2789
2790 OwningExprResult Result
2791 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2792 Base.takeAs<Expr>(),
2793 OpKind == tok::arrow,
2794 OpLoc,
2795 (NestedNameSpecifier *) SS.getScopeRep(),
2796 SS.getRange(),
2797 ScopeTypeInfo,
2798 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002799 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002800 Destructed));
2801
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002802 if (HasTrailingLParen)
2803 return move(Result);
2804
Douglas Gregor678f90d2010-02-25 01:56:36 +00002805 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002806}
2807
2808Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2809 SourceLocation OpLoc,
2810 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002811 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002812 UnqualifiedId &FirstTypeName,
2813 SourceLocation CCLoc,
2814 SourceLocation TildeLoc,
2815 UnqualifiedId &SecondTypeName,
2816 bool HasTrailingLParen) {
2817 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2818 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2819 "Invalid first type name in pseudo-destructor");
2820 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2821 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2822 "Invalid second type name in pseudo-destructor");
2823
2824 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002825
2826 // C++ [expr.pseudo]p2:
2827 // The left-hand side of the dot operator shall be of scalar type. The
2828 // left-hand side of the arrow operator shall be of pointer to scalar type.
2829 // This scalar type is the object type.
2830 QualType ObjectType = BaseE->getType();
2831 if (OpKind == tok::arrow) {
2832 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2833 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002834 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002835 // The user wrote "p->" when she probably meant "p."; fix it.
2836 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002837 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002838 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002839 if (isSFINAEContext())
2840 return ExprError();
2841
2842 OpKind = tok::period;
2843 }
2844 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002845
2846 // Compute the object type that we should use for name lookup purposes. Only
2847 // record types and dependent types matter.
2848 void *ObjectTypePtrForLookup = 0;
2849 if (!SS.isSet()) {
2850 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2851 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2852 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2853 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002854
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002855 // Convert the name of the type being destructed (following the ~) into a
2856 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002857 QualType DestructedType;
2858 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002859 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002860 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2861 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2862 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002863 S, &SS, true, ObjectTypePtrForLookup);
2864 if (!T &&
2865 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2866 (!SS.isSet() && ObjectType->isDependentType()))) {
2867 // The name of the type being destroyed is a dependent name, and we
2868 // couldn't find anything useful in scope. Just store the identifier and
2869 // it's location, and we'll perform (qualified) name lookup again at
2870 // template instantiation time.
2871 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2872 SecondTypeName.StartLocation);
2873 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002874 Diag(SecondTypeName.StartLocation,
2875 diag::err_pseudo_dtor_destructor_non_type)
2876 << SecondTypeName.Identifier << ObjectType;
2877 if (isSFINAEContext())
2878 return ExprError();
2879
2880 // Recover by assuming we had the right type all along.
2881 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002882 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002883 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002884 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002885 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002886 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002887 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2888 TemplateId->getTemplateArgs(),
2889 TemplateId->NumArgs);
2890 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2891 TemplateId->TemplateNameLoc,
2892 TemplateId->LAngleLoc,
2893 TemplateArgsPtr,
2894 TemplateId->RAngleLoc);
2895 if (T.isInvalid() || !T.get()) {
2896 // Recover by assuming we had the right type all along.
2897 DestructedType = ObjectType;
2898 } else
2899 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002900 }
2901
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002902 // If we've performed some kind of recovery, (re-)build the type source
2903 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002904 if (!DestructedType.isNull()) {
2905 if (!DestructedTypeInfo)
2906 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002907 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002908 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2909 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002910
2911 // Convert the name of the scope type (the type prior to '::') into a type.
2912 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002913 QualType ScopeType;
2914 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2915 FirstTypeName.Identifier) {
2916 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2917 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2918 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002919 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002920 if (!T) {
2921 Diag(FirstTypeName.StartLocation,
2922 diag::err_pseudo_dtor_destructor_non_type)
2923 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002924
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002925 if (isSFINAEContext())
2926 return ExprError();
2927
2928 // Just drop this type. It's unnecessary anyway.
2929 ScopeType = QualType();
2930 } else
2931 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002932 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002933 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002934 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002935 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2936 TemplateId->getTemplateArgs(),
2937 TemplateId->NumArgs);
2938 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2939 TemplateId->TemplateNameLoc,
2940 TemplateId->LAngleLoc,
2941 TemplateArgsPtr,
2942 TemplateId->RAngleLoc);
2943 if (T.isInvalid() || !T.get()) {
2944 // Recover by dropping this type.
2945 ScopeType = QualType();
2946 } else
2947 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002948 }
2949 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00002950
2951 if (!ScopeType.isNull() && !ScopeTypeInfo)
2952 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2953 FirstTypeName.StartLocation);
2954
2955
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002956 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002957 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002958 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00002959}
2960
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002961CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00002962 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002963 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00002964 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2965 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00002966 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2967
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002968 MemberExpr *ME =
2969 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2970 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002971 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002972 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2973 CXXMemberCallExpr *CE =
2974 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2975 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002976 return CE;
2977}
2978
Anders Carlsson85a307d2009-05-17 18:41:29 +00002979Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2980 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002981 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002982 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00002983 else
2984 return ExprError();
2985
Anders Carlsson85a307d2009-05-17 18:41:29 +00002986 return Owned(FullExpr);
2987}