blob: 0737e9f151a6566c014d350b6c69077f64a2c6c9 [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
Abramo Bagnarad7548482010-05-19 21:37:53 +0000264 return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
265 Range, NameLoc).getAsOpaquePtr();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000266 }
267
268 if (ObjectTypePtr)
269 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
270 << &II;
271 else
272 Diag(NameLoc, diag::err_destructor_class_name);
273
274 return 0;
275}
276
Douglas Gregor9da64192010-04-26 22:37:10 +0000277/// \brief Build a C++ typeid expression with a type operand.
278Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
279 SourceLocation TypeidLoc,
280 TypeSourceInfo *Operand,
281 SourceLocation RParenLoc) {
282 // C++ [expr.typeid]p4:
283 // The top-level cv-qualifiers of the lvalue expression or the type-id
284 // that is the operand of typeid are always ignored.
285 // If the type of the type-id is a class type or a reference to a class
286 // type, the class shall be completely-defined.
287 QualType T = Operand->getType().getNonReferenceType();
288 if (T->getAs<RecordType>() &&
289 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
290 return ExprError();
Daniel Dunbar0547ad32010-05-11 21:32:35 +0000291
Douglas Gregor9da64192010-04-26 22:37:10 +0000292 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
293 Operand,
294 SourceRange(TypeidLoc, RParenLoc)));
295}
296
297/// \brief Build a C++ typeid expression with an expression operand.
298Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
299 SourceLocation TypeidLoc,
300 ExprArg Operand,
301 SourceLocation RParenLoc) {
302 bool isUnevaluatedOperand = true;
303 Expr *E = static_cast<Expr *>(Operand.get());
304 if (E && !E->isTypeDependent()) {
305 QualType T = E->getType();
306 if (const RecordType *RecordT = T->getAs<RecordType>()) {
307 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
308 // C++ [expr.typeid]p3:
309 // [...] If the type of the expression is a class type, the class
310 // shall be completely-defined.
311 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
312 return ExprError();
313
314 // C++ [expr.typeid]p3:
315 // When typeid is applied to an expression other than an lvalue of a
316 // polymorphic class type [...] [the] expression is an unevaluated
317 // operand. [...]
Douglas Gregor88d292c2010-05-13 16:44:06 +0000318 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000319 isUnevaluatedOperand = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000320
321 // We require a vtable to query the type at run time.
322 MarkVTableUsed(TypeidLoc, RecordD);
323 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000324 }
325
326 // C++ [expr.typeid]p4:
327 // [...] If the type of the type-id is a reference to a possibly
328 // cv-qualified type, the result of the typeid expression refers to a
329 // std::type_info object representing the cv-unqualified referenced
330 // type.
331 if (T.hasQualifiers()) {
332 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
333 E->isLvalue(Context));
334 Operand.release();
335 Operand = Owned(E);
336 }
337 }
338
339 // If this is an unevaluated operand, clear out the set of
340 // declaration references we have been computing and eliminate any
341 // temporaries introduced in its computation.
342 if (isUnevaluatedOperand)
343 ExprEvalContexts.back().Context = Unevaluated;
344
345 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
346 Operand.takeAs<Expr>(),
347 SourceRange(TypeidLoc, RParenLoc)));
348}
349
350/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000351Action::OwningExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000352Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
353 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000354 // Find the std::type_info type.
Douglas Gregor87f54062009-09-15 22:30:29 +0000355 if (!StdNamespace)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000356 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000357
Chris Lattnerec7f7732008-11-20 05:51:55 +0000358 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCall27b18f82009-11-17 02:14:36 +0000359 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
360 LookupQualifiedName(R, StdNamespace);
John McCall67c00872009-12-02 08:25:40 +0000361 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattnerec7f7732008-11-20 05:51:55 +0000362 if (!TypeInfoRecordDecl)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000363 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor9da64192010-04-26 22:37:10 +0000364
Sebastian Redlc4704762008-11-11 11:37:55 +0000365 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor9da64192010-04-26 22:37:10 +0000366
367 if (isType) {
368 // The operand is a type; handle it as such.
369 TypeSourceInfo *TInfo = 0;
370 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
371 if (T.isNull())
372 return ExprError();
373
374 if (!TInfo)
375 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000376
Douglas Gregor9da64192010-04-26 22:37:10 +0000377 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000378 }
Mike Stump11289f42009-09-09 15:08:12 +0000379
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // The operand is an expression.
381 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000382}
383
Steve Naroff66356bd2007-09-16 14:56:35 +0000384/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000385Action::OwningExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000386Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000387 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000388 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000389 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
390 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000391}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000392
Sebastian Redl576fd422009-05-10 18:38:11 +0000393/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
394Action::OwningExprResult
395Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
396 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
397}
398
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000399/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000400Action::OwningExprResult
401Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000402 Expr *Ex = E.takeAs<Expr>();
403 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
404 return ExprError();
405 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
406}
407
408/// CheckCXXThrowOperand - Validate the operand of a throw.
409bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
410 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000411 // A throw-expression initializes a temporary object, called the exception
412 // object, the type of which is determined by removing any top-level
413 // cv-qualifiers from the static type of the operand of throw and adjusting
414 // the type from "array of T" or "function returning T" to "pointer to T"
415 // or "pointer to function returning T", [...]
416 if (E->getType().hasQualifiers())
417 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
418 E->isLvalue(Context) == Expr::LV_Valid);
419
Sebastian Redl4de47b42009-04-27 20:27:31 +0000420 DefaultFunctionArrayConversion(E);
421
422 // If the type of the exception would be an incomplete type or a pointer
423 // to an incomplete type other than (cv) void the program is ill-formed.
424 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000425 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000426 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000427 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000428 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000429 }
430 if (!isPointer || !Ty->isVoidType()) {
431 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlsson029fc692009-08-26 22:59:12 +0000432 PDiag(isPointer ? diag::err_throw_incomplete_ptr
433 : diag::err_throw_incomplete)
434 << E->getSourceRange()))
Sebastian Redl4de47b42009-04-27 20:27:31 +0000435 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000436
Douglas Gregore8154332010-04-15 18:05:39 +0000437 if (RequireNonAbstractType(ThrowLoc, E->getType(),
438 PDiag(diag::err_throw_abstract_type)
439 << E->getSourceRange()))
440 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000441 }
442
John McCall2e6567a2010-04-22 01:10:34 +0000443 // Initialize the exception result. This implicitly weeds out
444 // abstract types or types with inaccessible copy constructors.
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000445 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCall2e6567a2010-04-22 01:10:34 +0000446 InitializedEntity Entity =
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000447 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
448 /*NRVO=*/false);
John McCall2e6567a2010-04-22 01:10:34 +0000449 OwningExprResult Res = PerformCopyInitialization(Entity,
450 SourceLocation(),
451 Owned(E));
452 if (Res.isInvalid())
453 return true;
454 E = Res.takeAs<Expr>();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000455
456 // If we are throwing a polymorphic class type or pointer thereof,
457 // exception handling will make use of the vtable.
458 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
459 MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl()));
460
Sebastian Redl4de47b42009-04-27 20:27:31 +0000461 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000462}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000463
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000464Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000465 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
466 /// is a non-lvalue expression whose value is the address of the object for
467 /// which the function is called.
468
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000469 if (!isa<FunctionDecl>(CurContext))
470 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000471
472 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
473 if (MD->isInstance())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000474 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000475 MD->getThisType(Context),
476 /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000477
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000478 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000479}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000480
481/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
482/// Can be interpreted either as function-style casting ("int(x)")
483/// or class type construction ("ClassType(x,y,z)")
484/// or creation of a value-initialized type ("int()").
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000485Action::OwningExprResult
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000486Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
487 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000488 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000489 SourceLocation *CommaLocs,
490 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000491 if (!TypeRep)
492 return ExprError();
493
John McCall97513962010-01-15 18:39:57 +0000494 TypeSourceInfo *TInfo;
495 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
496 if (!TInfo)
497 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000498 unsigned NumExprs = exprs.size();
499 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000500 SourceLocation TyBeginLoc = TypeRange.getBegin();
501 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
502
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000503 if (Ty->isDependentType() ||
Douglas Gregor0950e412009-03-13 21:01:28 +0000504 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000505 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000506
507 return Owned(CXXUnresolvedConstructExpr::Create(Context,
508 TypeRange.getBegin(), Ty,
Douglas Gregorce934142009-05-20 18:46:25 +0000509 LParenLoc,
510 Exprs, NumExprs,
511 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000512 }
513
Anders Carlsson55243162009-08-27 03:53:50 +0000514 if (Ty->isArrayType())
515 return ExprError(Diag(TyBeginLoc,
516 diag::err_value_init_for_array_type) << FullRange);
517 if (!Ty->isVoidType() &&
518 RequireCompleteType(TyBeginLoc, Ty,
519 PDiag(diag::err_invalid_incomplete_type_use)
520 << FullRange))
521 return ExprError();
Fariborz Jahanian9a14b842009-10-23 21:01:39 +0000522
Anders Carlsson55243162009-08-27 03:53:50 +0000523 if (RequireNonAbstractType(TyBeginLoc, Ty,
524 diag::err_allocation_of_abstract_type))
525 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000526
527
Douglas Gregordd04d332009-01-16 18:33:17 +0000528 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000529 // If the expression list is a single expression, the type conversion
530 // expression is equivalent (in definedness, and if defined in meaning) to the
531 // corresponding cast expression.
532 //
533 if (NumExprs == 1) {
Anders Carlssonf10e4142009-08-07 22:21:05 +0000534 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000535 CXXBaseSpecifierArray BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +0000536 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
537 /*FunctionalStyle=*/true))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000538 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +0000539
540 exprs.release();
Anders Carlssone9766d52009-09-09 21:33:21 +0000541
542 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000543 TInfo, TyBeginLoc, Kind,
Anders Carlsson5d270e82010-04-24 18:38:56 +0000544 Exprs[0], BasePath,
545 RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000546 }
547
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000548 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregordd04d332009-01-16 18:33:17 +0000549 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000550
Mike Stump11289f42009-09-09 15:08:12 +0000551 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlsson574315a2009-08-27 05:08:22 +0000552 !Record->hasTrivialDestructor()) {
Eli Friedmana6824272010-01-31 20:58:15 +0000553 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
554 InitializationKind Kind
555 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
556 LParenLoc, RParenLoc)
557 : InitializationKind::CreateValue(TypeRange.getBegin(),
558 LParenLoc, RParenLoc);
559 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
560 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
561 move(exprs));
Douglas Gregordd04d332009-01-16 18:33:17 +0000562
Eli Friedmana6824272010-01-31 20:58:15 +0000563 // FIXME: Improve AST representation?
564 return move(Result);
Douglas Gregordd04d332009-01-16 18:33:17 +0000565 }
566
567 // Fall through to value-initialize an object of class type that
568 // doesn't have a user-declared default constructor.
569 }
570
571 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000572 // If the expression list specifies more than a single value, the type shall
573 // be a class with a suitably declared constructor.
574 //
575 if (NumExprs > 1)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000576 return ExprError(Diag(CommaLocs[0],
577 diag::err_builtin_func_cast_more_than_one_arg)
578 << FullRange);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000579
580 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregordd04d332009-01-16 18:33:17 +0000581 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000582 // The expression T(), where T is a simple-type-specifier for a non-array
583 // complete object type or the (possibly cv-qualified) void type, creates an
584 // rvalue of the specified type, which is value-initialized.
585 //
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000586 exprs.release();
587 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000588}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000589
590
Sebastian Redlbd150f42008-11-21 19:14:01 +0000591/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
592/// @code new (memory) int[size][4] @endcode
593/// or
594/// @code ::new Foo(23, "hello") @endcode
595/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000596Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000597Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000598 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redlbd150f42008-11-21 19:14:01 +0000599 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redl351bb782008-12-02 14:43:59 +0000600 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000601 MultiExprArg ConstructorArgs,
Mike Stump11289f42009-09-09 15:08:12 +0000602 SourceLocation ConstructorRParen) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000603 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000604 // If the specified type is an array, unwrap it and save the expression.
605 if (D.getNumTypeObjects() > 0 &&
606 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
607 DeclaratorChunk &Chunk = D.getTypeObject(0);
608 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000609 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
610 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000611 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000612 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
613 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000614
615 if (ParenTypeId) {
616 // Can't have dynamic array size when the type-id is in parentheses.
617 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
618 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
619 !NumElts->isIntegerConstantExpr(Context)) {
620 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
621 << NumElts->getSourceRange();
622 return ExprError();
623 }
624 }
625
Sebastian Redl351bb782008-12-02 14:43:59 +0000626 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000627 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000628 }
629
Douglas Gregor73341c42009-09-11 00:18:58 +0000630 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000631 if (ArraySize) {
632 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000633 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
634 break;
635
636 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
637 if (Expr *NumElts = (Expr *)Array.NumElts) {
638 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
639 !NumElts->isIntegerConstantExpr(Context)) {
640 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
641 << NumElts->getSourceRange();
642 return ExprError();
643 }
644 }
645 }
646 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000647
John McCallbcd03502009-12-07 02:54:59 +0000648 //FIXME: Store TypeSourceInfo in CXXNew expression.
649 TypeSourceInfo *TInfo = 0;
650 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000651 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000652 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000653
Mike Stump11289f42009-09-09 15:08:12 +0000654 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000655 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000656 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +0000657 PlacementRParen,
658 ParenTypeId,
Mike Stump11289f42009-09-09 15:08:12 +0000659 AllocType,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000660 D.getSourceRange().getBegin(),
661 D.getSourceRange(),
662 Owned(ArraySize),
663 ConstructorLParen,
664 move(ConstructorArgs),
665 ConstructorRParen);
666}
667
Mike Stump11289f42009-09-09 15:08:12 +0000668Sema::OwningExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +0000669Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
670 SourceLocation PlacementLParen,
671 MultiExprArg PlacementArgs,
672 SourceLocation PlacementRParen,
Mike Stump11289f42009-09-09 15:08:12 +0000673 bool ParenTypeId,
Douglas Gregord0fefba2009-05-21 00:00:09 +0000674 QualType AllocType,
675 SourceLocation TypeLoc,
676 SourceRange TypeRange,
677 ExprArg ArraySizeE,
678 SourceLocation ConstructorLParen,
679 MultiExprArg ConstructorArgs,
680 SourceLocation ConstructorRParen) {
681 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000682 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +0000683
Douglas Gregorcda95f42010-05-16 16:01:03 +0000684 // Per C++0x [expr.new]p5, the type being constructed may be a
685 // typedef of an array type.
686 if (!ArraySizeE.get()) {
687 if (const ConstantArrayType *Array
688 = Context.getAsConstantArrayType(AllocType)) {
689 ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
690 Context.getSizeType(),
691 TypeRange.getEnd()));
692 AllocType = Array->getElementType();
693 }
694 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000695
Douglas Gregorcda95f42010-05-16 16:01:03 +0000696 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl351bb782008-12-02 14:43:59 +0000697
Sebastian Redlbd150f42008-11-21 19:14:01 +0000698 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
699 // or enumeration type with a non-negative value."
Douglas Gregord0fefba2009-05-21 00:00:09 +0000700 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000701 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redl351bb782008-12-02 14:43:59 +0000702 QualType SizeType = ArraySize->getType();
703 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000704 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
705 diag::err_array_size_not_integral)
706 << SizeType << ArraySize->getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000707 // Let's see if this is a constant < 0. If so, we reject it out of hand.
708 // We don't care about special rules, so we tell the machinery it's not
709 // evaluated - it gives us a result in more cases.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000710 if (!ArraySize->isValueDependent()) {
711 llvm::APSInt Value;
712 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
713 if (Value < llvm::APSInt(
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000714 llvm::APInt::getNullValue(Value.getBitWidth()),
715 Value.isUnsigned()))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000716 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
717 diag::err_typecheck_negative_array_size)
718 << ArraySize->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000719 }
Sebastian Redl351bb782008-12-02 14:43:59 +0000720 }
Anders Carlsson8ab20bb2009-09-23 00:37:25 +0000721
Eli Friedman06ed2a52009-10-20 08:27:19 +0000722 ImpCastExprToType(ArraySize, Context.getSizeType(),
723 CastExpr::CK_IntegralCast);
Sebastian Redl351bb782008-12-02 14:43:59 +0000724 }
Sebastian Redlbd150f42008-11-21 19:14:01 +0000725
Sebastian Redlbd150f42008-11-21 19:14:01 +0000726 FunctionDecl *OperatorNew = 0;
727 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000728 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
729 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000730
Sebastian Redl8d2ccae2009-02-26 14:39:58 +0000731 if (!AllocType->isDependentType() &&
732 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
733 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000734 SourceRange(PlacementLParen, PlacementRParen),
735 UseGlobal, AllocType, ArraySize, PlaceArgs,
736 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000737 return ExprError();
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000738 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000739 if (OperatorNew) {
740 // Add default arguments, if any.
741 const FunctionProtoType *Proto =
742 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +0000743 VariadicCallType CallType =
744 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlssonc144bc22010-05-03 02:07:56 +0000745
746 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
747 Proto, 1, PlaceArgs, NumPlaceArgs,
748 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +0000749 return ExprError();
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000750
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +0000751 NumPlaceArgs = AllPlaceArgs.size();
752 if (NumPlaceArgs > 0)
753 PlaceArgs = &AllPlaceArgs[0];
754 }
755
Sebastian Redlbd150f42008-11-21 19:14:01 +0000756 bool Init = ConstructorLParen.isValid();
757 // --- Choosing a constructor ---
Sebastian Redlbd150f42008-11-21 19:14:01 +0000758 CXXConstructorDecl *Constructor = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000759 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
760 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmanfd8d4e12009-11-08 22:15:39 +0000761 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
762
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000763 // Array 'new' can't have any initializers.
Anders Carlssone6ae81b2010-05-16 16:24:20 +0000764 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
Anders Carlssonc6bb0e12010-05-03 15:45:23 +0000765 SourceRange InitRange(ConsArgs[0]->getLocStart(),
766 ConsArgs[NumConsArgs - 1]->getLocEnd());
767
768 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
769 return ExprError();
770 }
771
Douglas Gregor85dabae2009-12-16 01:38:02 +0000772 if (!AllocType->isDependentType() &&
773 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
774 // C++0x [expr.new]p15:
775 // A new-expression that creates an object of type T initializes that
776 // object as follows:
777 InitializationKind Kind
778 // - If the new-initializer is omitted, the object is default-
779 // initialized (8.5); if no initialization is performed,
780 // the object has indeterminate value
781 = !Init? InitializationKind::CreateDefault(TypeLoc)
782 // - Otherwise, the new-initializer is interpreted according to the
783 // initialization rules of 8.5 for direct-initialization.
784 : InitializationKind::CreateDirect(TypeLoc,
785 ConstructorLParen,
786 ConstructorRParen);
787
Douglas Gregor85dabae2009-12-16 01:38:02 +0000788 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +0000789 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000790 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000791 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
792 move(ConstructorArgs));
793 if (FullInit.isInvalid())
794 return ExprError();
795
796 // FullInit is our initializer; walk through it to determine if it's a
797 // constructor call, which CXXNewExpr handles directly.
798 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
799 if (CXXBindTemporaryExpr *Binder
800 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
801 FullInitExpr = Binder->getSubExpr();
802 if (CXXConstructExpr *Construct
803 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
804 Constructor = Construct->getConstructor();
805 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
806 AEnd = Construct->arg_end();
807 A != AEnd; ++A)
808 ConvertedConstructorArgs.push_back(A->Retain());
809 } else {
810 // Take the converted initializer.
811 ConvertedConstructorArgs.push_back(FullInit.release());
812 }
813 } else {
814 // No initialization required.
815 }
816
817 // Take the converted arguments and use them for the new expression.
Douglas Gregor5d3507d2009-09-09 23:08:42 +0000818 NumConsArgs = ConvertedConstructorArgs.size();
819 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +0000820 }
Douglas Gregor85dabae2009-12-16 01:38:02 +0000821
Douglas Gregor6642ca22010-02-26 05:06:18 +0000822 // Mark the new and delete operators as referenced.
823 if (OperatorNew)
824 MarkDeclarationReferenced(StartLoc, OperatorNew);
825 if (OperatorDelete)
826 MarkDeclarationReferenced(StartLoc, OperatorDelete);
827
Sebastian Redlbd150f42008-11-21 19:14:01 +0000828 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor4bbd1ac2009-10-17 21:40:42 +0000829
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000830 PlacementArgs.release();
831 ConstructorArgs.release();
Douglas Gregord0fefba2009-05-21 00:00:09 +0000832 ArraySizeE.release();
Ted Kremenek9d6eb402010-02-11 22:51:03 +0000833 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
834 PlaceArgs, NumPlaceArgs, ParenTypeId,
835 ArraySize, Constructor, Init,
836 ConsArgs, NumConsArgs, OperatorDelete,
837 ResultType, StartLoc,
838 Init ? ConstructorRParen :
839 SourceLocation()));
Sebastian Redlbd150f42008-11-21 19:14:01 +0000840}
841
842/// CheckAllocatedType - Checks that a type is suitable as the allocated type
843/// in a new-expression.
844/// dimension off and stores the size expression in ArraySize.
Douglas Gregord0fefba2009-05-21 00:00:09 +0000845bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000846 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +0000847 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
848 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +0000849 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000850 return Diag(Loc, diag::err_bad_new_type)
851 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000852 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +0000853 return Diag(Loc, diag::err_bad_new_type)
854 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +0000855 else if (!AllocType->isDependentType() &&
Douglas Gregord0fefba2009-05-21 00:00:09 +0000856 RequireCompleteType(Loc, AllocType,
Anders Carlssond624e162009-08-26 23:45:07 +0000857 PDiag(diag::err_new_incomplete_type)
858 << R))
Sebastian Redlbd150f42008-11-21 19:14:01 +0000859 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +0000860 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +0000861 diag::err_allocation_of_abstract_type))
862 return true;
Sebastian Redlbd150f42008-11-21 19:14:01 +0000863
Sebastian Redlbd150f42008-11-21 19:14:01 +0000864 return false;
865}
866
Douglas Gregor6642ca22010-02-26 05:06:18 +0000867/// \brief Determine whether the given function is a non-placement
868/// deallocation function.
869static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
870 if (FD->isInvalidDecl())
871 return false;
872
873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
874 return Method->isUsualDeallocationFunction();
875
876 return ((FD->getOverloadedOperator() == OO_Delete ||
877 FD->getOverloadedOperator() == OO_Array_Delete) &&
878 FD->getNumParams() == 1);
879}
880
Sebastian Redlfaf68082008-12-03 20:26:15 +0000881/// FindAllocationFunctions - Finds the overloads of operator new and delete
882/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000883bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
884 bool UseGlobal, QualType AllocType,
885 bool IsArray, Expr **PlaceArgs,
886 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +0000887 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +0000888 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +0000889 // --- Choosing an allocation function ---
890 // C++ 5.3.4p8 - 14 & 18
891 // 1) If UseGlobal is true, only look in the global scope. Else, also look
892 // in the scope of the allocated class.
893 // 2) If an array size is given, look for operator new[], else look for
894 // operator new.
895 // 3) The first argument is always size_t. Append the arguments from the
896 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +0000897
898 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
899 // We don't care about the actual value of this argument.
900 // FIXME: Should the Sema create the expression and embed it in the syntax
901 // tree? Or should the consumer just recalculate the value?
Anders Carlssona471db02009-08-16 20:29:29 +0000902 IntegerLiteral Size(llvm::APInt::getNullValue(
903 Context.Target.getPointerWidth(0)),
904 Context.getSizeType(),
905 SourceLocation());
906 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000907 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
908
Douglas Gregor6642ca22010-02-26 05:06:18 +0000909 // C++ [expr.new]p8:
910 // If the allocated type is a non-array type, the allocation
911 // function’s name is operator new and the deallocation function’s
912 // name is operator delete. If the allocated type is an array
913 // type, the allocation function’s name is operator new[] and the
914 // deallocation function’s name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +0000915 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
916 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +0000917 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
918 IsArray ? OO_Array_Delete : OO_Delete);
919
Sebastian Redlfaf68082008-12-03 20:26:15 +0000920 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +0000921 CXXRecordDecl *Record
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000922 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000923 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000924 AllocArgs.size(), Record, /*AllowMissing=*/true,
925 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000926 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000927 }
928 if (!OperatorNew) {
929 // Didn't find a member overload. Look for a global one.
930 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +0000931 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +0000932 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +0000933 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
934 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +0000935 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +0000936 }
937
John McCall0f55a032010-04-20 02:18:25 +0000938 // We don't need an operator delete if we're running under
939 // -fno-exceptions.
940 if (!getLangOptions().Exceptions) {
941 OperatorDelete = 0;
942 return false;
943 }
944
Anders Carlsson6f9dabf2009-05-31 20:26:12 +0000945 // FindAllocationOverload can change the passed in arguments, so we need to
946 // copy them back.
947 if (NumPlaceArgs > 0)
948 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregor6642ca22010-02-26 05:06:18 +0000950 // C++ [expr.new]p19:
951 //
952 // If the new-expression begins with a unary :: operator, the
953 // deallocation function’s name is looked up in the global
954 // scope. Otherwise, if the allocated type is a class type T or an
955 // array thereof, the deallocation function’s name is looked up in
956 // the scope of T. If this lookup fails to find the name, or if
957 // the allocated type is not a class type or array thereof, the
958 // deallocation function’s name is looked up in the global scope.
959 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
960 if (AllocType->isRecordType() && !UseGlobal) {
961 CXXRecordDecl *RD
962 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
963 LookupQualifiedName(FoundDelete, RD);
964 }
John McCallfb6f5262010-03-18 08:19:33 +0000965 if (FoundDelete.isAmbiguous())
966 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +0000967
968 if (FoundDelete.empty()) {
969 DeclareGlobalNewDelete();
970 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
971 }
972
973 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +0000974
975 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
976
John McCallfb6f5262010-03-18 08:19:33 +0000977 if (NumPlaceArgs > 0) {
Douglas Gregor6642ca22010-02-26 05:06:18 +0000978 // C++ [expr.new]p20:
979 // A declaration of a placement deallocation function matches the
980 // declaration of a placement allocation function if it has the
981 // same number of parameters and, after parameter transformations
982 // (8.3.5), all parameter types except the first are
983 // identical. [...]
984 //
985 // To perform this comparison, we compute the function type that
986 // the deallocation function should have, and use that type both
987 // for template argument deduction and for comparison purposes.
988 QualType ExpectedFunctionType;
989 {
990 const FunctionProtoType *Proto
991 = OperatorNew->getType()->getAs<FunctionProtoType>();
992 llvm::SmallVector<QualType, 4> ArgTypes;
993 ArgTypes.push_back(Context.VoidPtrTy);
994 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
995 ArgTypes.push_back(Proto->getArgType(I));
996
997 ExpectedFunctionType
998 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
999 ArgTypes.size(),
1000 Proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001001 0, false, false, 0, 0,
1002 FunctionType::ExtInfo());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001003 }
1004
1005 for (LookupResult::iterator D = FoundDelete.begin(),
1006 DEnd = FoundDelete.end();
1007 D != DEnd; ++D) {
1008 FunctionDecl *Fn = 0;
1009 if (FunctionTemplateDecl *FnTmpl
1010 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1011 // Perform template argument deduction to try to match the
1012 // expected function type.
1013 TemplateDeductionInfo Info(Context, StartLoc);
1014 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1015 continue;
1016 } else
1017 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1018
1019 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001020 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001021 }
1022 } else {
1023 // C++ [expr.new]p20:
1024 // [...] Any non-placement deallocation function matches a
1025 // non-placement allocation function. [...]
1026 for (LookupResult::iterator D = FoundDelete.begin(),
1027 DEnd = FoundDelete.end();
1028 D != DEnd; ++D) {
1029 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1030 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001031 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001032 }
1033 }
1034
1035 // C++ [expr.new]p20:
1036 // [...] If the lookup finds a single matching deallocation
1037 // function, that function will be called; otherwise, no
1038 // deallocation function will be called.
1039 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001040 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001041
1042 // C++0x [expr.new]p20:
1043 // If the lookup finds the two-parameter form of a usual
1044 // deallocation function (3.7.4.2) and that function, considered
1045 // as a placement deallocation function, would have been
1046 // selected as a match for the allocation function, the program
1047 // is ill-formed.
1048 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1049 isNonPlacementDeallocationFunction(OperatorDelete)) {
1050 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1051 << SourceRange(PlaceArgs[0]->getLocStart(),
1052 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1053 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1054 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001055 } else {
1056 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001057 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001058 }
1059 }
1060
Sebastian Redlfaf68082008-12-03 20:26:15 +00001061 return false;
1062}
1063
Sebastian Redl33a31012008-12-04 22:20:51 +00001064/// FindAllocationOverload - Find an fitting overload for the allocation
1065/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001066bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1067 DeclarationName Name, Expr** Args,
1068 unsigned NumArgs, DeclContext *Ctx,
Mike Stump11289f42009-09-09 15:08:12 +00001069 bool AllowMissing, FunctionDecl *&Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001070 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1071 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001072 if (R.empty()) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001073 if (AllowMissing)
1074 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001075 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001076 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001077 }
1078
John McCallfb6f5262010-03-18 08:19:33 +00001079 if (R.isAmbiguous())
1080 return true;
1081
1082 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001083
John McCallbc077cf2010-02-08 23:07:23 +00001084 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001085 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1086 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001087 // Even member operator new/delete are implicitly treated as
1088 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001089 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001090
John McCalla0296f72010-03-19 07:35:19 +00001091 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1092 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth93538422010-02-03 11:02:14 +00001093 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1094 Candidates,
1095 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001096 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001097 }
1098
John McCalla0296f72010-03-19 07:35:19 +00001099 FunctionDecl *Fn = cast<FunctionDecl>(D);
1100 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001101 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001102 }
1103
1104 // Do the resolution.
1105 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001106 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001107 case OR_Success: {
1108 // Got one!
1109 FunctionDecl *FnDecl = Best->Function;
1110 // The first argument is size_t, and the first parameter must be size_t,
1111 // too. This is checked on declaration and can be assumed. (It can't be
1112 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001113 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001114 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1115 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor34147272010-03-26 20:35:59 +00001116 OwningExprResult Result
1117 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1118 FnDecl->getParamDecl(i)),
1119 SourceLocation(),
1120 Owned(Args[i]->Retain()));
1121 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001122 return true;
Douglas Gregor34147272010-03-26 20:35:59 +00001123
1124 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001125 }
1126 Operator = FnDecl;
John McCalla0296f72010-03-19 07:35:19 +00001127 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001128 return false;
1129 }
1130
1131 case OR_No_Viable_Function:
Sebastian Redl33a31012008-12-04 22:20:51 +00001132 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001133 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001134 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001135 return true;
1136
1137 case OR_Ambiguous:
Sebastian Redl33a31012008-12-04 22:20:51 +00001138 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001139 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001140 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl33a31012008-12-04 22:20:51 +00001141 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001142
1143 case OR_Deleted:
1144 Diag(StartLoc, diag::err_ovl_deleted_call)
1145 << Best->Function->isDeleted()
1146 << Name << Range;
John McCallad907772010-01-12 07:18:19 +00001147 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001148 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001149 }
1150 assert(false && "Unreachable, bad result from BestViableFunction");
1151 return true;
1152}
1153
1154
Sebastian Redlfaf68082008-12-03 20:26:15 +00001155/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1156/// delete. These are:
1157/// @code
1158/// void* operator new(std::size_t) throw(std::bad_alloc);
1159/// void* operator new[](std::size_t) throw(std::bad_alloc);
1160/// void operator delete(void *) throw();
1161/// void operator delete[](void *) throw();
1162/// @endcode
1163/// Note that the placement and nothrow forms of new are *not* implicitly
1164/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001165void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001166 if (GlobalNewDeleteDeclared)
1167 return;
Douglas Gregor87f54062009-09-15 22:30:29 +00001168
1169 // C++ [basic.std.dynamic]p2:
1170 // [...] The following allocation and deallocation functions (18.4) are
1171 // implicitly declared in global scope in each translation unit of a
1172 // program
1173 //
1174 // void* operator new(std::size_t) throw(std::bad_alloc);
1175 // void* operator new[](std::size_t) throw(std::bad_alloc);
1176 // void operator delete(void*) throw();
1177 // void operator delete[](void*) throw();
1178 //
1179 // These implicit declarations introduce only the function names operator
1180 // new, operator new[], operator delete, operator delete[].
1181 //
1182 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1183 // "std" or "bad_alloc" as necessary to form the exception specification.
1184 // However, we do not make these implicit declarations visible to name
1185 // lookup.
1186 if (!StdNamespace) {
1187 // The "std" namespace has not yet been defined, so build one implicitly.
1188 StdNamespace = NamespaceDecl::Create(Context,
1189 Context.getTranslationUnitDecl(),
1190 SourceLocation(),
1191 &PP.getIdentifierTable().get("std"));
1192 StdNamespace->setImplicit(true);
1193 }
1194
1195 if (!StdBadAlloc) {
1196 // The "std::bad_alloc" class has not yet been declared, so build it
1197 // implicitly.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001198 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor87f54062009-09-15 22:30:29 +00001199 StdNamespace,
1200 SourceLocation(),
1201 &PP.getIdentifierTable().get("bad_alloc"),
1202 SourceLocation(), 0);
1203 StdBadAlloc->setImplicit(true);
1204 }
1205
Sebastian Redlfaf68082008-12-03 20:26:15 +00001206 GlobalNewDeleteDeclared = true;
1207
1208 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1209 QualType SizeT = Context.getSizeType();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001210 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001211
Sebastian Redlfaf68082008-12-03 20:26:15 +00001212 DeclareGlobalAllocationFunction(
1213 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001214 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001215 DeclareGlobalAllocationFunction(
1216 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001217 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001218 DeclareGlobalAllocationFunction(
1219 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1220 Context.VoidTy, VoidPtr);
1221 DeclareGlobalAllocationFunction(
1222 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1223 Context.VoidTy, VoidPtr);
1224}
1225
1226/// DeclareGlobalAllocationFunction - Declares a single implicit global
1227/// allocation function if it doesn't already exist.
1228void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001229 QualType Return, QualType Argument,
1230 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001231 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1232
1233 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001234 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001235 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001236 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001237 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001238 // Only look at non-template functions, as it is the predefined,
1239 // non-templated allocation function we are trying to declare here.
1240 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1241 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001242 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001243 Func->getParamDecl(0)->getType().getUnqualifiedType());
1244 // FIXME: Do we need to check for default arguments here?
1245 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1246 return;
1247 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001248 }
1249 }
1250
Douglas Gregor87f54062009-09-15 22:30:29 +00001251 QualType BadAllocType;
1252 bool HasBadAllocExceptionSpec
1253 = (Name.getCXXOverloadedOperator() == OO_New ||
1254 Name.getCXXOverloadedOperator() == OO_Array_New);
1255 if (HasBadAllocExceptionSpec) {
1256 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1257 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1258 }
1259
1260 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1261 true, false,
1262 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001263 &BadAllocType,
1264 FunctionType::ExtInfo());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001265 FunctionDecl *Alloc =
1266 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001267 FnType, /*TInfo=*/0, FunctionDecl::None,
1268 FunctionDecl::None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001269 Alloc->setImplicit();
Nuno Lopes13c88c72009-12-16 16:59:22 +00001270
1271 if (AddMallocAttr)
1272 Alloc->addAttr(::new (Context) MallocAttr());
1273
Sebastian Redlfaf68082008-12-03 20:26:15 +00001274 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCallbcd03502009-12-07 02:54:59 +00001275 0, Argument, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001276 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001277 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00001278 Alloc->setParams(&Param, 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001279
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001280 // FIXME: Also add this declaration to the IdentifierResolver, but
1281 // make sure it is at the end of the chain to coincide with the
1282 // global scope.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001283 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001284}
1285
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001286bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1287 DeclarationName Name,
Anders Carlssonf98849e2009-12-02 17:15:43 +00001288 FunctionDecl* &Operator) {
John McCall27b18f82009-11-17 02:14:36 +00001289 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001290 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001291 LookupQualifiedName(Found, RD);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001292
John McCall27b18f82009-11-17 02:14:36 +00001293 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001294 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001295
1296 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1297 F != FEnd; ++F) {
1298 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1299 if (Delete->isUsualDeallocationFunction()) {
1300 Operator = Delete;
1301 return false;
1302 }
1303 }
1304
1305 // We did find operator delete/operator delete[] declarations, but
1306 // none of them were suitable.
1307 if (!Found.empty()) {
1308 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1309 << Name << RD;
1310
1311 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1312 F != FEnd; ++F) {
Douglas Gregor861eb802010-04-25 20:55:08 +00001313 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001314 << Name;
1315 }
1316
1317 return true;
1318 }
1319
1320 // Look for a global declaration.
1321 DeclareGlobalNewDelete();
1322 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1323
1324 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1325 Expr* DeallocArgs[1];
1326 DeallocArgs[0] = &Null;
1327 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1328 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1329 Operator))
1330 return true;
1331
1332 assert(Operator && "Did not find a deallocation function!");
1333 return false;
1334}
1335
Sebastian Redlbd150f42008-11-21 19:14:01 +00001336/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1337/// @code ::delete ptr; @endcode
1338/// or
1339/// @code delete [] ptr; @endcode
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001340Action::OwningExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001341Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump11289f42009-09-09 15:08:12 +00001342 bool ArrayForm, ExprArg Operand) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001343 // C++ [expr.delete]p1:
1344 // The operand shall have a pointer type, or a class type having a single
1345 // conversion function to a pointer type. The result has type void.
1346 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001347 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1348
Anders Carlssona471db02009-08-16 20:29:29 +00001349 FunctionDecl *OperatorDelete = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001351 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001352 if (!Ex->isTypeDependent()) {
1353 QualType Type = Ex->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001354
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001355 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCallda4458e2010-03-31 01:36:47 +00001356 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1357
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00001358 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCallda4458e2010-03-31 01:36:47 +00001359 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001360 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001361 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00001362 NamedDecl *D = I.getDecl();
1363 if (isa<UsingShadowDecl>(D))
1364 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1365
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001366 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00001367 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001368 continue;
1369
John McCallda4458e2010-03-31 01:36:47 +00001370 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001371
1372 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1373 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1374 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001375 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001376 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001377 if (ObjectPtrConversions.size() == 1) {
1378 // We have a single conversion to a pointer-to-object type. Perform
1379 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00001380 // TODO: don't redo the conversion calculation.
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001381 Operand.release();
John McCallda4458e2010-03-31 01:36:47 +00001382 if (!PerformImplicitConversion(Ex,
1383 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001384 AA_Converting)) {
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001385 Operand = Owned(Ex);
1386 Type = Ex->getType();
1387 }
1388 }
1389 else if (ObjectPtrConversions.size() > 1) {
1390 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1391 << Type << Ex->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00001392 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1393 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00001394 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001395 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001396 }
1397
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001398 if (!Type->isPointerType())
1399 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1400 << Type << Ex->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001401
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001402 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001403 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001404 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1405 << Type << Ex->getSourceRange());
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001406 else if (!Pointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001407 RequireCompleteType(StartLoc, Pointee,
Anders Carlssond624e162009-08-26 23:45:07 +00001408 PDiag(diag::warn_delete_incomplete)
1409 << Ex->getSourceRange()))
Douglas Gregorc9a1a3b2009-03-24 20:13:58 +00001410 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001411
Douglas Gregor98496dc2009-09-29 21:38:53 +00001412 // C++ [expr.delete]p2:
1413 // [Note: a pointer to a const type can be the operand of a
1414 // delete-expression; it is not necessary to cast away the constness
1415 // (5.2.11) of the pointer expression before it is used as the operand
1416 // of the delete-expression. ]
1417 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1418 CastExpr::CK_NoOp);
1419
1420 // Update the operand.
1421 Operand.take();
1422 Operand = ExprArg(*this, Ex);
1423
Anders Carlssona471db02009-08-16 20:29:29 +00001424 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1425 ArrayForm ? OO_Array_Delete : OO_Delete);
1426
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001427 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1428 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1429
1430 if (!UseGlobal &&
1431 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00001432 return ExprError();
Anders Carlsson654e5c72009-11-14 03:17:38 +00001433
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001434 if (!RD->hasTrivialDestructor())
1435 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001436 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001437 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssona471db02009-08-16 20:29:29 +00001438 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001439
Anders Carlssona471db02009-08-16 20:29:29 +00001440 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001441 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00001442 DeclareGlobalNewDelete();
1443 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001444 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001445 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00001446 OperatorDelete))
1447 return ExprError();
1448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
John McCall0f55a032010-04-20 02:18:25 +00001450 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1451
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001452 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redlbd150f42008-11-21 19:14:01 +00001453 }
1454
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001455 Operand.release();
1456 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssona471db02009-08-16 20:29:29 +00001457 OperatorDelete, Ex, StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001458}
1459
Douglas Gregor633caca2009-11-23 23:44:04 +00001460/// \brief Check the use of the given variable as a C++ condition in an if,
1461/// while, do-while, or switch statement.
Douglas Gregore60e41a2010-05-06 17:25:47 +00001462Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1463 SourceLocation StmtLoc,
1464 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00001465 QualType T = ConditionVar->getType();
1466
1467 // C++ [stmt.select]p2:
1468 // The declarator shall not specify a function or an array.
1469 if (T->isFunctionType())
1470 return ExprError(Diag(ConditionVar->getLocation(),
1471 diag::err_invalid_use_of_function_type)
1472 << ConditionVar->getSourceRange());
1473 else if (T->isArrayType())
1474 return ExprError(Diag(ConditionVar->getLocation(),
1475 diag::err_invalid_use_of_array_type)
1476 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00001477
Douglas Gregore60e41a2010-05-06 17:25:47 +00001478 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1479 ConditionVar->getLocation(),
1480 ConditionVar->getType().getNonReferenceType());
1481 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1482 Condition->Destroy(Context);
1483 return ExprError();
1484 }
1485
1486 return Owned(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00001487}
1488
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001489/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1490bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1491 // C++ 6.4p4:
1492 // The value of a condition that is an initialized declaration in a statement
1493 // other than a switch statement is the value of the declared variable
1494 // implicitly converted to type bool. If that conversion is ill-formed, the
1495 // program is ill-formed.
1496 // The value of a condition that is an expression is the value of the
1497 // expression, implicitly converted to bool.
1498 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00001499 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001500}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001501
1502/// Helper function to determine whether this is the (deprecated) C++
1503/// conversion from a string literal to a pointer to non-const char or
1504/// non-const wchar_t (for narrow and wide string literals,
1505/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00001506bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001507Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1508 // Look inside the implicit cast, if it exists.
1509 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1510 From = Cast->getSubExpr();
1511
1512 // A string literal (2.13.4) that is not a wide string literal can
1513 // be converted to an rvalue of type "pointer to char"; a wide
1514 // string literal can be converted to an rvalue of type "pointer
1515 // to wchar_t" (C++ 4.2p2).
1516 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001517 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001518 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00001519 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001520 // This conversion is considered only when there is an
1521 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall8ccfcb52009-09-24 19:53:00 +00001522 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001523 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1524 (!StrLit->isWide() &&
1525 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1526 ToPointeeType->getKind() == BuiltinType::Char_S))))
1527 return true;
1528 }
1529
1530 return false;
1531}
Douglas Gregor39c16d42008-10-24 04:54:22 +00001532
Douglas Gregora4253922010-04-16 22:17:36 +00001533static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1534 SourceLocation CastLoc,
1535 QualType Ty,
1536 CastExpr::CastKind Kind,
1537 CXXMethodDecl *Method,
1538 Sema::ExprArg Arg) {
1539 Expr *From = Arg.takeAs<Expr>();
1540
1541 switch (Kind) {
1542 default: assert(0 && "Unhandled cast kind!");
1543 case CastExpr::CK_ConstructorConversion: {
1544 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1545
1546 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1547 Sema::MultiExprArg(S, (void **)&From, 1),
1548 CastLoc, ConstructorArgs))
1549 return S.ExprError();
1550
1551 Sema::OwningExprResult Result =
1552 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1553 move_arg(ConstructorArgs));
1554 if (Result.isInvalid())
1555 return S.ExprError();
1556
1557 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1558 }
1559
1560 case CastExpr::CK_UserDefinedConversion: {
1561 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1562
1563 // Create an implicit call expr that calls it.
1564 // FIXME: pass the FoundDecl for the user-defined conversion here
1565 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1566 return S.MaybeBindToTemporary(CE);
1567 }
1568 }
1569}
1570
Douglas Gregor5fb53972009-01-14 15:45:31 +00001571/// PerformImplicitConversion - Perform an implicit conversion of the
1572/// expression From to the type ToType using the pre-computed implicit
1573/// conversion sequence ICS. Returns true if there was an error, false
1574/// otherwise. The expression From is replaced with the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001575/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001576/// used in the error message.
1577bool
1578Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1579 const ImplicitConversionSequence &ICS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001580 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall0d1da222010-01-12 00:44:57 +00001581 switch (ICS.getKind()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001582 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001583 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redl7c353682009-11-14 21:15:49 +00001584 IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001585 return true;
1586 break;
1587
Anders Carlsson110b07b2009-09-15 06:28:28 +00001588 case ImplicitConversionSequence::UserDefinedConversion: {
1589
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001590 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1591 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001592 QualType BeforeToType;
1593 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00001594 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlsson110b07b2009-09-15 06:28:28 +00001595
1596 // If the user-defined conversion is specified by a conversion function,
1597 // the initial standard conversion sequence converts the source type to
1598 // the implicit object parameter of the conversion function.
1599 BeforeToType = Context.getTagDeclType(Conv->getParent());
1600 } else if (const CXXConstructorDecl *Ctor =
1601 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlssone9766d52009-09-09 21:33:21 +00001602 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001603 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00001604 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001605 // If the user-defined conversion is specified by a constructor, the
1606 // initial standard conversion sequence converts the source type to the
1607 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00001608 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1609 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001610 }
Anders Carlssone9766d52009-09-09 21:33:21 +00001611 else
1612 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian55824512009-11-06 00:23:08 +00001613 // Whatch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00001614 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian55824512009-11-06 00:23:08 +00001615 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001616 ICS.UserDefined.Before, AA_Converting,
Sebastian Redl7c353682009-11-14 21:15:49 +00001617 IgnoreBaseAccess))
Fariborz Jahanian55824512009-11-06 00:23:08 +00001618 return true;
1619 }
Anders Carlsson110b07b2009-09-15 06:28:28 +00001620
Anders Carlssone9766d52009-09-09 21:33:21 +00001621 OwningExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00001622 = BuildCXXCastArgument(*this,
1623 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00001624 ToType.getNonReferenceType(),
1625 CastKind, cast<CXXMethodDecl>(FD),
1626 Owned(From));
1627
1628 if (CastArg.isInvalid())
1629 return true;
Eli Friedmane96f1d32009-11-27 04:41:50 +00001630
1631 From = CastArg.takeAs<Expr>();
1632
Eli Friedmane96f1d32009-11-27 04:41:50 +00001633 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001634 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001635 }
John McCall0d1da222010-01-12 00:44:57 +00001636
1637 case ImplicitConversionSequence::AmbiguousConversion:
1638 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1639 PDiag(diag::err_typecheck_ambiguous_condition)
1640 << From->getSourceRange());
1641 return true;
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00001642
Douglas Gregor39c16d42008-10-24 04:54:22 +00001643 case ImplicitConversionSequence::EllipsisConversion:
1644 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001646
1647 case ImplicitConversionSequence::BadConversion:
1648 return true;
1649 }
1650
1651 // Everything went well.
1652 return false;
1653}
1654
1655/// PerformImplicitConversion - Perform an implicit conversion of the
1656/// expression From to the type ToType by following the standard
1657/// conversion sequence SCS. Returns true if there was an error, false
1658/// otherwise. The expression From is replaced with the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00001659/// expression. Flavor is the context in which we're performing this
1660/// conversion, for use in error messages.
Mike Stump11289f42009-09-09 15:08:12 +00001661bool
Douglas Gregor39c16d42008-10-24 04:54:22 +00001662Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001663 const StandardConversionSequence& SCS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001664 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump87c57ac2009-05-16 07:39:55 +00001665 // Overall FIXME: we are recomputing too many types here and doing far too
1666 // much extra work. What this means is that we need to keep track of more
1667 // information that is computed when we try the implicit conversion initially,
1668 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001669 QualType FromType = From->getType();
1670
Douglas Gregor2fe98832008-11-03 19:09:14 +00001671 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00001672 // FIXME: When can ToType be a reference type?
1673 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00001674 if (SCS.Second == ICK_Derived_To_Base) {
1675 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1676 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1677 MultiExprArg(*this, (void **)&From, 1),
1678 /*FIXME:ConstructLoc*/SourceLocation(),
1679 ConstructorArgs))
1680 return true;
1681 OwningExprResult FromResult =
1682 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1683 ToType, SCS.CopyConstructor,
1684 move_arg(ConstructorArgs));
1685 if (FromResult.isInvalid())
1686 return true;
1687 From = FromResult.takeAs<Expr>();
1688 return false;
1689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690 OwningExprResult FromResult =
1691 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1692 ToType, SCS.CopyConstructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00001693 MultiExprArg(*this, (void**)&From, 1));
Mike Stump11289f42009-09-09 15:08:12 +00001694
Anders Carlsson6eb55572009-08-25 05:12:04 +00001695 if (FromResult.isInvalid())
1696 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001697
Anders Carlsson6eb55572009-08-25 05:12:04 +00001698 From = FromResult.takeAs<Expr>();
Douglas Gregor2fe98832008-11-03 19:09:14 +00001699 return false;
1700 }
1701
Douglas Gregor980fb162010-04-29 18:24:40 +00001702 // Resolve overloaded function references.
1703 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1704 DeclAccessPair Found;
1705 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1706 true, Found);
1707 if (!Fn)
1708 return true;
1709
1710 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1711 return true;
1712
1713 From = FixOverloadedFunctionReference(From, Found, Fn);
1714 FromType = From->getType();
1715 }
1716
Douglas Gregor39c16d42008-10-24 04:54:22 +00001717 // Perform the first implicit conversion.
1718 switch (SCS.First) {
1719 case ICK_Identity:
1720 case ICK_Lvalue_To_Rvalue:
1721 // Nothing to do.
1722 break;
1723
1724 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00001725 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson2c101b32009-08-08 21:04:35 +00001726 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001727 break;
1728
1729 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001730 FromType = Context.getPointerType(FromType);
Anders Carlsson6904f642009-09-01 20:37:18 +00001731 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001732 break;
1733
1734 default:
1735 assert(false && "Improper first standard conversion");
1736 break;
1737 }
1738
1739 // Perform the second implicit conversion
1740 switch (SCS.Second) {
1741 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00001742 // If both sides are functions (or pointers/references to them), there could
1743 // be incompatible exception declarations.
1744 if (CheckExceptionSpecCompatibility(From, ToType))
1745 return true;
1746 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00001747 break;
1748
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001749 case ICK_NoReturn_Adjustment:
1750 // If both sides are functions (or pointers/references to them), there could
1751 // be incompatible exception declarations.
1752 if (CheckExceptionSpecCompatibility(From, ToType))
1753 return true;
1754
1755 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1756 CastExpr::CK_NoOp);
1757 break;
1758
Douglas Gregor39c16d42008-10-24 04:54:22 +00001759 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001760 case ICK_Integral_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001761 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1762 break;
1763
1764 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001765 case ICK_Floating_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001766 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1767 break;
1768
1769 case ICK_Complex_Promotion:
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001770 case ICK_Complex_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001771 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1772 break;
1773
Douglas Gregor39c16d42008-10-24 04:54:22 +00001774 case ICK_Floating_Integral:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001775 if (ToType->isFloatingType())
1776 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1777 else
1778 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1779 break;
1780
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001781 case ICK_Compatible_Conversion:
Eli Friedman06ed2a52009-10-20 08:27:19 +00001782 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001783 break;
1784
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001785 case ICK_Pointer_Conversion: {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001786 if (SCS.IncompatibleObjC) {
1787 // Diagnose incompatible Objective-C conversions
Mike Stump11289f42009-09-09 15:08:12 +00001788 Diag(From->getSourceRange().getBegin(),
Douglas Gregor47d3f272008-12-19 17:40:08 +00001789 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00001790 << From->getType() << ToType << Action
Douglas Gregor47d3f272008-12-19 17:40:08 +00001791 << From->getSourceRange();
1792 }
1793
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001794
1795 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssona70cff62010-04-24 19:06:50 +00001796 CXXBaseSpecifierArray BasePath;
1797 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor39c16d42008-10-24 04:54:22 +00001798 return true;
Anders Carlssona70cff62010-04-24 19:06:50 +00001799 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001800 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001801 }
1802
1803 case ICK_Pointer_Member: {
1804 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001805 CXXBaseSpecifierArray BasePath;
1806 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1807 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001808 return true;
Sebastian Redl5d431642009-10-10 12:04:10 +00001809 if (CheckExceptionSpecCompatibility(From, ToType))
1810 return true;
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001811 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001812 break;
1813 }
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001814 case ICK_Boolean_Conversion: {
1815 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1816 if (FromType->isMemberPointerType())
1817 Kind = CastExpr::CK_MemberPointerToBoolean;
1818
1819 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor39c16d42008-10-24 04:54:22 +00001820 break;
Anders Carlsson7fa434c2009-11-23 20:04:44 +00001821 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001822
Douglas Gregor88d292c2010-05-13 16:44:06 +00001823 case ICK_Derived_To_Base: {
1824 CXXBaseSpecifierArray BasePath;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001825 if (CheckDerivedToBaseConversion(From->getType(),
1826 ToType.getNonReferenceType(),
1827 From->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001828 From->getSourceRange(),
1829 &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001830 IgnoreBaseAccess))
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001831 return true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001832
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001833 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00001834 CastExpr::CK_DerivedToBase,
1835 /*isLvalue=*/(From->getType()->isRecordType() &&
1836 From->isLvalue(Context) == Expr::LV_Valid),
1837 BasePath);
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001838 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00001839 }
1840
Douglas Gregor46188682010-05-18 22:42:18 +00001841 case ICK_Vector_Conversion:
1842 ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1843 break;
1844
1845 case ICK_Vector_Splat:
1846 ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1847 break;
1848
1849 case ICK_Complex_Real:
1850 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1851 break;
1852
1853 case ICK_Lvalue_To_Rvalue:
1854 case ICK_Array_To_Pointer:
1855 case ICK_Function_To_Pointer:
1856 case ICK_Qualification:
1857 case ICK_Num_Conversion_Kinds:
Douglas Gregor39c16d42008-10-24 04:54:22 +00001858 assert(false && "Improper second standard conversion");
1859 break;
1860 }
1861
1862 switch (SCS.Third) {
1863 case ICK_Identity:
1864 // Nothing to do.
1865 break;
1866
1867 case ICK_Qualification:
Mike Stump87c57ac2009-05-16 07:39:55 +00001868 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1869 // references.
Mike Stump11289f42009-09-09 15:08:12 +00001870 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00001871 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregore489a7d2010-02-28 18:30:25 +00001872
1873 if (SCS.DeprecatedStringLiteralToCharPtr)
1874 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1875 << ToType.getNonReferenceType();
1876
Douglas Gregor39c16d42008-10-24 04:54:22 +00001877 break;
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00001878
Douglas Gregor39c16d42008-10-24 04:54:22 +00001879 default:
Douglas Gregor46188682010-05-18 22:42:18 +00001880 assert(false && "Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00001881 break;
1882 }
1883
1884 return false;
1885}
1886
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001887Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1888 SourceLocation KWLoc,
1889 SourceLocation LParen,
1890 TypeTy *Ty,
1891 SourceLocation RParen) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001892 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001893
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001894 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1895 // all traits except __is_class, __is_enum and __is_union require a the type
1896 // to be complete.
1897 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump11289f42009-09-09 15:08:12 +00001898 if (RequireCompleteType(KWLoc, T,
Anders Carlsson029fc692009-08-26 22:59:12 +00001899 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001900 return ExprError();
1901 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001902
1903 // There is no point in eagerly computing the value. The traits are designed
1904 // to be used from type trait templates, so Ty will be a template parameter
1905 // 99% of the time.
Anders Carlsson1f9648d2009-07-07 19:06:02 +00001906 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1907 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001908}
Sebastian Redl5822f082009-02-07 20:10:22 +00001909
1910QualType Sema::CheckPointerToMemberOperands(
Mike Stump11289f42009-09-09 15:08:12 +00001911 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001912 const char *OpSpelling = isIndirect ? "->*" : ".*";
1913 // C++ 5.5p2
1914 // The binary operator .* [p3: ->*] binds its second operand, which shall
1915 // be of type "pointer to member of T" (where T is a completely-defined
1916 // class type) [...]
1917 QualType RType = rex->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001918 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00001919 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00001920 Diag(Loc, diag::err_bad_memptr_rhs)
1921 << OpSpelling << RType << rex->getSourceRange();
1922 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001923 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00001924
Sebastian Redl5822f082009-02-07 20:10:22 +00001925 QualType Class(MemPtr->getClass(), 0);
1926
Sebastian Redlc72350e2010-04-10 10:14:54 +00001927 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1928 return QualType();
1929
Sebastian Redl5822f082009-02-07 20:10:22 +00001930 // C++ 5.5p2
1931 // [...] to its first operand, which shall be of class T or of a class of
1932 // which T is an unambiguous and accessible base class. [p3: a pointer to
1933 // such a class]
1934 QualType LType = lex->getType();
1935 if (isIndirect) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001936 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl5822f082009-02-07 20:10:22 +00001937 LType = Ptr->getPointeeType().getNonReferenceType();
1938 else {
1939 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanian59f64202009-10-26 20:45:27 +00001940 << OpSpelling << 1 << LType
Douglas Gregora771f462010-03-31 17:46:05 +00001941 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00001942 return QualType();
1943 }
1944 }
1945
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001946 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00001947 // If we want to check the hierarchy, we need a complete type.
1948 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1949 << OpSpelling << (int)isIndirect)) {
1950 return QualType();
1951 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001952 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001953 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00001954 // FIXME: Would it be useful to print full ambiguity paths, or is that
1955 // overkill?
Sebastian Redl5822f082009-02-07 20:10:22 +00001956 if (!IsDerivedFrom(LType, Class, Paths) ||
1957 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1958 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001959 << (int)isIndirect << lex->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00001960 return QualType();
1961 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00001962 // Cast LHS to type of use.
1963 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1964 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlssona70cff62010-04-24 19:06:50 +00001965
1966 CXXBaseSpecifierArray BasePath;
1967 BuildBasePathArray(Paths, BasePath);
1968 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1969 BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00001970 }
1971
Fariborz Jahanianfff3fb22009-11-18 22:16:17 +00001972 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00001973 // Diagnose use of pointer-to-member type which when used as
1974 // the functional cast in a pointer-to-member expression.
1975 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1976 return QualType();
1977 }
Sebastian Redl5822f082009-02-07 20:10:22 +00001978 // C++ 5.5p2
1979 // The result is an object or a function of the type specified by the
1980 // second operand.
1981 // The cv qualifiers are the union of those in the pointer and the left side,
1982 // in accordance with 5.5p5 and 5.2.5.
1983 // FIXME: This returns a dereferenced member function pointer as a normal
1984 // function type. However, the only operation valid on such functions is
Mike Stump87c57ac2009-05-16 07:39:55 +00001985 // calling them. There's also a GCC extension to get a function pointer to the
1986 // thing, which is another complication, because this type - unlike the type
1987 // that is the result of this expression - takes the class as the first
Sebastian Redl5822f082009-02-07 20:10:22 +00001988 // argument.
1989 // We probably need a "MemberFunctionClosureType" or something like that.
1990 QualType Result = MemPtr->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00001991 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl5822f082009-02-07 20:10:22 +00001992 return Result;
1993}
Sebastian Redl1a99f442009-04-16 17:51:27 +00001994
Sebastian Redl1a99f442009-04-16 17:51:27 +00001995/// \brief Try to convert a type to another according to C++0x 5.16p3.
1996///
1997/// This is part of the parameter validation for the ? operator. If either
1998/// value operand is a class type, the two operands are attempted to be
1999/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002000/// It returns true if the program is ill-formed and has already been diagnosed
2001/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002002static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2003 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00002004 bool &HaveConversion,
2005 QualType &ToType) {
2006 HaveConversion = false;
2007 ToType = To->getType();
2008
2009 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2010 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00002011 // C++0x 5.16p3
2012 // The process for determining whether an operand expression E1 of type T1
2013 // can be converted to match an operand expression E2 of type T2 is defined
2014 // as follows:
2015 // -- If E2 is an lvalue:
Douglas Gregorf9edf802010-03-26 20:59:55 +00002016 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2017 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002018 // E1 can be converted to match E2 if E1 can be implicitly converted to
2019 // type "lvalue reference to T2", subject to the constraint that in the
2020 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002021 QualType T = Self.Context.getLValueReferenceType(ToType);
2022 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2023
2024 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2025 if (InitSeq.isDirectReferenceBinding()) {
2026 ToType = T;
2027 HaveConversion = true;
2028 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002029 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002030
2031 if (InitSeq.isAmbiguous())
2032 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002033 }
John McCall65eb8792010-02-25 01:37:24 +00002034
Sebastian Redl1a99f442009-04-16 17:51:27 +00002035 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2036 // -- if E1 and E2 have class type, and the underlying class types are
2037 // the same or one is a base class of the other:
2038 QualType FTy = From->getType();
2039 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002040 const RecordType *FRec = FTy->getAs<RecordType>();
2041 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002042 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2043 Self.IsDerivedFrom(FTy, TTy);
2044 if (FRec && TRec &&
2045 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002046 // E1 can be converted to match E2 if the class of T2 is the
2047 // same type as, or a base class of, the class of T1, and
2048 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00002049 if (FRec == TRec || FDerivedFromT) {
2050 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002051 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2052 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2053 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2054 HaveConversion = true;
2055 return false;
2056 }
2057
2058 if (InitSeq.isAmbiguous())
2059 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2060 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00002061 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002062
2063 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002064 }
Douglas Gregor838fcc32010-03-26 20:14:36 +00002065
2066 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2067 // implicitly converted to the type that expression E2 would have
Douglas Gregorf9edf802010-03-26 20:59:55 +00002068 // if E2 were converted to an rvalue (or the type it has, if E2 is
2069 // an rvalue).
2070 //
2071 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2072 // to the array-to-pointer or function-to-pointer conversions.
2073 if (!TTy->getAs<TagType>())
2074 TTy = TTy.getUnqualifiedType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002075
2076 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2077 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2078 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2079 ToType = TTy;
2080 if (InitSeq.isAmbiguous())
2081 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2082
Sebastian Redl1a99f442009-04-16 17:51:27 +00002083 return false;
2084}
2085
2086/// \brief Try to find a common type for two according to C++0x 5.16p5.
2087///
2088/// This is part of the parameter validation for the ? operator. If either
2089/// value operand is a class type, overload resolution is used to find a
2090/// conversion to a common type.
2091static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2092 SourceLocation Loc) {
2093 Expr *Args[2] = { LHS, RHS };
John McCallbc077cf2010-02-08 23:07:23 +00002094 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002095 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002096
2097 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00002098 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099 case OR_Success:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002100 // We found a match. Perform the conversions on the arguments and move on.
2101 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002102 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00002103 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002104 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002105 break;
2106 return false;
2107
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002108 case OR_No_Viable_Function:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002109 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2110 << LHS->getType() << RHS->getType()
2111 << LHS->getSourceRange() << RHS->getSourceRange();
2112 return true;
2113
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002114 case OR_Ambiguous:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002115 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2116 << LHS->getType() << RHS->getType()
2117 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00002118 // FIXME: Print the possible common types by printing the return types of
2119 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002120 break;
2121
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002122 case OR_Deleted:
Sebastian Redl1a99f442009-04-16 17:51:27 +00002123 assert(false && "Conditional operator has only built-in overloads");
2124 break;
2125 }
2126 return true;
2127}
2128
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002129/// \brief Perform an "extended" implicit conversion as returned by
2130/// TryClassUnification.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002131static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2132 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2133 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2134 SourceLocation());
2135 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2136 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2137 Sema::MultiExprArg(Self, (void **)&E, 1));
2138 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002139 return true;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002140
2141 E = Result.takeAs<Expr>();
Sebastian Redl5775af1a2009-04-17 16:30:52 +00002142 return false;
2143}
2144
Sebastian Redl1a99f442009-04-16 17:51:27 +00002145/// \brief Check the operands of ?: under C++ semantics.
2146///
2147/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2148/// extension. In this case, LHS == Cond. (But they're not aliases.)
2149QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2150 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00002151 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2152 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00002153
2154 // C++0x 5.16p1
2155 // The first expression is contextually converted to bool.
2156 if (!Cond->isTypeDependent()) {
2157 if (CheckCXXBooleanCondition(Cond))
2158 return QualType();
2159 }
2160
2161 // Either of the arguments dependent?
2162 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2163 return Context.DependentTy;
2164
2165 // C++0x 5.16p2
2166 // If either the second or the third operand has type (cv) void, ...
2167 QualType LTy = LHS->getType();
2168 QualType RTy = RHS->getType();
2169 bool LVoid = LTy->isVoidType();
2170 bool RVoid = RTy->isVoidType();
2171 if (LVoid || RVoid) {
2172 // ... then the [l2r] conversions are performed on the second and third
2173 // operands ...
Douglas Gregorb92a1562010-02-03 00:27:59 +00002174 DefaultFunctionArrayLvalueConversion(LHS);
2175 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002176 LTy = LHS->getType();
2177 RTy = RHS->getType();
2178
2179 // ... and one of the following shall hold:
2180 // -- The second or the third operand (but not both) is a throw-
2181 // expression; the result is of the type of the other and is an rvalue.
2182 bool LThrow = isa<CXXThrowExpr>(LHS);
2183 bool RThrow = isa<CXXThrowExpr>(RHS);
2184 if (LThrow && !RThrow)
2185 return RTy;
2186 if (RThrow && !LThrow)
2187 return LTy;
2188
2189 // -- Both the second and third operands have type void; the result is of
2190 // type void and is an rvalue.
2191 if (LVoid && RVoid)
2192 return Context.VoidTy;
2193
2194 // Neither holds, error.
2195 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2196 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2197 << LHS->getSourceRange() << RHS->getSourceRange();
2198 return QualType();
2199 }
2200
2201 // Neither is void.
2202
2203 // C++0x 5.16p3
2204 // Otherwise, if the second and third operand have different types, and
2205 // either has (cv) class type, and attempt is made to convert each of those
2206 // operands to the other.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002207 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00002208 (LTy->isRecordType() || RTy->isRecordType())) {
2209 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2210 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00002211 QualType L2RType, R2LType;
2212 bool HaveL2R, HaveR2L;
2213 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002214 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002215 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002216 return QualType();
Douglas Gregor838fcc32010-03-26 20:14:36 +00002217
Sebastian Redl1a99f442009-04-16 17:51:27 +00002218 // If both can be converted, [...] the program is ill-formed.
2219 if (HaveL2R && HaveR2L) {
2220 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2221 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2222 return QualType();
2223 }
2224
2225 // If exactly one conversion is possible, that conversion is applied to
2226 // the chosen operand and the converted operands are used in place of the
2227 // original operands for the remainder of this section.
2228 if (HaveL2R) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002229 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002230 return QualType();
2231 LTy = LHS->getType();
2232 } else if (HaveR2L) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00002233 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00002234 return QualType();
2235 RTy = RHS->getType();
2236 }
2237 }
2238
2239 // C++0x 5.16p4
2240 // If the second and third operands are lvalues and have the same type,
2241 // the result is of that type [...]
Douglas Gregor697a3912010-04-01 22:47:07 +00002242 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002243 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2244 RHS->isLvalue(Context) == Expr::LV_Valid)
2245 return LTy;
2246
2247 // C++0x 5.16p5
2248 // Otherwise, the result is an rvalue. If the second and third operands
2249 // do not have the same type, and either has (cv) class type, ...
2250 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2251 // ... overload resolution is used to determine the conversions (if any)
2252 // to be applied to the operands. If the overload resolution fails, the
2253 // program is ill-formed.
2254 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2255 return QualType();
2256 }
2257
2258 // C++0x 5.16p6
2259 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2260 // conversions are performed on the second and third operands.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002261 DefaultFunctionArrayLvalueConversion(LHS);
2262 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002263 LTy = LHS->getType();
2264 RTy = RHS->getType();
2265
2266 // After those conversions, one of the following shall hold:
2267 // -- The second and third operands have the same type; the result
2268 // is of that type.
2269 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2270 return LTy;
2271
Douglas Gregor46188682010-05-18 22:42:18 +00002272 // Extension: conditional operator involving vector types.
2273 if (LTy->isVectorType() || RTy->isVectorType())
2274 return CheckVectorOperands(QuestionLoc, LHS, RHS);
2275
Sebastian Redl1a99f442009-04-16 17:51:27 +00002276 // -- The second and third operands have arithmetic or enumeration type;
2277 // the usual arithmetic conversions are performed to bring them to a
2278 // common type, and the result is of that type.
2279 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2280 UsualArithmeticConversions(LHS, RHS);
2281 return LHS->getType();
2282 }
2283
2284 // -- The second and third operands have pointer type, or one has pointer
2285 // type and the other is a null pointer constant; pointer conversions
2286 // and qualification conversions are performed to bring them to their
2287 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00002288 // -- The second and third operands have pointer to member type, or one has
2289 // pointer to member type and the other is a null pointer constant;
2290 // pointer to member conversions and qualification conversions are
2291 // performed to bring them to a common type, whose cv-qualification
2292 // shall match the cv-qualification of either the second or the third
2293 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002294 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00002295 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002296 isSFINAEContext()? 0 : &NonStandardCompositeType);
2297 if (!Composite.isNull()) {
2298 if (NonStandardCompositeType)
2299 Diag(QuestionLoc,
2300 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2301 << LTy << RTy << Composite
2302 << LHS->getSourceRange() << RHS->getSourceRange();
2303
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002304 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002305 }
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002306
Douglas Gregor697a3912010-04-01 22:47:07 +00002307 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00002308 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2309 if (!Composite.isNull())
2310 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00002311
Sebastian Redl1a99f442009-04-16 17:51:27 +00002312 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2313 << LHS->getType() << RHS->getType()
2314 << LHS->getSourceRange() << RHS->getSourceRange();
2315 return QualType();
2316}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002317
2318/// \brief Find a merged pointer type and convert the two expressions to it.
2319///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002320/// This finds the composite pointer type (or member pointer type) for @p E1
2321/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2322/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002323/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002324///
Douglas Gregor19175ff2010-04-16 23:20:25 +00002325/// \param Loc The location of the operator requiring these two expressions to
2326/// be converted to the composite pointer type.
2327///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002328/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2329/// a non-standard (but still sane) composite type to which both expressions
2330/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2331/// will be set true.
Douglas Gregor19175ff2010-04-16 23:20:25 +00002332QualType Sema::FindCompositePointerType(SourceLocation Loc,
2333 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002334 bool *NonStandardCompositeType) {
2335 if (NonStandardCompositeType)
2336 *NonStandardCompositeType = false;
2337
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002338 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2339 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002340
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00002341 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2342 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002343 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002344
2345 // C++0x 5.9p2
2346 // Pointer conversions and qualification conversions are performed on
2347 // pointer operands to bring them to their composite pointer type. If
2348 // one operand is a null pointer constant, the composite pointer type is
2349 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00002350 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002351 if (T2->isMemberPointerType())
2352 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2353 else
2354 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002355 return T2;
2356 }
Douglas Gregor56751b52009-09-25 04:25:58 +00002357 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002358 if (T1->isMemberPointerType())
2359 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2360 else
2361 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002362 return T1;
2363 }
Mike Stump11289f42009-09-09 15:08:12 +00002364
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002365 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00002366 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2367 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002368 return QualType();
2369
2370 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2371 // the other has type "pointer to cv2 T" and the composite pointer type is
2372 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2373 // Otherwise, the composite pointer type is a pointer type similar to the
2374 // type of one of the operands, with a cv-qualification signature that is
2375 // the union of the cv-qualification signatures of the operand types.
2376 // In practice, the first part here is redundant; it's subsumed by the second.
2377 // What we do here is, we build the two possible composite types, and try the
2378 // conversions in both directions. If only one works, or if the two composite
2379 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00002380 // FIXME: extended qualifiers?
Sebastian Redl658262f2009-11-16 21:03:45 +00002381 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2382 QualifierVector QualifierUnion;
2383 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2384 ContainingClassVector;
2385 ContainingClassVector MemberOfClass;
2386 QualType Composite1 = Context.getCanonicalType(T1),
2387 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002388 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002389 do {
2390 const PointerType *Ptr1, *Ptr2;
2391 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2392 (Ptr2 = Composite2->getAs<PointerType>())) {
2393 Composite1 = Ptr1->getPointeeType();
2394 Composite2 = Ptr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002395
2396 // If we're allowed to create a non-standard composite type, keep track
2397 // of where we need to fill in additional 'const' qualifiers.
2398 if (NonStandardCompositeType &&
2399 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2400 NeedConstBefore = QualifierUnion.size();
2401
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002402 QualifierUnion.push_back(
2403 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2404 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2405 continue;
2406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002408 const MemberPointerType *MemPtr1, *MemPtr2;
2409 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2410 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2411 Composite1 = MemPtr1->getPointeeType();
2412 Composite2 = MemPtr2->getPointeeType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002413
2414 // If we're allowed to create a non-standard composite type, keep track
2415 // of where we need to fill in additional 'const' qualifiers.
2416 if (NonStandardCompositeType &&
2417 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2418 NeedConstBefore = QualifierUnion.size();
2419
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002420 QualifierUnion.push_back(
2421 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2422 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2423 MemPtr2->getClass()));
2424 continue;
2425 }
Mike Stump11289f42009-09-09 15:08:12 +00002426
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002427 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00002428
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002429 // Cannot unwrap any more types.
2430 break;
2431 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Douglas Gregor6f5f6422010-02-25 22:29:57 +00002433 if (NeedConstBefore && NonStandardCompositeType) {
2434 // Extension: Add 'const' to qualifiers that come before the first qualifier
2435 // mismatch, so that our (non-standard!) composite type meets the
2436 // requirements of C++ [conv.qual]p4 bullet 3.
2437 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2438 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2439 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2440 *NonStandardCompositeType = true;
2441 }
2442 }
2443 }
2444
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002445 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00002446 ContainingClassVector::reverse_iterator MOC
2447 = MemberOfClass.rbegin();
2448 for (QualifierVector::reverse_iterator
2449 I = QualifierUnion.rbegin(),
2450 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002451 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00002452 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002453 if (MOC->first && MOC->second) {
2454 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002455 Composite1 = Context.getMemberPointerType(
2456 Context.getQualifiedType(Composite1, Quals),
2457 MOC->first);
2458 Composite2 = Context.getMemberPointerType(
2459 Context.getQualifiedType(Composite2, Quals),
2460 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002461 } else {
2462 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00002463 Composite1
2464 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2465 Composite2
2466 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00002467 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002468 }
2469
Douglas Gregor19175ff2010-04-16 23:20:25 +00002470 // Try to convert to the first composite pointer type.
2471 InitializedEntity Entity1
2472 = InitializedEntity::InitializeTemporary(Composite1);
2473 InitializationKind Kind
2474 = InitializationKind::CreateCopy(Loc, SourceLocation());
2475 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2476 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregor19175ff2010-04-16 23:20:25 +00002478 if (E1ToC1 && E2ToC1) {
2479 // Conversion to Composite1 is viable.
2480 if (!Context.hasSameType(Composite1, Composite2)) {
2481 // Composite2 is a different type from Composite1. Check whether
2482 // Composite2 is also viable.
2483 InitializedEntity Entity2
2484 = InitializedEntity::InitializeTemporary(Composite2);
2485 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2486 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2487 if (E1ToC2 && E2ToC2) {
2488 // Both Composite1 and Composite2 are viable and are different;
2489 // this is an ambiguity.
2490 return QualType();
2491 }
2492 }
2493
2494 // Convert E1 to Composite1
2495 OwningExprResult E1Result
2496 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2497 if (E1Result.isInvalid())
2498 return QualType();
2499 E1 = E1Result.takeAs<Expr>();
2500
2501 // Convert E2 to Composite1
2502 OwningExprResult E2Result
2503 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2504 if (E2Result.isInvalid())
2505 return QualType();
2506 E2 = E2Result.takeAs<Expr>();
2507
2508 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002509 }
2510
Douglas Gregor19175ff2010-04-16 23:20:25 +00002511 // Check whether Composite2 is viable.
2512 InitializedEntity Entity2
2513 = InitializedEntity::InitializeTemporary(Composite2);
2514 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2515 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2516 if (!E1ToC2 || !E2ToC2)
2517 return QualType();
2518
2519 // Convert E1 to Composite2
2520 OwningExprResult E1Result
2521 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2522 if (E1Result.isInvalid())
2523 return QualType();
2524 E1 = E1Result.takeAs<Expr>();
2525
2526 // Convert E2 to Composite2
2527 OwningExprResult E2Result
2528 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2529 if (E2Result.isInvalid())
2530 return QualType();
2531 E2 = E2Result.takeAs<Expr>();
2532
2533 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00002534}
Anders Carlsson85a307d2009-05-17 18:41:29 +00002535
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002536Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlssonf86a8d12009-08-15 23:41:35 +00002537 if (!Context.getLangOptions().CPlusPlus)
2538 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002539
Douglas Gregor363b1512009-12-24 18:51:59 +00002540 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2541
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002542 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002543 if (!RT)
2544 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002545
John McCall67da35c2010-02-04 22:26:26 +00002546 // If this is the result of a call expression, our source might
2547 // actually be a reference, in which case we shouldn't bind.
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002548 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2549 QualType Ty = CE->getCallee()->getType();
2550 if (const PointerType *PT = Ty->getAs<PointerType>())
2551 Ty = PT->getPointeeType();
Fariborz Jahanianffcfecd2010-02-18 20:31:02 +00002552 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2553 Ty = BPT->getPointeeType();
2554
John McCall9dd450b2009-09-21 23:43:11 +00002555 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlssonaedb46f2009-09-14 01:30:44 +00002556 if (FTy->getResultType()->isReferenceType())
2557 return Owned(E);
2558 }
John McCall67da35c2010-02-04 22:26:26 +00002559
2560 // That should be enough to guarantee that this type is complete.
2561 // If it has a trivial destructor, we can avoid the extra copy.
2562 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2563 if (RD->hasTrivialDestructor())
2564 return Owned(E);
2565
Mike Stump11289f42009-09-09 15:08:12 +00002566 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002567 RD->getDestructor(Context));
Anders Carlssonc78576e2009-05-30 21:21:49 +00002568 ExprTemporaries.push_back(Temp);
Fariborz Jahanian67828442009-08-03 19:13:25 +00002569 if (CXXDestructorDecl *Destructor =
John McCall8e36d532010-04-07 00:41:46 +00002570 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahanian67828442009-08-03 19:13:25 +00002571 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00002572 CheckDestructorAccess(E->getExprLoc(), Destructor,
2573 PDiag(diag::err_access_dtor_temp)
2574 << E->getType());
2575 }
Anders Carlsson2d4cada2009-05-30 20:36:53 +00002576 // FIXME: Add the temporary to the temporaries vector.
2577 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2578}
2579
Anders Carlsson6e997b22009-12-15 20:51:39 +00002580Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002581 assert(SubExpr && "sub expression can't be null!");
Mike Stump11289f42009-09-09 15:08:12 +00002582
John McCallcc7e5bf2010-05-06 08:58:33 +00002583 // Check any implicit conversions within the expression.
2584 CheckImplicitConversions(SubExpr);
2585
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002586 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2587 assert(ExprTemporaries.size() >= FirstTemporary);
2588 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002589 return SubExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002591 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002592 &ExprTemporaries[FirstTemporary],
Anders Carlsson6e997b22009-12-15 20:51:39 +00002593 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor580cd4a2009-12-03 17:10:37 +00002594 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2595 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00002596
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002597 return E;
2598}
2599
Douglas Gregorb6ea6082009-12-22 22:17:25 +00002600Sema::OwningExprResult
2601Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2602 if (SubExpr.isInvalid())
2603 return ExprError();
2604
2605 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2606}
2607
Anders Carlssonafb2dad2009-12-16 02:09:40 +00002608FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2609 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2610 assert(ExprTemporaries.size() >= FirstTemporary);
2611
2612 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2613 CXXTemporary **Temporaries =
2614 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2615
2616 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2617
2618 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2619 ExprTemporaries.end());
2620
2621 return E;
2622}
2623
Mike Stump11289f42009-09-09 15:08:12 +00002624Sema::OwningExprResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002625Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00002626 tok::TokenKind OpKind, TypeTy *&ObjectType,
2627 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002628 // Since this might be a postfix expression, get rid of ParenListExprs.
2629 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump11289f42009-09-09 15:08:12 +00002630
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002631 Expr *BaseExpr = (Expr*)Base.get();
2632 assert(BaseExpr && "no record expansion");
Mike Stump11289f42009-09-09 15:08:12 +00002633
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002634 QualType BaseType = BaseExpr->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00002635 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002636 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00002637 // If we have a pointer to a dependent type and are using the -> operator,
2638 // the object type is the type that the pointer points to. We might still
2639 // have enough information about that type to do something useful.
2640 if (OpKind == tok::arrow)
2641 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2642 BaseType = Ptr->getPointeeType();
2643
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002644 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregore610ada2010-02-24 18:44:31 +00002645 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002646 return move(Base);
2647 }
Mike Stump11289f42009-09-09 15:08:12 +00002648
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002649 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00002650 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002651 // returned, with the original second operand.
2652 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00002653 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00002654 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002655 llvm::SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00002656 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc1538c02009-09-30 01:01:30 +00002657
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002658 while (BaseType->isRecordType()) {
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00002659 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002660 BaseExpr = (Expr*)Base.get();
2661 if (BaseExpr == NULL)
2662 return ExprError();
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002663 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00002664 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc1538c02009-09-30 01:01:30 +00002665 BaseType = BaseExpr->getType();
2666 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00002667 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002668 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00002669 for (unsigned i = 0; i < Locations.size(); i++)
2670 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00002671 return ExprError();
2672 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002673 }
Mike Stump11289f42009-09-09 15:08:12 +00002674
Douglas Gregore4f764f2009-11-20 19:58:21 +00002675 if (BaseType->isPointerType())
2676 BaseType = BaseType->getPointeeType();
2677 }
Mike Stump11289f42009-09-09 15:08:12 +00002678
2679 // We could end up with various non-record types here, such as extended
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002680 // vector types or Objective-C interfaces. Just return early and let
2681 // ActOnMemberReferenceExpr do the work.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002682 if (!BaseType->isRecordType()) {
2683 // C++ [basic.lookup.classref]p2:
2684 // [...] If the type of the object expression is of pointer to scalar
2685 // type, the unqualified-id is looked up in the context of the complete
2686 // postfix-expression.
Douglas Gregore610ada2010-02-24 18:44:31 +00002687 //
2688 // This also indicates that we should be parsing a
2689 // pseudo-destructor-name.
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002690 ObjectType = 0;
Douglas Gregore610ada2010-02-24 18:44:31 +00002691 MayBePseudoDestructor = true;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002692 return move(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694
Douglas Gregor3fad6172009-11-17 05:17:33 +00002695 // The object type must be complete (or dependent).
2696 if (!BaseType->isDependentType() &&
2697 RequireCompleteType(OpLoc, BaseType,
2698 PDiag(diag::err_incomplete_member_access)))
2699 return ExprError();
2700
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002701 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002702 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00002703 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002704 // type C (or of pointer to a class type C), the unqualified-id is looked
2705 // up in the scope of class C. [...]
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002706 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump11289f42009-09-09 15:08:12 +00002707 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00002708}
2709
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002710Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2711 ExprArg MemExpr) {
2712 Expr *E = (Expr *) MemExpr.get();
2713 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2714 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2715 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregora771f462010-03-31 17:46:05 +00002716 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002717
2718 return ActOnCallExpr(/*Scope*/ 0,
2719 move(MemExpr),
2720 /*LPLoc*/ ExpectedLParenLoc,
2721 Sema::MultiExprArg(*this, 0, 0),
2722 /*CommaLocs*/ 0,
2723 /*RPLoc*/ ExpectedLParenLoc);
2724}
Douglas Gregore610ada2010-02-24 18:44:31 +00002725
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002726Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2727 SourceLocation OpLoc,
2728 tok::TokenKind OpKind,
2729 const CXXScopeSpec &SS,
Douglas Gregor651fe5e2010-02-24 23:40:28 +00002730 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002731 SourceLocation CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002732 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002733 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002734 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00002735 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002736
2737 // C++ [expr.pseudo]p2:
2738 // The left-hand side of the dot operator shall be of scalar type. The
2739 // left-hand side of the arrow operator shall be of pointer to scalar type.
2740 // This scalar type is the object type.
2741 Expr *BaseE = (Expr *)Base.get();
2742 QualType ObjectType = BaseE->getType();
2743 if (OpKind == tok::arrow) {
2744 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2745 ObjectType = Ptr->getPointeeType();
2746 } else if (!BaseE->isTypeDependent()) {
2747 // The user wrote "p->" when she probably meant "p."; fix it.
2748 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2749 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002750 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002751 if (isSFINAEContext())
2752 return ExprError();
2753
2754 OpKind = tok::period;
2755 }
2756 }
2757
2758 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2759 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2760 << ObjectType << BaseE->getSourceRange();
2761 return ExprError();
2762 }
2763
2764 // C++ [expr.pseudo]p2:
2765 // [...] The cv-unqualified versions of the object type and of the type
2766 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002767 if (DestructedTypeInfo) {
2768 QualType DestructedType = DestructedTypeInfo->getType();
2769 SourceLocation DestructedTypeStart
2770 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2771 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2772 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2773 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2774 << ObjectType << DestructedType << BaseE->getSourceRange()
2775 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2776
2777 // Recover by setting the destructed type to the object type.
2778 DestructedType = ObjectType;
2779 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2780 DestructedTypeStart);
2781 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2782 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002783 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002784
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002785 // C++ [expr.pseudo]p2:
2786 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2787 // form
2788 //
2789 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2790 //
2791 // shall designate the same scalar type.
2792 if (ScopeTypeInfo) {
2793 QualType ScopeType = ScopeTypeInfo->getType();
2794 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2795 !Context.hasSameType(ScopeType, ObjectType)) {
2796
2797 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2798 diag::err_pseudo_dtor_type_mismatch)
2799 << ObjectType << ScopeType << BaseE->getSourceRange()
2800 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2801
2802 ScopeType = QualType();
2803 ScopeTypeInfo = 0;
2804 }
2805 }
2806
2807 OwningExprResult Result
2808 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2809 Base.takeAs<Expr>(),
2810 OpKind == tok::arrow,
2811 OpLoc,
2812 (NestedNameSpecifier *) SS.getScopeRep(),
2813 SS.getRange(),
2814 ScopeTypeInfo,
2815 CCLoc,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002816 TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002817 Destructed));
2818
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002819 if (HasTrailingLParen)
2820 return move(Result);
2821
Douglas Gregor678f90d2010-02-25 01:56:36 +00002822 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002823}
2824
2825Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2826 SourceLocation OpLoc,
2827 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002828 CXXScopeSpec &SS,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002829 UnqualifiedId &FirstTypeName,
2830 SourceLocation CCLoc,
2831 SourceLocation TildeLoc,
2832 UnqualifiedId &SecondTypeName,
2833 bool HasTrailingLParen) {
2834 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2835 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2836 "Invalid first type name in pseudo-destructor");
2837 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2838 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2839 "Invalid second type name in pseudo-destructor");
2840
2841 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002842
2843 // C++ [expr.pseudo]p2:
2844 // The left-hand side of the dot operator shall be of scalar type. The
2845 // left-hand side of the arrow operator shall be of pointer to scalar type.
2846 // This scalar type is the object type.
2847 QualType ObjectType = BaseE->getType();
2848 if (OpKind == tok::arrow) {
2849 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2850 ObjectType = Ptr->getPointeeType();
Douglas Gregor678f90d2010-02-25 01:56:36 +00002851 } else if (!ObjectType->isDependentType()) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002852 // The user wrote "p->" when she probably meant "p."; fix it.
2853 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregor678f90d2010-02-25 01:56:36 +00002854 << ObjectType << true
Douglas Gregora771f462010-03-31 17:46:05 +00002855 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002856 if (isSFINAEContext())
2857 return ExprError();
2858
2859 OpKind = tok::period;
2860 }
2861 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00002862
2863 // Compute the object type that we should use for name lookup purposes. Only
2864 // record types and dependent types matter.
2865 void *ObjectTypePtrForLookup = 0;
2866 if (!SS.isSet()) {
2867 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2868 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2869 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2870 }
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002871
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002872 // Convert the name of the type being destructed (following the ~) into a
2873 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002874 QualType DestructedType;
2875 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00002876 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002877 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2878 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2879 SecondTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002880 S, &SS, true, ObjectTypePtrForLookup);
2881 if (!T &&
2882 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2883 (!SS.isSet() && ObjectType->isDependentType()))) {
2884 // The name of the type being destroyed is a dependent name, and we
2885 // couldn't find anything useful in scope. Just store the identifier and
2886 // it's location, and we'll perform (qualified) name lookup again at
2887 // template instantiation time.
2888 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2889 SecondTypeName.StartLocation);
2890 } else if (!T) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002891 Diag(SecondTypeName.StartLocation,
2892 diag::err_pseudo_dtor_destructor_non_type)
2893 << SecondTypeName.Identifier << ObjectType;
2894 if (isSFINAEContext())
2895 return ExprError();
2896
2897 // Recover by assuming we had the right type all along.
2898 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002899 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002900 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002901 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002902 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002903 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002904 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2905 TemplateId->getTemplateArgs(),
2906 TemplateId->NumArgs);
2907 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2908 TemplateId->TemplateNameLoc,
2909 TemplateId->LAngleLoc,
2910 TemplateArgsPtr,
2911 TemplateId->RAngleLoc);
2912 if (T.isInvalid() || !T.get()) {
2913 // Recover by assuming we had the right type all along.
2914 DestructedType = ObjectType;
2915 } else
2916 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002917 }
2918
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002919 // If we've performed some kind of recovery, (re-)build the type source
2920 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00002921 if (!DestructedType.isNull()) {
2922 if (!DestructedTypeInfo)
2923 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002924 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00002925 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2926 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002927
2928 // Convert the name of the scope type (the type prior to '::') into a type.
2929 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002930 QualType ScopeType;
2931 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2932 FirstTypeName.Identifier) {
2933 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2934 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2935 FirstTypeName.StartLocation,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002936 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002937 if (!T) {
2938 Diag(FirstTypeName.StartLocation,
2939 diag::err_pseudo_dtor_destructor_non_type)
2940 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002941
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002942 if (isSFINAEContext())
2943 return ExprError();
2944
2945 // Just drop this type. It's unnecessary anyway.
2946 ScopeType = QualType();
2947 } else
2948 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002949 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002950 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002951 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002952 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2953 TemplateId->getTemplateArgs(),
2954 TemplateId->NumArgs);
2955 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2956 TemplateId->TemplateNameLoc,
2957 TemplateId->LAngleLoc,
2958 TemplateArgsPtr,
2959 TemplateId->RAngleLoc);
2960 if (T.isInvalid() || !T.get()) {
2961 // Recover by dropping this type.
2962 ScopeType = QualType();
2963 } else
2964 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00002965 }
2966 }
Douglas Gregor90ad9222010-02-24 23:02:30 +00002967
2968 if (!ScopeType.isNull() && !ScopeTypeInfo)
2969 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2970 FirstTypeName.StartLocation);
2971
2972
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00002973 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00002974 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00002975 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00002976}
2977
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002978CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall16df1e52010-03-30 21:47:33 +00002979 NamedDecl *FoundDecl,
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002980 CXXMethodDecl *Method) {
John McCall16df1e52010-03-30 21:47:33 +00002981 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2982 FoundDecl, Method))
Eli Friedmanf7195532009-12-09 04:53:56 +00002983 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2984
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002985 MemberExpr *ME =
2986 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2987 SourceLocation(), Method->getType());
Eli Friedmanf7195532009-12-09 04:53:56 +00002988 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor27381f32009-11-23 12:27:39 +00002989 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2990 CXXMemberCallExpr *CE =
2991 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2992 Exp->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00002993 return CE;
2994}
2995
Anders Carlsson85a307d2009-05-17 18:41:29 +00002996Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2997 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlssonb3d05d62009-06-05 15:38:08 +00002998 if (FullExpr)
Anders Carlsson6e997b22009-12-15 20:51:39 +00002999 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00003000 else
3001 return ExprError();
3002
Anders Carlsson85a307d2009-05-17 18:41:29 +00003003 return Owned(FullExpr);
3004}