blob: 34b10aec8807c2f2775f5f657d0bc17e927674de [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//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000295
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
Richard Smithef2cd8f2017-02-08 20:39:08 +0000326ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
327 ParsedType ObjectType) {
328 if (DS.getTypeSpecType() == DeclSpec::TST_error)
329 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000330
Richard Smithef2cd8f2017-02-08 20:39:08 +0000331 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
332 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
333 return nullptr;
334 }
335
336 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
337 "unexpected type in getDestructorType");
338 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
339
340 // If we know the type of the object, check that the correct destructor
341 // type was named now; we can give better diagnostics this way.
342 QualType SearchType = GetTypeFromParser(ObjectType);
343 if (!SearchType.isNull() && !SearchType->isDependentType() &&
344 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000345 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
346 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000347 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000348 }
349
350 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000351}
352
Richard Smithd091dc12013-12-05 00:58:33 +0000353bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
354 const UnqualifiedId &Name) {
355 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
356
357 if (!SS.isValid())
358 return false;
359
360 switch (SS.getScopeRep()->getKind()) {
361 case NestedNameSpecifier::Identifier:
362 case NestedNameSpecifier::TypeSpec:
363 case NestedNameSpecifier::TypeSpecWithTemplate:
364 // Per C++11 [over.literal]p2, literal operators can only be declared at
365 // namespace scope. Therefore, this unqualified-id cannot name anything.
366 // Reject it early, because we have no AST representation for this in the
367 // case where the scope is dependent.
368 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
369 << SS.getScopeRep();
370 return true;
371
372 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000373 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000374 case NestedNameSpecifier::Namespace:
375 case NestedNameSpecifier::NamespaceAlias:
376 return false;
377 }
378
379 llvm_unreachable("unknown nested name specifier kind");
380}
381
Douglas Gregor9da64192010-04-26 22:37:10 +0000382/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000383ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000384 SourceLocation TypeidLoc,
385 TypeSourceInfo *Operand,
386 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000387 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000389 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000391 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000392 Qualifiers Quals;
393 QualType T
394 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
395 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000396 if (T->getAs<RecordType>() &&
397 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
398 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
David Majnemer6f3150a2014-11-21 21:09:12 +0000400 if (T->isVariablyModifiedType())
401 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
402
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000403 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
404 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000405}
406
407/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000408ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000409 SourceLocation TypeidLoc,
410 Expr *E,
411 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000412 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000413 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000414 if (E->getType()->isPlaceholderType()) {
415 ExprResult result = CheckPlaceholderExpr(E);
416 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000417 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000418 }
419
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 QualType T = E->getType();
421 if (const RecordType *RecordT = T->getAs<RecordType>()) {
422 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
423 // C++ [expr.typeid]p3:
424 // [...] If the type of the expression is a class type, the class
425 // shall be completely-defined.
426 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
427 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor9da64192010-04-26 22:37:10 +0000429 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000430 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000431 // polymorphic class type [...] [the] expression is an unevaluated
432 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000433 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000434 // The subexpression is potentially evaluated; switch the context
435 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000436 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000437 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000438 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000439
440 // We require a vtable to query the type at run time.
441 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000442 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000443 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor9da64192010-04-26 22:37:10 +0000446 // C++ [expr.typeid]p4:
447 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448 // cv-qualified type, the result of the typeid expression refers to a
449 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000451 Qualifiers Quals;
452 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
453 if (!Context.hasSameType(T, UnqualT)) {
454 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000455 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000456 }
457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458
David Majnemer6f3150a2014-11-21 21:09:12 +0000459 if (E->getType()->isVariablyModifiedType())
460 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
461 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000462 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000463 E->HasSideEffects(Context, WasEvaluated)) {
464 // The expression operand for typeid is in an unevaluated expression
465 // context, so side effects could result in unintended consequences.
466 Diag(E->getExprLoc(), WasEvaluated
467 ? diag::warn_side_effects_typeid
468 : diag::warn_side_effects_unevaluated_context);
469 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000470
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000471 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
472 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000473}
474
475/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000476ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000477Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
478 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000479 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000480 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000481 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000482
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl) {
484 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
485 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
486 LookupQualifiedName(R, getStdNamespace());
487 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000488 // Microsoft's typeinfo doesn't have type_info in std but in the global
489 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000490 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000491 LookupQualifiedName(R, Context.getTranslationUnitDecl());
492 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
493 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000494 if (!CXXTypeInfoDecl)
495 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000497
Nico Weber1b7f39d2012-05-20 01:27:21 +0000498 if (!getLangOpts().RTTI) {
499 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
500 }
501
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000502 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 if (isType) {
505 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000506 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000507 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
508 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000509 if (T.isNull())
510 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
Douglas Gregor9da64192010-04-26 22:37:10 +0000512 if (!TInfo)
513 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000514
Douglas Gregor9da64192010-04-26 22:37:10 +0000515 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000519 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000520}
521
David Majnemer1dbc7a72016-03-27 04:46:07 +0000522/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
523/// a single GUID.
524static void
525getUuidAttrOfType(Sema &SemaRef, QualType QT,
526 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
527 // Optionally remove one level of pointer, reference or array indirection.
528 const Type *Ty = QT.getTypePtr();
529 if (QT->isPointerType() || QT->isReferenceType())
530 Ty = QT->getPointeeType().getTypePtr();
531 else if (QT->isArrayType())
532 Ty = Ty->getBaseElementTypeUnsafe();
533
Reid Klecknere516eab2016-12-13 18:58:09 +0000534 const auto *TD = Ty->getAsTagDecl();
535 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000536 return;
537
Reid Klecknere516eab2016-12-13 18:58:09 +0000538 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000539 UuidAttrs.insert(Uuid);
540 return;
541 }
542
543 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000544 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000545 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
546 for (const TemplateArgument &TA : TAL.asArray()) {
547 const UuidAttr *UuidForTA = nullptr;
548 if (TA.getKind() == TemplateArgument::Type)
549 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
550 else if (TA.getKind() == TemplateArgument::Declaration)
551 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
552
553 if (UuidForTA)
554 UuidAttrs.insert(UuidForTA);
555 }
556 }
557}
558
Francois Pichet9f4f2072010-09-08 12:20:18 +0000559/// \brief Build a Microsoft __uuidof expression with a type operand.
560ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
561 SourceLocation TypeidLoc,
562 TypeSourceInfo *Operand,
563 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000564 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000565 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000566 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
567 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
568 if (UuidAttrs.empty())
569 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
570 if (UuidAttrs.size() > 1)
571 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000572 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
David Majnemer2041b462016-03-28 03:19:50 +0000575 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000576 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000577}
578
579/// \brief Build a Microsoft __uuidof expression with an expression operand.
580ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
581 SourceLocation TypeidLoc,
582 Expr *E,
583 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000584 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000585 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000586 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
587 UuidStr = "00000000-0000-0000-0000-000000000000";
588 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000589 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
590 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
591 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000592 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000593 if (UuidAttrs.size() > 1)
594 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000595 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000596 }
Francois Pichetb7577652010-12-27 01:32:00 +0000597 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000598
David Majnemer2041b462016-03-28 03:19:50 +0000599 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000600 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000601}
602
603/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
604ExprResult
605Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
606 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000608 if (!MSVCGuidDecl) {
609 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
610 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
611 LookupQualifiedName(R, Context.getTranslationUnitDecl());
612 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
613 if (!MSVCGuidDecl)
614 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615 }
616
Francois Pichet9f4f2072010-09-08 12:20:18 +0000617 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Francois Pichet9f4f2072010-09-08 12:20:18 +0000619 if (isType) {
620 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000621 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000622 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
623 &TInfo);
624 if (T.isNull())
625 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Francois Pichet9f4f2072010-09-08 12:20:18 +0000627 if (!TInfo)
628 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
629
630 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
631 }
632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000634 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
635}
636
Steve Naroff66356bd2007-09-16 14:56:35 +0000637/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000638ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000639Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000640 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000641 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000642 return new (Context)
643 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000644}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000645
Sebastian Redl576fd422009-05-10 18:38:11 +0000646/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000647ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000648Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000649 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000650}
651
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000652/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000653ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000654Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
655 bool IsThrownVarInScope = false;
656 if (Ex) {
657 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000658 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000659 // copy/move construction of a class object [...]
660 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000661 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000662 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000663 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000664 // innermost enclosing try-block (if there is one), the copy/move
665 // operation from the operand to the exception object (15.1) can be
666 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000667 // exception object
668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
669 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
670 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
671 for( ; S; S = S->getParent()) {
672 if (S->isDeclScope(Var)) {
673 IsThrownVarInScope = true;
674 break;
675 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000676
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000677 if (S->getFlags() &
678 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
679 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
680 Scope::TryScope))
681 break;
682 }
683 }
684 }
685 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000686
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000687 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
688}
689
Simon Pilgrim75c26882016-09-30 14:25:09 +0000690ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000691 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000692 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000693 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000694 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000695 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000696
Justin Lebar2a8db342016-09-28 22:45:54 +0000697 // Exceptions aren't allowed in CUDA device code.
698 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000699 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
700 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000701
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000702 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
703 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
704
John Wiegley01296292011-04-08 18:41:53 +0000705 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000706 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
707 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000708 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000709
710 // Initialize the exception result. This implicitly weeds out
711 // abstract types or types with inaccessible copy constructors.
712
713 // C++0x [class.copymove]p31:
714 // When certain criteria are met, an implementation is allowed to omit the
715 // copy/move construction of a class object [...]
716 //
717 // - in a throw-expression, when the operand is the name of a
718 // non-volatile automatic object (other than a function or
719 // catch-clause
720 // parameter) whose scope does not extend beyond the end of the
721 // innermost enclosing try-block (if there is one), the copy/move
722 // operation from the operand to the exception object (15.1) can be
723 // omitted by constructing the automatic object directly into the
724 // exception object
725 const VarDecl *NRVOVariable = nullptr;
726 if (IsThrownVarInScope)
727 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
728
729 InitializedEntity Entity = InitializedEntity::InitializeException(
730 OpLoc, ExceptionObjectTy,
731 /*NRVO=*/NRVOVariable != nullptr);
732 ExprResult Res = PerformMoveOrCopyInitialization(
733 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
734 if (Res.isInvalid())
735 return ExprError();
736 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000737 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000738
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000739 return new (Context)
740 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000741}
742
David Majnemere7a818f2015-03-06 18:53:55 +0000743static void
744collectPublicBases(CXXRecordDecl *RD,
745 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
746 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
747 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
748 bool ParentIsPublic) {
749 for (const CXXBaseSpecifier &BS : RD->bases()) {
750 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
751 bool NewSubobject;
752 // Virtual bases constitute the same subobject. Non-virtual bases are
753 // always distinct subobjects.
754 if (BS.isVirtual())
755 NewSubobject = VBases.insert(BaseDecl).second;
756 else
757 NewSubobject = true;
758
759 if (NewSubobject)
760 ++SubobjectsSeen[BaseDecl];
761
762 // Only add subobjects which have public access throughout the entire chain.
763 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
764 if (PublicPath)
765 PublicSubobjectsSeen.insert(BaseDecl);
766
767 // Recurse on to each base subobject.
768 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
769 PublicPath);
770 }
771}
772
773static void getUnambiguousPublicSubobjects(
774 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
775 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
776 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
777 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
778 SubobjectsSeen[RD] = 1;
779 PublicSubobjectsSeen.insert(RD);
780 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
781 /*ParentIsPublic=*/true);
782
783 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
784 // Skip ambiguous objects.
785 if (SubobjectsSeen[PublicSubobject] > 1)
786 continue;
787
788 Objects.push_back(PublicSubobject);
789 }
790}
791
Sebastian Redl4de47b42009-04-27 20:27:31 +0000792/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000793bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
794 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000795 // If the type of the exception would be an incomplete type or a pointer
796 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000797 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000798 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000799 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000800 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000801 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802 }
803 if (!isPointer || !Ty->isVoidType()) {
804 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000805 isPointer ? diag::err_throw_incomplete_ptr
806 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000807 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000808 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000809
David Majnemerd09a51c2015-03-03 01:50:05 +0000810 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000811 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000812 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000813 }
814
Eli Friedman91a3d272010-06-03 20:39:03 +0000815 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000816 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
817 if (!RD)
818 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000819
Douglas Gregor88d292c2010-05-13 16:44:06 +0000820 // If we are throwing a polymorphic class type or pointer thereof,
821 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000822 MarkVTableUsed(ThrowLoc, RD);
823
Eli Friedman36ebbec2010-10-12 20:32:36 +0000824 // If a pointer is thrown, the referenced object will not be destroyed.
825 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000826 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000827
Richard Smitheec915d62012-02-18 04:13:32 +0000828 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000829 if (!RD->hasIrrelevantDestructor()) {
830 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
831 MarkFunctionReferenced(E->getExprLoc(), Destructor);
832 CheckDestructorAccess(E->getExprLoc(), Destructor,
833 PDiag(diag::err_access_dtor_exception) << Ty);
834 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000835 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000836 }
837 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000838
David Majnemerdfa6d202015-03-11 18:36:39 +0000839 // The MSVC ABI creates a list of all types which can catch the exception
840 // object. This list also references the appropriate copy constructor to call
841 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000843 // We are only interested in the public, unambiguous bases contained within
844 // the exception object. Bases which are ambiguous or otherwise
845 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000846 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
847 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000848
David Majnemere7a818f2015-03-06 18:53:55 +0000849 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000850 // Attempt to lookup the copy constructor. Various pieces of machinery
851 // will spring into action, like template instantiation, which means this
852 // cannot be a simple walk of the class's decls. Instead, we must perform
853 // lookup and overload resolution.
854 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
855 if (!CD)
856 continue;
857
858 // Mark the constructor referenced as it is used by this throw expression.
859 MarkFunctionReferenced(E->getExprLoc(), CD);
860
861 // Skip this copy constructor if it is trivial, we don't need to record it
862 // in the catchable type data.
863 if (CD->isTrivial())
864 continue;
865
866 // The copy constructor is non-trivial, create a mapping from this class
867 // type to this constructor.
868 // N.B. The selection of copy constructor is not sensitive to this
869 // particular throw-site. Lookup will be performed at the catch-site to
870 // ensure that the copy constructor is, in fact, accessible (via
871 // friendship or any other means).
872 Context.addCopyConstructorForExceptionObject(Subobject, CD);
873
874 // We don't keep the instantiated default argument expressions around so
875 // we must rebuild them here.
876 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000877 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
878 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000879 }
880 }
881 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000882
David Majnemerba3e5ec2015-03-13 18:26:17 +0000883 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000884}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885
Faisal Vali67b04462016-06-11 16:41:54 +0000886static QualType adjustCVQualifiersForCXXThisWithinLambda(
887 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
888 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
889
890 QualType ClassType = ThisTy->getPointeeType();
891 LambdaScopeInfo *CurLSI = nullptr;
892 DeclContext *CurDC = CurSemaContext;
893
894 // Iterate through the stack of lambdas starting from the innermost lambda to
895 // the outermost lambda, checking if '*this' is ever captured by copy - since
896 // that could change the cv-qualifiers of the '*this' object.
897 // The object referred to by '*this' starts out with the cv-qualifiers of its
898 // member function. We then start with the innermost lambda and iterate
899 // outward checking to see if any lambda performs a by-copy capture of '*this'
900 // - and if so, any nested lambda must respect the 'constness' of that
901 // capturing lamdbda's call operator.
902 //
903
Faisal Vali999f27e2017-05-02 20:56:34 +0000904 // Since the FunctionScopeInfo stack is representative of the lexical
905 // nesting of the lambda expressions during initial parsing (and is the best
906 // place for querying information about captures about lambdas that are
907 // partially processed) and perhaps during instantiation of function templates
908 // that contain lambda expressions that need to be transformed BUT not
909 // necessarily during instantiation of a nested generic lambda's function call
910 // operator (which might even be instantiated at the end of the TU) - at which
911 // time the DeclContext tree is mature enough to query capture information
912 // reliably - we use a two pronged approach to walk through all the lexically
913 // enclosing lambda expressions:
914 //
915 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
916 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
917 // enclosed by the call-operator of the LSI below it on the stack (while
918 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
919 // the stack represents the innermost lambda.
920 //
921 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
922 // represents a lambda's call operator. If it does, we must be instantiating
923 // a generic lambda's call operator (represented by the Current LSI, and
924 // should be the only scenario where an inconsistency between the LSI and the
925 // DeclContext should occur), so climb out the DeclContexts if they
926 // represent lambdas, while querying the corresponding closure types
927 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000928
Faisal Vali999f27e2017-05-02 20:56:34 +0000929 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000930 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000931 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
932 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
933 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000934 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
935 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000936
937 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000938 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000939
Faisal Vali67b04462016-06-11 16:41:54 +0000940 auto C = CurLSI->getCXXThisCapture();
941
942 if (C.isCopyCapture()) {
943 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
944 if (CurLSI->CallOperator->isConst())
945 ClassType.addConst();
946 return ASTCtx.getPointerType(ClassType);
947 }
948 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000949
950 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
951 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000952 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +0000953 assert(CurLSI && "While computing 'this' capture-type for a generic "
954 "lambda, we must have a corresponding LambdaScopeInfo");
955 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
956 "While computing 'this' capture-type for a generic lambda, when we "
957 "run out of enclosing LSI's, yet the enclosing DC is a "
958 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
959 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +0000960 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000961
Faisal Vali67b04462016-06-11 16:41:54 +0000962 auto IsThisCaptured =
963 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
964 IsConst = false;
965 IsByCopy = false;
966 for (auto &&C : Closure->captures()) {
967 if (C.capturesThis()) {
968 if (C.getCaptureKind() == LCK_StarThis)
969 IsByCopy = true;
970 if (Closure->getLambdaCallOperator()->isConst())
971 IsConst = true;
972 return true;
973 }
974 }
975 return false;
976 };
977
978 bool IsByCopyCapture = false;
979 bool IsConstCapture = false;
980 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
981 while (Closure &&
982 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
983 if (IsByCopyCapture) {
984 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
985 if (IsConstCapture)
986 ClassType.addConst();
987 return ASTCtx.getPointerType(ClassType);
988 }
989 Closure = isLambdaCallOperator(Closure->getParent())
990 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
991 : nullptr;
992 }
993 }
994 return ASTCtx.getPointerType(ClassType);
995}
996
Eli Friedman73a04092012-01-07 04:59:52 +0000997QualType Sema::getCurrentThisType() {
998 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000999 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001000
Richard Smith938f40b2011-06-11 17:19:42 +00001001 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1002 if (method && method->isInstance())
1003 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001004 }
Faisal Validc6b5962016-03-21 09:25:37 +00001005
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001006 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001007 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001008
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001009 assert(isa<CXXRecordDecl>(DC) &&
1010 "Trying to get 'this' type from static method?");
1011
1012 // This is a lambda call operator that is being instantiated as a default
1013 // initializer. DC must point to the enclosing class type, so we can recover
1014 // the 'this' type from it.
1015
1016 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1017 // There are no cv-qualifiers for 'this' within default initializers,
1018 // per [expr.prim.general]p4.
1019 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001020 }
Faisal Vali67b04462016-06-11 16:41:54 +00001021
1022 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1023 // might need to be adjusted if the lambda or any of its enclosing lambda's
1024 // captures '*this' by copy.
1025 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1026 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1027 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001028 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001029}
1030
Simon Pilgrim75c26882016-09-30 14:25:09 +00001031Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001032 Decl *ContextDecl,
1033 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001034 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001035 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1036{
1037 if (!Enabled || !ContextDecl)
1038 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001039
1040 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001041 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1042 Record = Template->getTemplatedDecl();
1043 else
1044 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001045
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001046 // We care only for CVR qualifiers here, so cut everything else.
1047 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001048 S.CXXThisTypeOverride
1049 = S.Context.getPointerType(
1050 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001051
Douglas Gregor3024f072012-04-16 07:05:22 +00001052 this->Enabled = true;
1053}
1054
1055
1056Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1057 if (Enabled) {
1058 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1059 }
1060}
1061
Faisal Validc6b5962016-03-21 09:25:37 +00001062static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1063 QualType ThisTy, SourceLocation Loc,
1064 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001065
Faisal Vali67b04462016-06-11 16:41:54 +00001066 QualType AdjustedThisTy = ThisTy;
1067 // The type of the corresponding data member (not a 'this' pointer if 'by
1068 // copy').
1069 QualType CaptureThisFieldTy = ThisTy;
1070 if (ByCopy) {
1071 // If we are capturing the object referred to by '*this' by copy, ignore any
1072 // cv qualifiers inherited from the type of the member function for the type
1073 // of the closure-type's corresponding data member and any use of 'this'.
1074 CaptureThisFieldTy = ThisTy->getPointeeType();
1075 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1076 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1077 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001078
Faisal Vali67b04462016-06-11 16:41:54 +00001079 FieldDecl *Field = FieldDecl::Create(
1080 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1081 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1082 ICIS_NoInit);
1083
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001084 Field->setImplicit(true);
1085 Field->setAccess(AS_private);
1086 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001087 Expr *This =
1088 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001089 if (ByCopy) {
1090 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1091 UO_Deref,
1092 This).get();
1093 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001094 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001095 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1096 InitializationSequence Init(S, Entity, InitKind, StarThis);
1097 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1098 if (ER.isInvalid()) return nullptr;
1099 return ER.get();
1100 }
1101 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001102}
1103
Simon Pilgrim75c26882016-09-30 14:25:09 +00001104bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001105 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1106 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001107 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001108 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001109 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001110
Faisal Validc6b5962016-03-21 09:25:37 +00001111 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001112
Faisal Valia17d19f2013-11-07 05:17:06 +00001113 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001114 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001115
Simon Pilgrim75c26882016-09-30 14:25:09 +00001116 // Check that we can capture the *enclosing object* (referred to by '*this')
1117 // by the capturing-entity/closure (lambda/block/etc) at
1118 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1119
1120 // Note: The *enclosing object* can only be captured by-value by a
1121 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001122 // [*this] { ... }.
1123 // Every other capture of the *enclosing object* results in its by-reference
1124 // capture.
1125
1126 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1127 // stack), we can capture the *enclosing object* only if:
1128 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1129 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001130 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001131 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001132 // -- or, there is some enclosing closure 'E' that has already captured the
1133 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001134 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001135 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001136 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001137
1138
Faisal Validc6b5962016-03-21 09:25:37 +00001139 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001140 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001141 if (CapturingScopeInfo *CSI =
1142 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1143 if (CSI->CXXThisCaptureIndex != 0) {
1144 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001145 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001146 break;
1147 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001148 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1149 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1150 // This context can't implicitly capture 'this'; fail out.
1151 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001152 Diag(Loc, diag::err_this_capture)
1153 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001154 return true;
1155 }
Eli Friedman20139d32012-01-11 02:36:31 +00001156 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001157 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001158 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001159 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001160 (Explicit && idx == MaxFunctionScopesIndex)) {
1161 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1162 // iteration through can be an explicit capture, all enclosing closures,
1163 // if any, must perform implicit captures.
1164
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001165 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001166 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001167 continue;
1168 }
Eli Friedman20139d32012-01-11 02:36:31 +00001169 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001170 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001171 Diag(Loc, diag::err_this_capture)
1172 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001173 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001174 }
Eli Friedman73a04092012-01-07 04:59:52 +00001175 break;
1176 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001177 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001178
1179 // If we got here, then the closure at MaxFunctionScopesIndex on the
1180 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1181 // (including implicit by-reference captures in any enclosing closures).
1182
1183 // In the loop below, respect the ByCopy flag only for the closure requesting
1184 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001185 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001186 // implicitly capturing the *enclosing object* by reference (see loop
1187 // above)).
1188 assert((!ByCopy ||
1189 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1190 "Only a lambda can capture the enclosing object (referred to by "
1191 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001192 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1193 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001194 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001195 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001196 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001197 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001198 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001199
Faisal Validc6b5962016-03-21 09:25:37 +00001200 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1201 // For lambda expressions, build a field and an initializing expression,
1202 // and capture the *enclosing object* by copy only if this is the first
1203 // iteration.
1204 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1205 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001206
Faisal Validc6b5962016-03-21 09:25:37 +00001207 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001208 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001209 ThisExpr =
1210 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1211 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001212
Faisal Validc6b5962016-03-21 09:25:37 +00001213 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001214 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001215 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001216 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001217}
1218
Richard Smith938f40b2011-06-11 17:19:42 +00001219ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001220 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1221 /// is a non-lvalue expression whose value is the address of the object for
1222 /// which the function is called.
1223
Douglas Gregor09deffa2011-10-18 16:47:30 +00001224 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001225 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001226
Eli Friedman73a04092012-01-07 04:59:52 +00001227 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001228 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001229}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001230
Douglas Gregor3024f072012-04-16 07:05:22 +00001231bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1232 // If we're outside the body of a member function, then we'll have a specified
1233 // type for 'this'.
1234 if (CXXThisTypeOverride.isNull())
1235 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001236
Douglas Gregor3024f072012-04-16 07:05:22 +00001237 // Determine whether we're looking into a class that's currently being
1238 // defined.
1239 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1240 return Class && Class->isBeingDefined();
1241}
1242
John McCalldadc5752010-08-24 06:29:42 +00001243ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001244Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001245 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001246 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001247 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001248 if (!TypeRep)
1249 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
John McCall97513962010-01-15 18:39:57 +00001251 TypeSourceInfo *TInfo;
1252 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1253 if (!TInfo)
1254 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001255
Richard Smithb8c414c2016-06-30 20:24:30 +00001256 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1257 // Avoid creating a non-type-dependent expression that contains typos.
1258 // Non-type-dependent expressions are liable to be discarded without
1259 // checking for embedded typos.
1260 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1261 !Result.get()->isTypeDependent())
1262 Result = CorrectDelayedTyposInExpr(Result.get());
1263 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001264}
1265
1266/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1267/// Can be interpreted either as function-style casting ("int(x)")
1268/// or class type construction ("ClassType(x,y,z)")
1269/// or creation of a value-initialized type ("int()").
1270ExprResult
1271Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1272 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001273 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001274 SourceLocation RParenLoc) {
1275 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001276 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001277
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001278 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001279 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1280 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001281 }
1282
Sebastian Redld74dd492012-02-12 18:41:05 +00001283 bool ListInitialization = LParenLoc.isInvalid();
Richard Smith600b5262017-01-26 20:40:47 +00001284 assert((!ListInitialization ||
1285 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1286 "List initialization must have initializer list as expression.");
Sebastian Redld74dd492012-02-12 18:41:05 +00001287 SourceRange FullRange = SourceRange(TyBeginLoc,
1288 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1289
Richard Smith60437622017-02-09 19:17:44 +00001290 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1291 InitializationKind Kind =
1292 Exprs.size()
1293 ? ListInitialization
1294 ? InitializationKind::CreateDirectList(TyBeginLoc)
1295 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1296 RParenLoc)
1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1298
1299 // C++1z [expr.type.conv]p1:
1300 // If the type is a placeholder for a deduced class type, [...perform class
1301 // template argument deduction...]
1302 DeducedType *Deduced = Ty->getContainedDeducedType();
1303 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1304 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1305 Kind, Exprs);
1306 if (Ty.isNull())
1307 return ExprError();
1308 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1309 }
1310
Douglas Gregordd04d332009-01-16 18:33:17 +00001311 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001312 // If the expression list is a parenthesized single expression, the type
1313 // conversion expression is equivalent (in definedness, and if defined in
1314 // meaning) to the corresponding cast expression.
1315 if (Exprs.size() == 1 && !ListInitialization &&
1316 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001317 Expr *Arg = Exprs[0];
Richard Smith60437622017-02-09 19:17:44 +00001318 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001319 }
1320
Richard Smith49a6b6e2017-03-24 01:14:25 +00001321 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001322 QualType ElemTy = Ty;
1323 if (Ty->isArrayType()) {
1324 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001325 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1326 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001327 ElemTy = Context.getBaseElementType(Ty);
1328 }
1329
Richard Smith49a6b6e2017-03-24 01:14:25 +00001330 // There doesn't seem to be an explicit rule against this but sanity demands
1331 // we only construct objects with object types.
1332 if (Ty->isFunctionType())
1333 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1334 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001335
Richard Smith49a6b6e2017-03-24 01:14:25 +00001336 // C++17 [expr.type.conv]p2:
1337 // If the type is cv void and the initializer is (), the expression is a
1338 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001339 if (!Ty->isVoidType() &&
1340 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001341 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001342 return ExprError();
1343
Richard Smith49a6b6e2017-03-24 01:14:25 +00001344 // Otherwise, the expression is a prvalue of the specified type whose
1345 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001346 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1347 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001348
Richard Smith49a6b6e2017-03-24 01:14:25 +00001349 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001350 return Result;
1351
1352 Expr *Inner = Result.get();
1353 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1354 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001355 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1356 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001357 // If we created a CXXTemporaryObjectExpr, that node also represents the
1358 // functional cast. Otherwise, create an explicit cast to represent
1359 // the syntactic form of a functional-style cast that was used here.
1360 //
1361 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1362 // would give a more consistent AST representation than using a
1363 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1364 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001365 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001366 Result = CXXFunctionalCastExpr::Create(
Richard Smith60437622017-02-09 19:17:44 +00001367 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001368 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001369 }
1370
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001371 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001372}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001373
Richard Smithb2f0f052016-10-10 18:54:32 +00001374/// \brief Determine whether the given function is a non-placement
1375/// deallocation function.
1376static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1377 if (FD->isInvalidDecl())
1378 return false;
1379
1380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1381 return Method->isUsualDeallocationFunction();
1382
1383 if (FD->getOverloadedOperator() != OO_Delete &&
1384 FD->getOverloadedOperator() != OO_Array_Delete)
1385 return false;
1386
1387 unsigned UsualParams = 1;
1388
1389 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1390 S.Context.hasSameUnqualifiedType(
1391 FD->getParamDecl(UsualParams)->getType(),
1392 S.Context.getSizeType()))
1393 ++UsualParams;
1394
1395 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1396 S.Context.hasSameUnqualifiedType(
1397 FD->getParamDecl(UsualParams)->getType(),
1398 S.Context.getTypeDeclType(S.getStdAlignValT())))
1399 ++UsualParams;
1400
1401 return UsualParams == FD->getNumParams();
1402}
1403
1404namespace {
1405 struct UsualDeallocFnInfo {
1406 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001407 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001408 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001409 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001410 // A function template declaration is never a usual deallocation function.
1411 if (!FD)
1412 return;
1413 if (FD->getNumParams() == 3)
1414 HasAlignValT = HasSizeT = true;
1415 else if (FD->getNumParams() == 2) {
1416 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1417 HasAlignValT = !HasSizeT;
1418 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001419
1420 // In CUDA, determine how much we'd like / dislike to call this.
1421 if (S.getLangOpts().CUDA)
1422 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1423 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001424 }
1425
1426 operator bool() const { return FD; }
1427
Richard Smithf75dcbe2016-10-11 00:21:10 +00001428 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1429 bool WantAlign) const {
1430 // C++17 [expr.delete]p10:
1431 // If the type has new-extended alignment, a function with a parameter
1432 // of type std::align_val_t is preferred; otherwise a function without
1433 // such a parameter is preferred
1434 if (HasAlignValT != Other.HasAlignValT)
1435 return HasAlignValT == WantAlign;
1436
1437 if (HasSizeT != Other.HasSizeT)
1438 return HasSizeT == WantSize;
1439
1440 // Use CUDA call preference as a tiebreaker.
1441 return CUDAPref > Other.CUDAPref;
1442 }
1443
Richard Smithb2f0f052016-10-10 18:54:32 +00001444 DeclAccessPair Found;
1445 FunctionDecl *FD;
1446 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001447 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001448 };
1449}
1450
1451/// Determine whether a type has new-extended alignment. This may be called when
1452/// the type is incomplete (for a delete-expression with an incomplete pointee
1453/// type), in which case it will conservatively return false if the alignment is
1454/// not known.
1455static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1456 return S.getLangOpts().AlignedAllocation &&
1457 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1458 S.getASTContext().getTargetInfo().getNewAlign();
1459}
1460
1461/// Select the correct "usual" deallocation function to use from a selection of
1462/// deallocation functions (either global or class-scope).
1463static UsualDeallocFnInfo resolveDeallocationOverload(
1464 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1465 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1466 UsualDeallocFnInfo Best;
1467
Richard Smithb2f0f052016-10-10 18:54:32 +00001468 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001469 UsualDeallocFnInfo Info(S, I.getPair());
1470 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1471 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001472 continue;
1473
1474 if (!Best) {
1475 Best = Info;
1476 if (BestFns)
1477 BestFns->push_back(Info);
1478 continue;
1479 }
1480
Richard Smithf75dcbe2016-10-11 00:21:10 +00001481 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001482 continue;
1483
1484 // If more than one preferred function is found, all non-preferred
1485 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001486 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001487 BestFns->clear();
1488
1489 Best = Info;
1490 if (BestFns)
1491 BestFns->push_back(Info);
1492 }
1493
1494 return Best;
1495}
1496
1497/// Determine whether a given type is a class for which 'delete[]' would call
1498/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1499/// we need to store the array size (even if the type is
1500/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001501static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1502 QualType allocType) {
1503 const RecordType *record =
1504 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1505 if (!record) return false;
1506
1507 // Try to find an operator delete[] in class scope.
1508
1509 DeclarationName deleteName =
1510 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1511 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1512 S.LookupQualifiedName(ops, record->getDecl());
1513
1514 // We're just doing this for information.
1515 ops.suppressDiagnostics();
1516
1517 // Very likely: there's no operator delete[].
1518 if (ops.empty()) return false;
1519
1520 // If it's ambiguous, it should be illegal to call operator delete[]
1521 // on this thing, so it doesn't matter if we allocate extra space or not.
1522 if (ops.isAmbiguous()) return false;
1523
Richard Smithb2f0f052016-10-10 18:54:32 +00001524 // C++17 [expr.delete]p10:
1525 // If the deallocation functions have class scope, the one without a
1526 // parameter of type std::size_t is selected.
1527 auto Best = resolveDeallocationOverload(
1528 S, ops, /*WantSize*/false,
1529 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1530 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001531}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001532
Sebastian Redld74dd492012-02-12 18:41:05 +00001533/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001534///
Sebastian Redld74dd492012-02-12 18:41:05 +00001535/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001536/// @code new (memory) int[size][4] @endcode
1537/// or
1538/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001539///
1540/// \param StartLoc The first location of the expression.
1541/// \param UseGlobal True if 'new' was prefixed with '::'.
1542/// \param PlacementLParen Opening paren of the placement arguments.
1543/// \param PlacementArgs Placement new arguments.
1544/// \param PlacementRParen Closing paren of the placement arguments.
1545/// \param TypeIdParens If the type is in parens, the source range.
1546/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001547/// \param Initializer The initializing expression or initializer-list, or null
1548/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001549ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001550Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001551 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001553 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001554 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001555 // If the specified type is an array, unwrap it and save the expression.
1556 if (D.getNumTypeObjects() > 0 &&
1557 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001558 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001559 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001560 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1561 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001562 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001563 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1564 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001565 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001566 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1567 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001568
Sebastian Redl351bb782008-12-02 14:43:59 +00001569 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001570 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001571 }
1572
Douglas Gregor73341c42009-09-11 00:18:58 +00001573 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001574 if (ArraySize) {
1575 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001576 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1577 break;
1578
1579 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1580 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001581 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001582 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001583 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1584 // shall be a converted constant expression (5.19) of type std::size_t
1585 // and shall evaluate to a strictly positive value.
1586 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1587 assert(IntWidth && "Builtin type of size 0?");
1588 llvm::APSInt Value(IntWidth);
1589 Array.NumElts
1590 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1591 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001592 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001593 } else {
1594 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001595 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001596 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001597 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001598 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001599 if (!Array.NumElts)
1600 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001601 }
1602 }
1603 }
1604 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001605
Craig Topperc3ec1492014-05-26 06:22:03 +00001606 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001607 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001608 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001609 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001610
Sebastian Redl6047f072012-02-16 12:22:20 +00001611 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001612 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001613 DirectInitRange = List->getSourceRange();
1614
David Blaikie7b97aef2012-11-07 00:12:38 +00001615 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001616 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001617 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001618 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001619 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001620 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001621 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001622 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001623 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001624 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001625}
1626
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001627static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1628 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001629 if (!Init)
1630 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001631 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1632 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001633 if (isa<ImplicitValueInitExpr>(Init))
1634 return true;
1635 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1636 return !CCE->isListInitialization() &&
1637 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001638 else if (Style == CXXNewExpr::ListInit) {
1639 assert(isa<InitListExpr>(Init) &&
1640 "Shouldn't create list CXXConstructExprs for arrays.");
1641 return true;
1642 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001643 return false;
1644}
1645
John McCalldadc5752010-08-24 06:29:42 +00001646ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001647Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001648 SourceLocation PlacementLParen,
1649 MultiExprArg PlacementArgs,
1650 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001651 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001652 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001653 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001654 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001655 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001656 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001657 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001658 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001659
Sebastian Redl6047f072012-02-16 12:22:20 +00001660 CXXNewExpr::InitializationStyle initStyle;
1661 if (DirectInitRange.isValid()) {
1662 assert(Initializer && "Have parens but no initializer.");
1663 initStyle = CXXNewExpr::CallInit;
1664 } else if (Initializer && isa<InitListExpr>(Initializer))
1665 initStyle = CXXNewExpr::ListInit;
1666 else {
1667 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1668 isa<CXXConstructExpr>(Initializer)) &&
1669 "Initializer expression that cannot have been implicitly created.");
1670 initStyle = CXXNewExpr::NoInit;
1671 }
1672
1673 Expr **Inits = &Initializer;
1674 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001675 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1676 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1677 Inits = List->getExprs();
1678 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001679 }
1680
Richard Smith60437622017-02-09 19:17:44 +00001681 // C++11 [expr.new]p15:
1682 // A new-expression that creates an object of type T initializes that
1683 // object as follows:
1684 InitializationKind Kind
1685 // - If the new-initializer is omitted, the object is default-
1686 // initialized (8.5); if no initialization is performed,
1687 // the object has indeterminate value
1688 = initStyle == CXXNewExpr::NoInit
1689 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1690 // - Otherwise, the new-initializer is interpreted according to the
1691 // initialization rules of 8.5 for direct-initialization.
1692 : initStyle == CXXNewExpr::ListInit
1693 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1694 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1695 DirectInitRange.getBegin(),
1696 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001697
Richard Smith60437622017-02-09 19:17:44 +00001698 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1699 auto *Deduced = AllocType->getContainedDeducedType();
1700 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1701 if (ArraySize)
1702 return ExprError(Diag(ArraySize->getExprLoc(),
1703 diag::err_deduced_class_template_compound_type)
1704 << /*array*/ 2 << ArraySize->getSourceRange());
1705
1706 InitializedEntity Entity
1707 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1708 AllocType = DeduceTemplateSpecializationFromInitializer(
1709 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1710 if (AllocType.isNull())
1711 return ExprError();
1712 } else if (Deduced) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001713 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001714 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1715 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001716 if (initStyle == CXXNewExpr::ListInit ||
1717 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001718 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001719 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001720 << AllocType << TypeRange);
1721 if (NumInits > 1) {
1722 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001723 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001724 diag::err_auto_new_ctor_multiple_expressions)
1725 << AllocType << TypeRange);
1726 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001727 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001728 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001729 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001730 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001731 << AllocType << Deduce->getType()
1732 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001733 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001734 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001735 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001736 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001737
Douglas Gregorcda95f42010-05-16 16:01:03 +00001738 // Per C++0x [expr.new]p5, the type being constructed may be a
1739 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001740 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001741 if (const ConstantArrayType *Array
1742 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001743 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1744 Context.getSizeType(),
1745 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001746 AllocType = Array->getElementType();
1747 }
1748 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001749
Douglas Gregor3999e152010-10-06 16:00:31 +00001750 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1751 return ExprError();
1752
Craig Topperc3ec1492014-05-26 06:22:03 +00001753 if (initStyle == CXXNewExpr::ListInit &&
1754 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001755 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1756 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001757 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001758 }
1759
Simon Pilgrim75c26882016-09-30 14:25:09 +00001760 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001761 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001762 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1763 AllocType->isObjCLifetimeType()) {
1764 AllocType = Context.getLifetimeQualifiedType(AllocType,
1765 AllocType->getObjCARCImplicitLifetime());
1766 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001767
John McCall31168b02011-06-15 23:02:42 +00001768 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001769
John McCall5e77d762013-04-16 07:28:30 +00001770 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1771 ExprResult result = CheckPlaceholderExpr(ArraySize);
1772 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001773 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001774 }
Richard Smith8dd34252012-02-04 07:07:42 +00001775 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1776 // integral or enumeration type with a non-negative value."
1777 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1778 // enumeration type, or a class type for which a single non-explicit
1779 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001780 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001781 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001782 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001783 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001784 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001785 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001786 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1787
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001788 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1789 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001790
Simon Pilgrim75c26882016-09-30 14:25:09 +00001791 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001792 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001793 // Diagnose the compatibility of this conversion.
1794 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1795 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001796 } else {
1797 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1798 protected:
1799 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001800
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001801 public:
1802 SizeConvertDiagnoser(Expr *ArraySize)
1803 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1804 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001805
1806 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1807 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001808 return S.Diag(Loc, diag::err_array_size_not_integral)
1809 << S.getLangOpts().CPlusPlus11 << T;
1810 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001811
1812 SemaDiagnosticBuilder diagnoseIncomplete(
1813 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001814 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1815 << T << ArraySize->getSourceRange();
1816 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001817
1818 SemaDiagnosticBuilder diagnoseExplicitConv(
1819 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001820 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1821 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001822
1823 SemaDiagnosticBuilder noteExplicitConv(
1824 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001825 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1826 << ConvTy->isEnumeralType() << ConvTy;
1827 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001828
1829 SemaDiagnosticBuilder diagnoseAmbiguous(
1830 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001831 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1832 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001833
1834 SemaDiagnosticBuilder noteAmbiguous(
1835 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001836 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1837 << ConvTy->isEnumeralType() << ConvTy;
1838 }
Richard Smithccc11812013-05-21 19:05:48 +00001839
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001840 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1841 QualType T,
1842 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001843 return S.Diag(Loc,
1844 S.getLangOpts().CPlusPlus11
1845 ? diag::warn_cxx98_compat_array_size_conversion
1846 : diag::ext_array_size_conversion)
1847 << T << ConvTy->isEnumeralType() << ConvTy;
1848 }
1849 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001850
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001851 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1852 SizeDiagnoser);
1853 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001854 if (ConvertedSize.isInvalid())
1855 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001857 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001858 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001859
Douglas Gregor0bf31402010-10-08 23:50:27 +00001860 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001861 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001863 // C++98 [expr.new]p7:
1864 // The expression in a direct-new-declarator shall have integral type
1865 // with a non-negative value.
1866 //
Richard Smith0511d232016-10-05 22:41:02 +00001867 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1868 // per CWG1464. Otherwise, if it's not a constant, we must have an
1869 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001870 if (!ArraySize->isValueDependent()) {
1871 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001872 // We've already performed any required implicit conversion to integer or
1873 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001874 // FIXME: Per CWG1464, we are required to check the value prior to
1875 // converting to size_t. This will never find a negative array size in
1876 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001877 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001878 if (Value.isSigned() && Value.isNegative()) {
1879 return ExprError(Diag(ArraySize->getLocStart(),
1880 diag::err_typecheck_negative_array_size)
1881 << ArraySize->getSourceRange());
1882 }
1883
1884 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001885 unsigned ActiveSizeBits =
1886 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001887 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1888 return ExprError(Diag(ArraySize->getLocStart(),
1889 diag::err_array_too_large)
1890 << Value.toString(10)
1891 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001892 }
Richard Smith0511d232016-10-05 22:41:02 +00001893
1894 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001895 } else if (TypeIdParens.isValid()) {
1896 // Can't have dynamic array size when the type-id is in parentheses.
1897 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1898 << ArraySize->getSourceRange()
1899 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1900 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
Douglas Gregorf2753b32010-07-13 15:54:32 +00001902 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001903 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
John McCall036f2f62011-05-15 07:14:44 +00001906 // Note that we do *not* convert the argument in any way. It can
1907 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001908 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001909
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 FunctionDecl *OperatorNew = nullptr;
1911 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001912 unsigned Alignment =
1913 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1914 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1915 bool PassAlignment = getLangOpts().AlignedAllocation &&
1916 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001918 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001919 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001920 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001921 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001922 UseGlobal, AllocType, ArraySize, PassAlignment,
1923 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001924 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001925
1926 // If this is an array allocation, compute whether the usual array
1927 // deallocation function for the type has a size_t parameter.
1928 bool UsualArrayDeleteWantsSize = false;
1929 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001930 UsualArrayDeleteWantsSize =
1931 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001932
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001933 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001934 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001936 OperatorNew->getType()->getAs<FunctionProtoType>();
1937 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1938 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Richard Smithd6f9e732014-05-13 19:56:21 +00001940 // We've already converted the placement args, just fill in any default
1941 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001942 // argument. Skip the second parameter too if we're passing in the
1943 // alignment; we've already filled it in.
1944 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1945 PassAlignment ? 2 : 1, PlacementArgs,
1946 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001947 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001949 if (!AllPlaceArgs.empty())
1950 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001951
Richard Smithd6f9e732014-05-13 19:56:21 +00001952 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001953 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001954
1955 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
Richard Smithb2f0f052016-10-10 18:54:32 +00001957 // Warn if the type is over-aligned and is being allocated by (unaligned)
1958 // global operator new.
1959 if (PlacementArgs.empty() && !PassAlignment &&
1960 (OperatorNew->isImplicit() ||
1961 (OperatorNew->getLocStart().isValid() &&
1962 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1963 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001964 Diag(StartLoc, diag::warn_overaligned_type)
1965 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001966 << unsigned(Alignment / Context.getCharWidth())
1967 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001968 }
1969 }
1970
Sebastian Redl6047f072012-02-16 12:22:20 +00001971 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001972 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1973 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001974 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1975 SourceRange InitRange(Inits[0]->getLocStart(),
1976 Inits[NumInits - 1]->getLocEnd());
1977 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1978 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001979 }
1980
Richard Smithdd2ca572012-11-26 08:32:48 +00001981 // If we can perform the initialization, and we've not already done so,
1982 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001983 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001984 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001985 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001986 // The type we initialize is the complete type, including the array bound.
1987 QualType InitType;
1988 if (KnownArraySize)
1989 InitType = Context.getConstantArrayType(
1990 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1991 *KnownArraySize),
1992 ArrayType::Normal, 0);
1993 else if (ArraySize)
1994 InitType =
1995 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1996 else
1997 InitType = AllocType;
1998
Douglas Gregor85dabae2009-12-16 01:38:02 +00001999 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002000 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002001 InitializationSequence InitSeq(*this, Entity, Kind,
2002 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002004 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002005 if (FullInit.isInvalid())
2006 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Sebastian Redl6047f072012-02-16 12:22:20 +00002008 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2009 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002010 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002011 if (CXXBindTemporaryExpr *Binder =
2012 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002013 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002015 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
Douglas Gregor6642ca22010-02-26 05:06:18 +00002018 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002019 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002020 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2021 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002022 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002023 }
2024 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002025 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2026 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002027 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002028 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002029
John McCall928a2572011-07-13 20:12:57 +00002030 // C++0x [expr.new]p17:
2031 // If the new expression creates an array of objects of class type,
2032 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002033 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2034 if (ArraySize && !BaseAllocType->isDependentType()) {
2035 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2036 if (CXXDestructorDecl *dtor = LookupDestructor(
2037 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2038 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002039 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002040 PDiag(diag::err_access_dtor)
2041 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002042 if (DiagnoseUseOfDecl(dtor, StartLoc))
2043 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002044 }
John McCall928a2572011-07-13 20:12:57 +00002045 }
2046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002048 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002049 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002050 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2051 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2052 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002053}
2054
Sebastian Redl6047f072012-02-16 12:22:20 +00002055/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002056/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002057bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002058 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002059 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2060 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002061 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002062 return Diag(Loc, diag::err_bad_new_type)
2063 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002064 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002065 return Diag(Loc, diag::err_bad_new_type)
2066 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002067 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002068 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002069 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002070 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002071 diag::err_allocation_of_abstract_type))
2072 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002073 else if (AllocType->isVariablyModifiedType())
2074 return Diag(Loc, diag::err_variably_modified_new_type)
2075 << AllocType;
Yaxun Liub34ec822017-04-11 17:24:23 +00002076 else if (AllocType.getAddressSpace())
Douglas Gregor39d1a092011-04-15 19:46:20 +00002077 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002078 << AllocType.getUnqualifiedType()
2079 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002080 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002081 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2082 QualType BaseAllocType = Context.getBaseElementType(AT);
2083 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2084 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002085 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002086 << BaseAllocType;
2087 }
2088 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002089
Sebastian Redlbd150f42008-11-21 19:14:01 +00002090 return false;
2091}
2092
Richard Smithb2f0f052016-10-10 18:54:32 +00002093static bool
2094resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2095 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2096 FunctionDecl *&Operator,
2097 OverloadCandidateSet *AlignedCandidates = nullptr,
2098 Expr *AlignArg = nullptr) {
2099 OverloadCandidateSet Candidates(R.getNameLoc(),
2100 OverloadCandidateSet::CSK_Normal);
2101 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2102 Alloc != AllocEnd; ++Alloc) {
2103 // Even member operator new/delete are implicitly treated as
2104 // static, so don't use AddMemberCandidate.
2105 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2106
2107 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2108 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2109 /*ExplicitTemplateArgs=*/nullptr, Args,
2110 Candidates,
2111 /*SuppressUserConversions=*/false);
2112 continue;
2113 }
2114
2115 FunctionDecl *Fn = cast<FunctionDecl>(D);
2116 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2117 /*SuppressUserConversions=*/false);
2118 }
2119
2120 // Do the resolution.
2121 OverloadCandidateSet::iterator Best;
2122 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2123 case OR_Success: {
2124 // Got one!
2125 FunctionDecl *FnDecl = Best->Function;
2126 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2127 Best->FoundDecl) == Sema::AR_inaccessible)
2128 return true;
2129
2130 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002131 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002132 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002133
Richard Smithb2f0f052016-10-10 18:54:32 +00002134 case OR_No_Viable_Function:
2135 // C++17 [expr.new]p13:
2136 // If no matching function is found and the allocated object type has
2137 // new-extended alignment, the alignment argument is removed from the
2138 // argument list, and overload resolution is performed again.
2139 if (PassAlignment) {
2140 PassAlignment = false;
2141 AlignArg = Args[1];
2142 Args.erase(Args.begin() + 1);
2143 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2144 Operator, &Candidates, AlignArg);
2145 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002146
Richard Smithb2f0f052016-10-10 18:54:32 +00002147 // MSVC will fall back on trying to find a matching global operator new
2148 // if operator new[] cannot be found. Also, MSVC will leak by not
2149 // generating a call to operator delete or operator delete[], but we
2150 // will not replicate that bug.
2151 // FIXME: Find out how this interacts with the std::align_val_t fallback
2152 // once MSVC implements it.
2153 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2154 S.Context.getLangOpts().MSVCCompat) {
2155 R.clear();
2156 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2157 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2158 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2159 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2160 Operator, nullptr);
2161 }
Richard Smith1cdec012013-09-29 04:40:38 +00002162
Richard Smithb2f0f052016-10-10 18:54:32 +00002163 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2164 << R.getLookupName() << Range;
2165
2166 // If we have aligned candidates, only note the align_val_t candidates
2167 // from AlignedCandidates and the non-align_val_t candidates from
2168 // Candidates.
2169 if (AlignedCandidates) {
2170 auto IsAligned = [](OverloadCandidate &C) {
2171 return C.Function->getNumParams() > 1 &&
2172 C.Function->getParamDecl(1)->getType()->isAlignValT();
2173 };
2174 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2175
2176 // This was an overaligned allocation, so list the aligned candidates
2177 // first.
2178 Args.insert(Args.begin() + 1, AlignArg);
2179 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2180 R.getNameLoc(), IsAligned);
2181 Args.erase(Args.begin() + 1);
2182 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2183 IsUnaligned);
2184 } else {
2185 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2186 }
Richard Smith1cdec012013-09-29 04:40:38 +00002187 return true;
2188
Richard Smithb2f0f052016-10-10 18:54:32 +00002189 case OR_Ambiguous:
2190 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2191 << R.getLookupName() << Range;
2192 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2193 return true;
2194
2195 case OR_Deleted: {
2196 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2197 << Best->Function->isDeleted()
2198 << R.getLookupName()
2199 << S.getDeletedOrUnavailableSuffix(Best->Function)
2200 << Range;
2201 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2202 return true;
2203 }
2204 }
2205 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002206}
2207
Richard Smithb2f0f052016-10-10 18:54:32 +00002208
Sebastian Redlfaf68082008-12-03 20:26:15 +00002209/// FindAllocationFunctions - Finds the overloads of operator new and delete
2210/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002211bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2212 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002213 bool IsArray, bool &PassAlignment,
2214 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002215 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002216 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002217 // --- Choosing an allocation function ---
2218 // C++ 5.3.4p8 - 14 & 18
2219 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2220 // in the scope of the allocated class.
2221 // 2) If an array size is given, look for operator new[], else look for
2222 // operator new.
2223 // 3) The first argument is always size_t. Append the arguments from the
2224 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002225
Richard Smithb2f0f052016-10-10 18:54:32 +00002226 SmallVector<Expr*, 8> AllocArgs;
2227 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2228
2229 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002230 // FIXME: Should the Sema create the expression and embed it in the syntax
2231 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002232 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002233 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002234 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002235 Context.getSizeType(),
2236 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002237 AllocArgs.push_back(&Size);
2238
2239 QualType AlignValT = Context.VoidTy;
2240 if (PassAlignment) {
2241 DeclareGlobalNewDelete();
2242 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2243 }
2244 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2245 if (PassAlignment)
2246 AllocArgs.push_back(&Align);
2247
2248 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002249
Douglas Gregor6642ca22010-02-26 05:06:18 +00002250 // C++ [expr.new]p8:
2251 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002252 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002253 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002254 // type, the allocation function's name is operator new[] and the
2255 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002256 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002257 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002258
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002259 QualType AllocElemType = Context.getBaseElementType(AllocType);
2260
Richard Smithb2f0f052016-10-10 18:54:32 +00002261 // Find the allocation function.
2262 {
2263 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2264
2265 // C++1z [expr.new]p9:
2266 // If the new-expression begins with a unary :: operator, the allocation
2267 // function's name is looked up in the global scope. Otherwise, if the
2268 // allocated type is a class type T or array thereof, the allocation
2269 // function's name is looked up in the scope of T.
2270 if (AllocElemType->isRecordType() && !UseGlobal)
2271 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2272
2273 // We can see ambiguity here if the allocation function is found in
2274 // multiple base classes.
2275 if (R.isAmbiguous())
2276 return true;
2277
2278 // If this lookup fails to find the name, or if the allocated type is not
2279 // a class type, the allocation function's name is looked up in the
2280 // global scope.
2281 if (R.empty())
2282 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2283
2284 assert(!R.empty() && "implicitly declared allocation functions not found");
2285 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2286
2287 // We do our own custom access checks below.
2288 R.suppressDiagnostics();
2289
2290 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2291 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002292 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002293 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002294
Richard Smithb2f0f052016-10-10 18:54:32 +00002295 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002296 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002297 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002298 return false;
2299 }
2300
Richard Smithb2f0f052016-10-10 18:54:32 +00002301 // Note, the name of OperatorNew might have been changed from array to
2302 // non-array by resolveAllocationOverload.
2303 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2304 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2305 ? OO_Array_Delete
2306 : OO_Delete);
2307
Douglas Gregor6642ca22010-02-26 05:06:18 +00002308 // C++ [expr.new]p19:
2309 //
2310 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002311 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002312 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002313 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002314 // the scope of T. If this lookup fails to find the name, or if
2315 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002316 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002317 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002318 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002319 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002320 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002321 LookupQualifiedName(FoundDelete, RD);
2322 }
John McCallfb6f5262010-03-18 08:19:33 +00002323 if (FoundDelete.isAmbiguous())
2324 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002325
Richard Smithb2f0f052016-10-10 18:54:32 +00002326 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002327 if (FoundDelete.empty()) {
2328 DeclareGlobalNewDelete();
2329 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2330 }
2331
2332 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002333
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002334 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002335
John McCalld3be2c82010-09-14 21:34:24 +00002336 // Whether we're looking for a placement operator delete is dictated
2337 // by whether we selected a placement operator new, not by whether
2338 // we had explicit placement arguments. This matters for things like
2339 // struct A { void *operator new(size_t, int = 0); ... };
2340 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002341 //
2342 // We don't have any definition for what a "placement allocation function"
2343 // is, but we assume it's any allocation function whose
2344 // parameter-declaration-clause is anything other than (size_t).
2345 //
2346 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2347 // This affects whether an exception from the constructor of an overaligned
2348 // type uses the sized or non-sized form of aligned operator delete.
2349 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2350 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002351
2352 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002353 // C++ [expr.new]p20:
2354 // A declaration of a placement deallocation function matches the
2355 // declaration of a placement allocation function if it has the
2356 // same number of parameters and, after parameter transformations
2357 // (8.3.5), all parameter types except the first are
2358 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002359 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002360 // To perform this comparison, we compute the function type that
2361 // the deallocation function should have, and use that type both
2362 // for template argument deduction and for comparison purposes.
2363 QualType ExpectedFunctionType;
2364 {
2365 const FunctionProtoType *Proto
2366 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002367
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002368 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002370 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2371 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002372
John McCalldb40c7f2010-12-14 08:05:40 +00002373 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002374 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002375 EPI.Variadic = Proto->isVariadic();
2376
Douglas Gregor6642ca22010-02-26 05:06:18 +00002377 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002378 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002379 }
2380
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002381 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002382 DEnd = FoundDelete.end();
2383 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002384 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002385 if (FunctionTemplateDecl *FnTmpl =
2386 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002387 // Perform template argument deduction to try to match the
2388 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002389 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002390 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2391 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002392 continue;
2393 } else
2394 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2395
Richard Smithbaa47832016-12-01 02:11:49 +00002396 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2397 ExpectedFunctionType,
2398 /*AdjustExcpetionSpec*/true),
2399 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002400 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002401 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002402
Richard Smithb2f0f052016-10-10 18:54:32 +00002403 if (getLangOpts().CUDA)
2404 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2405 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002406 // C++1y [expr.new]p22:
2407 // For a non-placement allocation function, the normal deallocation
2408 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002409 //
2410 // Per [expr.delete]p10, this lookup prefers a member operator delete
2411 // without a size_t argument, but prefers a non-member operator delete
2412 // with a size_t where possible (which it always is in this case).
2413 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2414 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2415 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2416 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2417 &BestDeallocFns);
2418 if (Selected)
2419 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2420 else {
2421 // If we failed to select an operator, all remaining functions are viable
2422 // but ambiguous.
2423 for (auto Fn : BestDeallocFns)
2424 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002425 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002426 }
2427
2428 // C++ [expr.new]p20:
2429 // [...] If the lookup finds a single matching deallocation
2430 // function, that function will be called; otherwise, no
2431 // deallocation function will be called.
2432 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002433 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002434
Richard Smithb2f0f052016-10-10 18:54:32 +00002435 // C++1z [expr.new]p23:
2436 // If the lookup finds a usual deallocation function (3.7.4.2)
2437 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002438 // as a placement deallocation function, would have been
2439 // selected as a match for the allocation function, the program
2440 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002441 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002442 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002443 UsualDeallocFnInfo Info(*this,
2444 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002445 // Core issue, per mail to core reflector, 2016-10-09:
2446 // If this is a member operator delete, and there is a corresponding
2447 // non-sized member operator delete, this isn't /really/ a sized
2448 // deallocation function, it just happens to have a size_t parameter.
2449 bool IsSizedDelete = Info.HasSizeT;
2450 if (IsSizedDelete && !FoundGlobalDelete) {
2451 auto NonSizedDelete =
2452 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2453 /*WantAlign*/Info.HasAlignValT);
2454 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2455 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2456 IsSizedDelete = false;
2457 }
2458
2459 if (IsSizedDelete) {
2460 SourceRange R = PlaceArgs.empty()
2461 ? SourceRange()
2462 : SourceRange(PlaceArgs.front()->getLocStart(),
2463 PlaceArgs.back()->getLocEnd());
2464 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2465 if (!OperatorDelete->isImplicit())
2466 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2467 << DeleteName;
2468 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002469 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002470
2471 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2472 Matches[0].first);
2473 } else if (!Matches.empty()) {
2474 // We found multiple suitable operators. Per [expr.new]p20, that means we
2475 // call no 'operator delete' function, but we should at least warn the user.
2476 // FIXME: Suppress this warning if the construction cannot throw.
2477 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2478 << DeleteName << AllocElemType;
2479
2480 for (auto &Match : Matches)
2481 Diag(Match.second->getLocation(),
2482 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002483 }
2484
Sebastian Redlfaf68082008-12-03 20:26:15 +00002485 return false;
2486}
2487
2488/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2489/// delete. These are:
2490/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002491/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002492/// void* operator new(std::size_t) throw(std::bad_alloc);
2493/// void* operator new[](std::size_t) throw(std::bad_alloc);
2494/// void operator delete(void *) throw();
2495/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002496/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002497/// void* operator new(std::size_t);
2498/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002499/// void operator delete(void *) noexcept;
2500/// void operator delete[](void *) noexcept;
2501/// // C++1y:
2502/// void* operator new(std::size_t);
2503/// void* operator new[](std::size_t);
2504/// void operator delete(void *) noexcept;
2505/// void operator delete[](void *) noexcept;
2506/// void operator delete(void *, std::size_t) noexcept;
2507/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002508/// @endcode
2509/// Note that the placement and nothrow forms of new are *not* implicitly
2510/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002511void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002512 if (GlobalNewDeleteDeclared)
2513 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514
Douglas Gregor87f54062009-09-15 22:30:29 +00002515 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516 // [...] The following allocation and deallocation functions (18.4) are
2517 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002518 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002519 //
Sebastian Redl37588092011-03-14 18:08:30 +00002520 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002521 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002522 // void* operator new[](std::size_t) throw(std::bad_alloc);
2523 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002524 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002525 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002526 // void* operator new(std::size_t);
2527 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002528 // void operator delete(void*) noexcept;
2529 // void operator delete[](void*) noexcept;
2530 // C++1y:
2531 // void* operator new(std::size_t);
2532 // void* operator new[](std::size_t);
2533 // void operator delete(void*) noexcept;
2534 // void operator delete[](void*) noexcept;
2535 // void operator delete(void*, std::size_t) noexcept;
2536 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002537 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002538 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002539 // new, operator new[], operator delete, operator delete[].
2540 //
2541 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2542 // "std" or "bad_alloc" as necessary to form the exception specification.
2543 // However, we do not make these implicit declarations visible to name
2544 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002545 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002546 // The "std::bad_alloc" class has not yet been declared, so build it
2547 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2549 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002550 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002552 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002553 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002554 }
Richard Smith59139022016-09-30 22:41:36 +00002555 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002556 // The "std::align_val_t" enum class has not yet been declared, so build it
2557 // implicitly.
2558 auto *AlignValT = EnumDecl::Create(
2559 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2560 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2561 AlignValT->setIntegerType(Context.getSizeType());
2562 AlignValT->setPromotionType(Context.getSizeType());
2563 AlignValT->setImplicit(true);
2564 StdAlignValT = AlignValT;
2565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566
Sebastian Redlfaf68082008-12-03 20:26:15 +00002567 GlobalNewDeleteDeclared = true;
2568
2569 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2570 QualType SizeT = Context.getSizeType();
2571
Richard Smith96269c52016-09-29 22:49:46 +00002572 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2573 QualType Return, QualType Param) {
2574 llvm::SmallVector<QualType, 3> Params;
2575 Params.push_back(Param);
2576
2577 // Create up to four variants of the function (sized/aligned).
2578 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2579 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002580 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002581
2582 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2583 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2584 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002585 if (Sized)
2586 Params.push_back(SizeT);
2587
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002588 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002589 if (Aligned)
2590 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2591
2592 DeclareGlobalAllocationFunction(
2593 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2594
2595 if (Aligned)
2596 Params.pop_back();
2597 }
2598 }
2599 };
2600
2601 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2602 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2603 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2604 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002605}
2606
2607/// DeclareGlobalAllocationFunction - Declares a single implicit global
2608/// allocation function if it doesn't already exist.
2609void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002610 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002611 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002612 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2613
2614 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002615 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2616 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2617 Alloc != AllocEnd; ++Alloc) {
2618 // Only look at non-template functions, as it is the predefined,
2619 // non-templated allocation function we are trying to declare here.
2620 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002621 if (Func->getNumParams() == Params.size()) {
2622 llvm::SmallVector<QualType, 3> FuncParams;
2623 for (auto *P : Func->parameters())
2624 FuncParams.push_back(
2625 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2626 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002627 // Make the function visible to name lookup, even if we found it in
2628 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002629 // allocation function, or is suppressing that function.
2630 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002631 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002632 }
Chandler Carruth93538422010-02-03 11:02:14 +00002633 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002634 }
2635 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002636
Richard Smithc015bc22014-02-07 22:39:53 +00002637 FunctionProtoType::ExtProtoInfo EPI;
2638
Richard Smithf8b417c2014-02-08 00:42:45 +00002639 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002640 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002641 = (Name.getCXXOverloadedOperator() == OO_New ||
2642 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002643 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002644 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002645 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002646 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002647 EPI.ExceptionSpec.Type = EST_Dynamic;
2648 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002649 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002650 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002651 EPI.ExceptionSpec =
2652 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654
Artem Belevich07db5cf2016-10-21 20:34:05 +00002655 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2656 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2657 FunctionDecl *Alloc = FunctionDecl::Create(
2658 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2659 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2660 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002661 // Global allocation functions should always be visible.
2662 Alloc->setHidden(false);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002663
Artem Belevich07db5cf2016-10-21 20:34:05 +00002664 // Implicit sized deallocation functions always have default visibility.
2665 Alloc->addAttr(
2666 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002667
Artem Belevich07db5cf2016-10-21 20:34:05 +00002668 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2669 for (QualType T : Params) {
2670 ParamDecls.push_back(ParmVarDecl::Create(
2671 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2672 /*TInfo=*/nullptr, SC_None, nullptr));
2673 ParamDecls.back()->setImplicit();
2674 }
2675 Alloc->setParams(ParamDecls);
2676 if (ExtraAttr)
2677 Alloc->addAttr(ExtraAttr);
2678 Context.getTranslationUnitDecl()->addDecl(Alloc);
2679 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2680 };
2681
2682 if (!LangOpts.CUDA)
2683 CreateAllocationFunctionDecl(nullptr);
2684 else {
2685 // Host and device get their own declaration so each can be
2686 // defined or re-declared independently.
2687 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2688 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002689 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002690}
2691
Richard Smith1cdec012013-09-29 04:40:38 +00002692FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2693 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002694 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002695 DeclarationName Name) {
2696 DeclareGlobalNewDelete();
2697
2698 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2699 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2700
Richard Smithb2f0f052016-10-10 18:54:32 +00002701 // FIXME: It's possible for this to result in ambiguity, through a
2702 // user-declared variadic operator delete or the enable_if attribute. We
2703 // should probably not consider those cases to be usual deallocation
2704 // functions. But for now we just make an arbitrary choice in that case.
2705 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2706 Overaligned);
2707 assert(Result.FD && "operator delete missing from global scope?");
2708 return Result.FD;
2709}
Richard Smith1cdec012013-09-29 04:40:38 +00002710
Richard Smithb2f0f052016-10-10 18:54:32 +00002711FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2712 CXXRecordDecl *RD) {
2713 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002714
Richard Smithb2f0f052016-10-10 18:54:32 +00002715 FunctionDecl *OperatorDelete = nullptr;
2716 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2717 return nullptr;
2718 if (OperatorDelete)
2719 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002720
Richard Smithb2f0f052016-10-10 18:54:32 +00002721 // If there's no class-specific operator delete, look up the global
2722 // non-array delete.
2723 return FindUsualDeallocationFunction(
2724 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2725 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002726}
2727
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002728bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2729 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002730 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002731 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002732 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002733 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002734
John McCall27b18f82009-11-17 02:14:36 +00002735 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002736 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002737
Chandler Carruthb6f99172010-06-28 00:30:51 +00002738 Found.suppressDiagnostics();
2739
Richard Smithb2f0f052016-10-10 18:54:32 +00002740 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002741
Richard Smithb2f0f052016-10-10 18:54:32 +00002742 // C++17 [expr.delete]p10:
2743 // If the deallocation functions have class scope, the one without a
2744 // parameter of type std::size_t is selected.
2745 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2746 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2747 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002748
Richard Smithb2f0f052016-10-10 18:54:32 +00002749 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002750 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002751 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002752
Richard Smithb2f0f052016-10-10 18:54:32 +00002753 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002754 if (Operator->isDeleted()) {
2755 if (Diagnose) {
2756 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002757 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002758 }
2759 return true;
2760 }
2761
Richard Smith921bd202012-02-26 09:11:52 +00002762 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002763 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002764 return true;
2765
John McCall66a87592010-08-04 00:31:26 +00002766 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002767 }
John McCall66a87592010-08-04 00:31:26 +00002768
Richard Smithb2f0f052016-10-10 18:54:32 +00002769 // We found multiple suitable operators; complain about the ambiguity.
2770 // FIXME: The standard doesn't say to do this; it appears that the intent
2771 // is that this should never happen.
2772 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002773 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002774 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2775 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002776 for (auto &Match : Matches)
2777 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002778 }
John McCall66a87592010-08-04 00:31:26 +00002779 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002780 }
2781
2782 // We did find operator delete/operator delete[] declarations, but
2783 // none of them were suitable.
2784 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002785 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002786 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2787 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002788
Richard Smithb2f0f052016-10-10 18:54:32 +00002789 for (NamedDecl *D : Found)
2790 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002791 diag::note_member_declared_here) << Name;
2792 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002793 return true;
2794 }
2795
Craig Topperc3ec1492014-05-26 06:22:03 +00002796 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002797 return false;
2798}
2799
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002800namespace {
2801/// \brief Checks whether delete-expression, and new-expression used for
2802/// initializing deletee have the same array form.
2803class MismatchingNewDeleteDetector {
2804public:
2805 enum MismatchResult {
2806 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2807 NoMismatch,
2808 /// Indicates that variable is initialized with mismatching form of \a new.
2809 VarInitMismatches,
2810 /// Indicates that member is initialized with mismatching form of \a new.
2811 MemberInitMismatches,
2812 /// Indicates that 1 or more constructors' definitions could not been
2813 /// analyzed, and they will be checked again at the end of translation unit.
2814 AnalyzeLater
2815 };
2816
2817 /// \param EndOfTU True, if this is the final analysis at the end of
2818 /// translation unit. False, if this is the initial analysis at the point
2819 /// delete-expression was encountered.
2820 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002821 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002822 HasUndefinedConstructors(false) {}
2823
2824 /// \brief Checks whether pointee of a delete-expression is initialized with
2825 /// matching form of new-expression.
2826 ///
2827 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2828 /// point where delete-expression is encountered, then a warning will be
2829 /// issued immediately. If return value is \c AnalyzeLater at the point where
2830 /// delete-expression is seen, then member will be analyzed at the end of
2831 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2832 /// couldn't be analyzed. If at least one constructor initializes the member
2833 /// with matching type of new, the return value is \c NoMismatch.
2834 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2835 /// \brief Analyzes a class member.
2836 /// \param Field Class member to analyze.
2837 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2838 /// for deleting the \p Field.
2839 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002840 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002841 /// List of mismatching new-expressions used for initialization of the pointee
2842 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2843 /// Indicates whether delete-expression was in array form.
2844 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002845
2846private:
2847 const bool EndOfTU;
2848 /// \brief Indicates that there is at least one constructor without body.
2849 bool HasUndefinedConstructors;
2850 /// \brief Returns \c CXXNewExpr from given initialization expression.
2851 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002852 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002853 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2854 /// \brief Returns whether member is initialized with mismatching form of
2855 /// \c new either by the member initializer or in-class initialization.
2856 ///
2857 /// If bodies of all constructors are not visible at the end of translation
2858 /// unit or at least one constructor initializes member with the matching
2859 /// form of \c new, mismatch cannot be proven, and this function will return
2860 /// \c NoMismatch.
2861 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2862 /// \brief Returns whether variable is initialized with mismatching form of
2863 /// \c new.
2864 ///
2865 /// If variable is initialized with matching form of \c new or variable is not
2866 /// initialized with a \c new expression, this function will return true.
2867 /// If variable is initialized with mismatching form of \c new, returns false.
2868 /// \param D Variable to analyze.
2869 bool hasMatchingVarInit(const DeclRefExpr *D);
2870 /// \brief Checks whether the constructor initializes pointee with mismatching
2871 /// form of \c new.
2872 ///
2873 /// Returns true, if member is initialized with matching form of \c new in
2874 /// member initializer list. Returns false, if member is initialized with the
2875 /// matching form of \c new in this constructor's initializer or given
2876 /// constructor isn't defined at the point where delete-expression is seen, or
2877 /// member isn't initialized by the constructor.
2878 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2879 /// \brief Checks whether member is initialized with matching form of
2880 /// \c new in member initializer list.
2881 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2882 /// Checks whether member is initialized with mismatching form of \c new by
2883 /// in-class initializer.
2884 MismatchResult analyzeInClassInitializer();
2885};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002886}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002887
2888MismatchingNewDeleteDetector::MismatchResult
2889MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2890 NewExprs.clear();
2891 assert(DE && "Expected delete-expression");
2892 IsArrayForm = DE->isArrayForm();
2893 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2894 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2895 return analyzeMemberExpr(ME);
2896 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2897 if (!hasMatchingVarInit(D))
2898 return VarInitMismatches;
2899 }
2900 return NoMismatch;
2901}
2902
2903const CXXNewExpr *
2904MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2905 assert(E != nullptr && "Expected a valid initializer expression");
2906 E = E->IgnoreParenImpCasts();
2907 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2908 if (ILE->getNumInits() == 1)
2909 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2910 }
2911
2912 return dyn_cast_or_null<const CXXNewExpr>(E);
2913}
2914
2915bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2916 const CXXCtorInitializer *CI) {
2917 const CXXNewExpr *NE = nullptr;
2918 if (Field == CI->getMember() &&
2919 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2920 if (NE->isArray() == IsArrayForm)
2921 return true;
2922 else
2923 NewExprs.push_back(NE);
2924 }
2925 return false;
2926}
2927
2928bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2929 const CXXConstructorDecl *CD) {
2930 if (CD->isImplicit())
2931 return false;
2932 const FunctionDecl *Definition = CD;
2933 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2934 HasUndefinedConstructors = true;
2935 return EndOfTU;
2936 }
2937 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2938 if (hasMatchingNewInCtorInit(CI))
2939 return true;
2940 }
2941 return false;
2942}
2943
2944MismatchingNewDeleteDetector::MismatchResult
2945MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2946 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002947 const Expr *InitExpr = Field->getInClassInitializer();
2948 if (!InitExpr)
2949 return EndOfTU ? NoMismatch : AnalyzeLater;
2950 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002951 if (NE->isArray() != IsArrayForm) {
2952 NewExprs.push_back(NE);
2953 return MemberInitMismatches;
2954 }
2955 }
2956 return NoMismatch;
2957}
2958
2959MismatchingNewDeleteDetector::MismatchResult
2960MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2961 bool DeleteWasArrayForm) {
2962 assert(Field != nullptr && "Analysis requires a valid class member.");
2963 this->Field = Field;
2964 IsArrayForm = DeleteWasArrayForm;
2965 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2966 for (const auto *CD : RD->ctors()) {
2967 if (hasMatchingNewInCtor(CD))
2968 return NoMismatch;
2969 }
2970 if (HasUndefinedConstructors)
2971 return EndOfTU ? NoMismatch : AnalyzeLater;
2972 if (!NewExprs.empty())
2973 return MemberInitMismatches;
2974 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2975 : NoMismatch;
2976}
2977
2978MismatchingNewDeleteDetector::MismatchResult
2979MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2980 assert(ME != nullptr && "Expected a member expression");
2981 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2982 return analyzeField(F, IsArrayForm);
2983 return NoMismatch;
2984}
2985
2986bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2987 const CXXNewExpr *NE = nullptr;
2988 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2989 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2990 NE->isArray() != IsArrayForm) {
2991 NewExprs.push_back(NE);
2992 }
2993 }
2994 return NewExprs.empty();
2995}
2996
2997static void
2998DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2999 const MismatchingNewDeleteDetector &Detector) {
3000 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3001 FixItHint H;
3002 if (!Detector.IsArrayForm)
3003 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3004 else {
3005 SourceLocation RSquare = Lexer::findLocationAfterToken(
3006 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3007 SemaRef.getLangOpts(), true);
3008 if (RSquare.isValid())
3009 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3010 }
3011 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3012 << Detector.IsArrayForm << H;
3013
3014 for (const auto *NE : Detector.NewExprs)
3015 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3016 << Detector.IsArrayForm;
3017}
3018
3019void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3020 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3021 return;
3022 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3023 switch (Detector.analyzeDeleteExpr(DE)) {
3024 case MismatchingNewDeleteDetector::VarInitMismatches:
3025 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3026 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3027 break;
3028 }
3029 case MismatchingNewDeleteDetector::AnalyzeLater: {
3030 DeleteExprs[Detector.Field].push_back(
3031 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3032 break;
3033 }
3034 case MismatchingNewDeleteDetector::NoMismatch:
3035 break;
3036 }
3037}
3038
3039void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3040 bool DeleteWasArrayForm) {
3041 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3042 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3043 case MismatchingNewDeleteDetector::VarInitMismatches:
3044 llvm_unreachable("This analysis should have been done for class members.");
3045 case MismatchingNewDeleteDetector::AnalyzeLater:
3046 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3047 "translation unit.");
3048 case MismatchingNewDeleteDetector::MemberInitMismatches:
3049 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3050 break;
3051 case MismatchingNewDeleteDetector::NoMismatch:
3052 break;
3053 }
3054}
3055
Sebastian Redlbd150f42008-11-21 19:14:01 +00003056/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3057/// @code ::delete ptr; @endcode
3058/// or
3059/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003060ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003061Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003062 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003063 // C++ [expr.delete]p1:
3064 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003065 // non-explicit conversion function to a pointer type. The result has type
3066 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003067 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003068 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3069
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003070 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003071 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003072 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003073 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003074
John Wiegley01296292011-04-08 18:41:53 +00003075 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003076 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003077 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003078 if (Ex.isInvalid())
3079 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003080
John Wiegley01296292011-04-08 18:41:53 +00003081 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003082
Richard Smithccc11812013-05-21 19:05:48 +00003083 class DeleteConverter : public ContextualImplicitConverter {
3084 public:
3085 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086
Craig Toppere14c0f82014-03-12 04:55:44 +00003087 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003088 // FIXME: If we have an operator T* and an operator void*, we must pick
3089 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003090 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003091 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003092 return true;
3093 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003094 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003095
Richard Smithccc11812013-05-21 19:05:48 +00003096 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003097 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003098 return S.Diag(Loc, diag::err_delete_operand) << T;
3099 }
3100
3101 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003102 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003103 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3104 }
3105
3106 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003107 QualType T,
3108 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003109 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3110 }
3111
3112 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003113 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003114 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3115 << ConvTy;
3116 }
3117
3118 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003119 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003120 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3121 }
3122
3123 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003124 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003125 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3126 << ConvTy;
3127 }
3128
3129 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003130 QualType T,
3131 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003132 llvm_unreachable("conversion functions are permitted");
3133 }
3134 } Converter;
3135
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003136 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003137 if (Ex.isInvalid())
3138 return ExprError();
3139 Type = Ex.get()->getType();
3140 if (!Converter.match(Type))
3141 // FIXME: PerformContextualImplicitConversion should return ExprError
3142 // itself in this case.
3143 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003144
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003145 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003146 QualType PointeeElem = Context.getBaseElementType(Pointee);
3147
Yaxun Liub34ec822017-04-11 17:24:23 +00003148 if (Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003149 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003150 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003151 << Pointee.getUnqualifiedType()
3152 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003153
Craig Topperc3ec1492014-05-26 06:22:03 +00003154 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003155 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003157 // effectively bans deletion of "void*". However, most compilers support
3158 // this, so we treat it as a warning unless we're in a SFINAE context.
3159 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003160 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003161 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003162 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003163 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003164 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003165 // FIXME: This can result in errors if the definition was imported from a
3166 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003167 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003168 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003169 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3170 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3171 }
3172 }
3173
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003174 if (Pointee->isArrayType() && !ArrayForm) {
3175 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003176 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003177 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003178 ArrayForm = true;
3179 }
3180
Anders Carlssona471db02009-08-16 20:29:29 +00003181 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3182 ArrayForm ? OO_Array_Delete : OO_Delete);
3183
Eli Friedmanae4280f2011-07-26 22:25:31 +00003184 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003186 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3187 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003188 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003189
John McCall284c48f2011-01-27 09:37:56 +00003190 // If we're allocating an array of records, check whether the
3191 // usual operator delete[] has a size_t parameter.
3192 if (ArrayForm) {
3193 // If the user specifically asked to use the global allocator,
3194 // we'll need to do the lookup into the class.
3195 if (UseGlobal)
3196 UsualArrayDeleteWantsSize =
3197 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3198
3199 // Otherwise, the usual operator delete[] should be the
3200 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003201 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003202 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003203 UsualDeallocFnInfo(*this,
3204 DeclAccessPair::make(OperatorDelete, AS_public))
3205 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003206 }
3207
Richard Smitheec915d62012-02-18 04:13:32 +00003208 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003209 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003210 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003211 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003212 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3213 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003214 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003215
Nico Weber5a9259c2016-01-15 21:45:31 +00003216 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3217 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3218 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3219 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221
Richard Smithb2f0f052016-10-10 18:54:32 +00003222 if (!OperatorDelete) {
3223 bool IsComplete = isCompleteType(StartLoc, Pointee);
3224 bool CanProvideSize =
3225 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3226 Pointee.isDestructedType());
3227 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3228
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003229 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003230 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3231 Overaligned, DeleteName);
3232 }
Mike Stump11289f42009-09-09 15:08:12 +00003233
Eli Friedmanfa0df832012-02-02 03:46:19 +00003234 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003235
Douglas Gregorfa778132011-02-01 15:50:11 +00003236 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003237 if (PointeeRD) {
3238 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003239 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003240 PDiag(diag::err_access_dtor) << PointeeElem);
3241 }
3242 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003243 }
3244
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003245 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003246 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3247 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003248 AnalyzeDeleteExprMismatch(Result);
3249 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003250}
3251
Nico Weber5a9259c2016-01-15 21:45:31 +00003252void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3253 bool IsDelete, bool CallCanBeVirtual,
3254 bool WarnOnNonAbstractTypes,
3255 SourceLocation DtorLoc) {
3256 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3257 return;
3258
3259 // C++ [expr.delete]p3:
3260 // In the first alternative (delete object), if the static type of the
3261 // object to be deleted is different from its dynamic type, the static
3262 // type shall be a base class of the dynamic type of the object to be
3263 // deleted and the static type shall have a virtual destructor or the
3264 // behavior is undefined.
3265 //
3266 const CXXRecordDecl *PointeeRD = dtor->getParent();
3267 // Note: a final class cannot be derived from, no issue there
3268 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3269 return;
3270
3271 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3272 if (PointeeRD->isAbstract()) {
3273 // If the class is abstract, we warn by default, because we're
3274 // sure the code has undefined behavior.
3275 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3276 << ClassType;
3277 } else if (WarnOnNonAbstractTypes) {
3278 // Otherwise, if this is not an array delete, it's a bit suspect,
3279 // but not necessarily wrong.
3280 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3281 << ClassType;
3282 }
3283 if (!IsDelete) {
3284 std::string TypeStr;
3285 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3286 Diag(DtorLoc, diag::note_delete_non_virtual)
3287 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3288 }
3289}
3290
Richard Smith03a4aa32016-06-23 19:02:52 +00003291Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3292 SourceLocation StmtLoc,
3293 ConditionKind CK) {
3294 ExprResult E =
3295 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3296 if (E.isInvalid())
3297 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003298 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3299 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003300}
3301
Douglas Gregor633caca2009-11-23 23:44:04 +00003302/// \brief Check the use of the given variable as a C++ condition in an if,
3303/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003304ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003305 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003306 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003307 if (ConditionVar->isInvalidDecl())
3308 return ExprError();
3309
Douglas Gregor633caca2009-11-23 23:44:04 +00003310 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003311
Douglas Gregor633caca2009-11-23 23:44:04 +00003312 // C++ [stmt.select]p2:
3313 // The declarator shall not specify a function or an array.
3314 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003316 diag::err_invalid_use_of_function_type)
3317 << ConditionVar->getSourceRange());
3318 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003320 diag::err_invalid_use_of_array_type)
3321 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003322
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003323 ExprResult Condition = DeclRefExpr::Create(
3324 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3325 /*enclosing*/ false, ConditionVar->getLocation(),
3326 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003327
Eli Friedmanfa0df832012-02-02 03:46:19 +00003328 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003329
Richard Smith03a4aa32016-06-23 19:02:52 +00003330 switch (CK) {
3331 case ConditionKind::Boolean:
3332 return CheckBooleanCondition(StmtLoc, Condition.get());
3333
Richard Smithb130fe72016-06-23 19:16:49 +00003334 case ConditionKind::ConstexprIf:
3335 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3336
Richard Smith03a4aa32016-06-23 19:02:52 +00003337 case ConditionKind::Switch:
3338 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340
Richard Smith03a4aa32016-06-23 19:02:52 +00003341 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003342}
3343
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003344/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003345ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003346 // C++ 6.4p4:
3347 // The value of a condition that is an initialized declaration in a statement
3348 // other than a switch statement is the value of the declared variable
3349 // implicitly converted to type bool. If that conversion is ill-formed, the
3350 // program is ill-formed.
3351 // The value of a condition that is an expression is the value of the
3352 // expression, implicitly converted to bool.
3353 //
Richard Smithb130fe72016-06-23 19:16:49 +00003354 // FIXME: Return this value to the caller so they don't need to recompute it.
3355 llvm::APSInt Value(/*BitWidth*/1);
3356 return (IsConstexpr && !CondExpr->isValueDependent())
3357 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3358 CCEK_ConstexprIf)
3359 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003360}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003361
3362/// Helper function to determine whether this is the (deprecated) C++
3363/// conversion from a string literal to a pointer to non-const char or
3364/// non-const wchar_t (for narrow and wide string literals,
3365/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003366bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003367Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3368 // Look inside the implicit cast, if it exists.
3369 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3370 From = Cast->getSubExpr();
3371
3372 // A string literal (2.13.4) that is not a wide string literal can
3373 // be converted to an rvalue of type "pointer to char"; a wide
3374 // string literal can be converted to an rvalue of type "pointer
3375 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003376 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003377 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003378 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003379 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003380 // This conversion is considered only when there is an
3381 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003382 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3383 switch (StrLit->getKind()) {
3384 case StringLiteral::UTF8:
3385 case StringLiteral::UTF16:
3386 case StringLiteral::UTF32:
3387 // We don't allow UTF literals to be implicitly converted
3388 break;
3389 case StringLiteral::Ascii:
3390 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3391 ToPointeeType->getKind() == BuiltinType::Char_S);
3392 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003393 return Context.typesAreCompatible(Context.getWideCharType(),
3394 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003395 }
3396 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003397 }
3398
3399 return false;
3400}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003401
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003403 SourceLocation CastLoc,
3404 QualType Ty,
3405 CastKind Kind,
3406 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003407 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003408 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003409 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003410 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003411 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003412 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003413 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003414 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415
Richard Smith72d74052013-07-20 19:41:36 +00003416 if (S.RequireNonAbstractType(CastLoc, Ty,
3417 diag::err_allocation_of_abstract_type))
3418 return ExprError();
3419
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003420 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003421 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422
Richard Smith5179eb72016-06-28 19:03:57 +00003423 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3424 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003425 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003426 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003427
Richard Smithf8adcdc2014-07-17 05:12:35 +00003428 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003429 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003430 ConstructorArgs, HadMultipleCandidates,
3431 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3432 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003433 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003434 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003436 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
John McCalle3027922010-08-25 11:45:40 +00003439 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003440 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441
Richard Smithd3f2d322015-02-24 21:16:19 +00003442 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003443 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003444 return ExprError();
3445
Douglas Gregora4253922010-04-16 22:17:36 +00003446 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003447 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3448 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003449 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003450 if (Result.isInvalid())
3451 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003452 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003453 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3454 CK_UserDefinedConversion, Result.get(),
3455 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregor668443e2011-01-20 00:18:04 +00003457 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003458 }
3459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460}
Douglas Gregora4253922010-04-16 22:17:36 +00003461
Douglas Gregor5fb53972009-01-14 15:45:31 +00003462/// PerformImplicitConversion - Perform an implicit conversion of the
3463/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003464/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003465/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003466/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003467ExprResult
3468Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003469 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003470 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003471 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003472 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003473 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003474 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3475 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003476 if (Res.isInvalid())
3477 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003478 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003479 break;
John Wiegley01296292011-04-08 18:41:53 +00003480 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003481
Anders Carlsson110b07b2009-09-15 06:28:28 +00003482 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003484 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003485 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003486 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003487 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003488 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003489 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Anders Carlsson110b07b2009-09-15 06:28:28 +00003491 // If the user-defined conversion is specified by a conversion function,
3492 // the initial standard conversion sequence converts the source type to
3493 // the implicit object parameter of the conversion function.
3494 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003495 } else {
3496 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003497 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003498 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003499 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003501 // initial standard conversion sequence converts the source type to
3502 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003503 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003505 }
Richard Smith72d74052013-07-20 19:41:36 +00003506 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003507 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003508 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003509 PerformImplicitConversion(From, BeforeToType,
3510 ICS.UserDefined.Before, AA_Converting,
3511 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003512 if (Res.isInvalid())
3513 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003514 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
3517 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003518 = BuildCXXCastArgument(*this,
3519 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003520 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003521 CastKind, cast<CXXMethodDecl>(FD),
3522 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003523 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003524 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003525
3526 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003527 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003528
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003529 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003530
Richard Smith507840d2011-11-29 22:48:16 +00003531 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3532 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003533 }
John McCall0d1da222010-01-12 00:44:57 +00003534
3535 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003536 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003537 PDiag(diag::err_typecheck_ambiguous_condition)
3538 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003539 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregor39c16d42008-10-24 04:54:22 +00003541 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003542 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003543
3544 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003545 bool Diagnosed =
3546 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3547 From->getType(), From, Action);
3548 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003549 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003550 }
3551
3552 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003553 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003554}
3555
Richard Smith507840d2011-11-29 22:48:16 +00003556/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003557/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003558/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003559/// expression. Flavor is the context in which we're performing this
3560/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003561ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003562Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003563 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003564 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003565 CheckedConversionKind CCK) {
3566 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003567
Mike Stump87c57ac2009-05-16 07:39:55 +00003568 // Overall FIXME: we are recomputing too many types here and doing far too
3569 // much extra work. What this means is that we need to keep track of more
3570 // information that is computed when we try the implicit conversion initially,
3571 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003572 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003573
Douglas Gregor2fe98832008-11-03 19:09:14 +00003574 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003575 // FIXME: When can ToType be a reference type?
3576 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003577 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003578 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003579 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003580 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003581 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003582 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003583 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003584 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3585 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003586 ConstructorArgs, /*HadMultipleCandidates*/ false,
3587 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3588 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003589 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003590 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003591 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3592 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003593 From, /*HadMultipleCandidates*/ false,
3594 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3595 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003596 }
3597
Douglas Gregor980fb162010-04-29 18:24:40 +00003598 // Resolve overloaded function references.
3599 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3600 DeclAccessPair Found;
3601 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3602 true, Found);
3603 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003604 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003605
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003606 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003607 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregor980fb162010-04-29 18:24:40 +00003609 From = FixOverloadedFunctionReference(From, Found, Fn);
3610 FromType = From->getType();
3611 }
3612
Richard Smitha23ab512013-05-23 00:30:41 +00003613 // If we're converting to an atomic type, first convert to the corresponding
3614 // non-atomic type.
3615 QualType ToAtomicType;
3616 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3617 ToAtomicType = ToType;
3618 ToType = ToAtomic->getValueType();
3619 }
3620
George Burgess IV8d141e02015-12-14 22:00:49 +00003621 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003622 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003623 switch (SCS.First) {
3624 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003625 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3626 FromType = FromAtomic->getValueType().getUnqualifiedType();
3627 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3628 From, /*BasePath=*/nullptr, VK_RValue);
3629 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003630 break;
3631
Eli Friedman946b7b52012-01-24 22:51:26 +00003632 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003633 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003634 ExprResult FromRes = DefaultLvalueConversion(From);
3635 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003636 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003637 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003638 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003639 }
John McCall34376a62010-12-04 03:47:34 +00003640
Douglas Gregor39c16d42008-10-24 04:54:22 +00003641 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003642 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003643 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003644 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003645 break;
3646
3647 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003648 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003649 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003650 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003651 break;
3652
3653 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003654 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003655 }
3656
Richard Smith507840d2011-11-29 22:48:16 +00003657 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003658 switch (SCS.Second) {
3659 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003660 // C++ [except.spec]p5:
3661 // [For] assignment to and initialization of pointers to functions,
3662 // pointers to member functions, and references to functions: the
3663 // target entity shall allow at least the exceptions allowed by the
3664 // source value in the assignment or initialization.
3665 switch (Action) {
3666 case AA_Assigning:
3667 case AA_Initializing:
3668 // Note, function argument passing and returning are initialization.
3669 case AA_Passing:
3670 case AA_Returning:
3671 case AA_Sending:
3672 case AA_Passing_CFAudited:
3673 if (CheckExceptionSpecCompatibility(From, ToType))
3674 return ExprError();
3675 break;
3676
3677 case AA_Casting:
3678 case AA_Converting:
3679 // Casts and implicit conversions are not initialization, so are not
3680 // checked for exception specification mismatches.
3681 break;
3682 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003683 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003684 break;
3685
3686 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003687 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003688 if (ToType->isBooleanType()) {
3689 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3690 SCS.Second == ICK_Integral_Promotion &&
3691 "only enums with fixed underlying type can promote to bool");
3692 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003693 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003694 } else {
3695 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003696 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003697 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003698 break;
3699
3700 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003701 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003702 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003703 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003704 break;
3705
3706 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003707 case ICK_Complex_Conversion: {
3708 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3709 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3710 CastKind CK;
3711 if (FromEl->isRealFloatingType()) {
3712 if (ToEl->isRealFloatingType())
3713 CK = CK_FloatingComplexCast;
3714 else
3715 CK = CK_FloatingComplexToIntegralComplex;
3716 } else if (ToEl->isRealFloatingType()) {
3717 CK = CK_IntegralComplexToFloatingComplex;
3718 } else {
3719 CK = CK_IntegralComplexCast;
3720 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003721 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003722 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003723 break;
John McCall8cb679e2010-11-15 09:13:47 +00003724 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003725
Douglas Gregor39c16d42008-10-24 04:54:22 +00003726 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003727 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003728 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003729 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003730 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003731 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003732 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003733 break;
3734
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003735 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003736 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003737 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003738 break;
3739
John McCall31168b02011-06-15 23:02:42 +00003740 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003741 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003742 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003743 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003744 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003745 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003746 diag::ext_typecheck_convert_incompatible_pointer)
3747 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003748 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003749 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003750 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003751 diag::ext_typecheck_convert_incompatible_pointer)
3752 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003753 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003754
Douglas Gregor33823722011-06-11 01:09:30 +00003755 if (From->getType()->isObjCObjectPointerType() &&
3756 ToType->isObjCObjectPointerType())
3757 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00003758 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3759 !CheckObjCARCUnavailableWeakConversion(ToType,
3760 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003761 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003762 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003763 diag::err_arc_weak_unavailable_assign);
3764 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003765 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003766 diag::err_arc_convesion_of_weak_unavailable)
3767 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003768 << From->getSourceRange();
3769 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003770
John McCall8cb679e2010-11-15 09:13:47 +00003771 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003772 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003773 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003774 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003775
3776 // Make sure we extend blocks if necessary.
3777 // FIXME: doing this here is really ugly.
3778 if (Kind == CK_BlockPointerToObjCPointerCast) {
3779 ExprResult E = From;
3780 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003781 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003782 }
Brian Kelley11352a82017-03-29 18:09:02 +00003783 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3784 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003785 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003786 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003787 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003790 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003791 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003792 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003793 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003794 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003795 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003796 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003797
3798 // We may not have been able to figure out what this member pointer resolved
3799 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003800 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003801 (void)isCompleteType(From->getExprLoc(), From->getType());
3802 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003803 }
David Majnemerd96b9972014-08-08 00:10:39 +00003804
Richard Smith507840d2011-11-29 22:48:16 +00003805 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003806 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003807 break;
3808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003810 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003811 // Perform half-to-boolean conversion via float.
3812 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003813 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003814 FromType = Context.FloatTy;
3815 }
3816
Richard Smith507840d2011-11-29 22:48:16 +00003817 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003818 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003819 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003820 break;
3821
Douglas Gregor88d292c2010-05-13 16:44:06 +00003822 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003823 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003825 ToType.getNonReferenceType(),
3826 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003827 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003828 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003829 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003830 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003831
Richard Smith507840d2011-11-29 22:48:16 +00003832 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3833 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003834 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003835 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003836 }
3837
Douglas Gregor46188682010-05-18 22:42:18 +00003838 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003839 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003840 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003841 break;
3842
George Burgess IVdf1ed002016-01-13 01:52:39 +00003843 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003844 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003845 Expr *Elem = prepareVectorSplat(ToType, From).get();
3846 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3847 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003848 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregor46188682010-05-18 22:42:18 +00003851 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003852 // Case 1. x -> _Complex y
3853 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3854 QualType ElType = ToComplex->getElementType();
3855 bool isFloatingComplex = ElType->isRealFloatingType();
3856
3857 // x -> y
3858 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3859 // do nothing
3860 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003861 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003862 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003863 } else {
3864 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003865 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003866 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003867 }
3868 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003869 From = ImpCastExprToType(From, ToType,
3870 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003871 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003872
3873 // Case 2. _Complex x -> y
3874 } else {
3875 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3876 assert(FromComplex);
3877
3878 QualType ElType = FromComplex->getElementType();
3879 bool isFloatingComplex = ElType->isRealFloatingType();
3880
3881 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003882 From = ImpCastExprToType(From, ElType,
3883 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003884 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003885 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003886
3887 // x -> y
3888 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3889 // do nothing
3890 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003891 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003892 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003893 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003894 } else {
3895 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003896 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003897 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003898 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003899 }
3900 }
Douglas Gregor46188682010-05-18 22:42:18 +00003901 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003902
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003903 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003904 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003905 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003906 break;
3907 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003908
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003909 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003910 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003911 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003912 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3913 if (FromRes.isInvalid())
3914 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003915 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003916 assert ((ConvTy == Sema::Compatible) &&
3917 "Improper transparent union conversion");
3918 (void)ConvTy;
3919 break;
3920 }
3921
Guy Benyei259f9f42013-02-07 16:05:33 +00003922 case ICK_Zero_Event_Conversion:
3923 From = ImpCastExprToType(From, ToType,
3924 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003925 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003926 break;
3927
Egor Churaev89831422016-12-23 14:55:49 +00003928 case ICK_Zero_Queue_Conversion:
3929 From = ImpCastExprToType(From, ToType,
3930 CK_ZeroToOCLQueue,
3931 From->getValueKind()).get();
3932 break;
3933
Douglas Gregor46188682010-05-18 22:42:18 +00003934 case ICK_Lvalue_To_Rvalue:
3935 case ICK_Array_To_Pointer:
3936 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003937 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003938 case ICK_Qualification:
3939 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003940 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003941 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003942 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003943 }
3944
3945 switch (SCS.Third) {
3946 case ICK_Identity:
3947 // Nothing to do.
3948 break;
3949
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003950 case ICK_Function_Conversion:
3951 // If both sides are functions (or pointers/references to them), there could
3952 // be incompatible exception declarations.
3953 if (CheckExceptionSpecCompatibility(From, ToType))
3954 return ExprError();
3955
3956 From = ImpCastExprToType(From, ToType, CK_NoOp,
3957 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3958 break;
3959
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003960 case ICK_Qualification: {
3961 // The qualification keeps the category of the inner expression, unless the
3962 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003963 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003964 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003965 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003966 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003967
Douglas Gregore981bb02011-03-14 16:13:32 +00003968 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003969 !getLangOpts().WritableStrings) {
3970 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3971 ? diag::ext_deprecated_string_literal_conversion
3972 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003973 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003974 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003975
Douglas Gregor39c16d42008-10-24 04:54:22 +00003976 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003977 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003978
Douglas Gregor39c16d42008-10-24 04:54:22 +00003979 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003980 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003981 }
3982
Douglas Gregor298f43d2012-04-12 20:42:30 +00003983 // If this conversion sequence involved a scalar -> atomic conversion, perform
3984 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003985 if (!ToAtomicType.isNull()) {
3986 assert(Context.hasSameType(
3987 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3988 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003989 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003990 }
3991
George Burgess IV8d141e02015-12-14 22:00:49 +00003992 // If this conversion sequence succeeded and involved implicitly converting a
3993 // _Nullable type to a _Nonnull one, complain.
3994 if (CCK == CCK_ImplicitConversion)
3995 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3996 From->getLocStart());
3997
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003998 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003999}
4000
Chandler Carruth8e172c62011-05-01 06:51:22 +00004001/// \brief Check the completeness of a type in a unary type trait.
4002///
4003/// If the particular type trait requires a complete type, tries to complete
4004/// it. If completing the type fails, a diagnostic is emitted and false
4005/// returned. If completing the type succeeds or no completion was required,
4006/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004007static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004008 SourceLocation Loc,
4009 QualType ArgTy) {
4010 // C++0x [meta.unary.prop]p3:
4011 // For all of the class templates X declared in this Clause, instantiating
4012 // that template with a template argument that is a class template
4013 // specialization may result in the implicit instantiation of the template
4014 // argument if and only if the semantics of X require that the argument
4015 // must be a complete type.
4016 // We apply this rule to all the type trait expressions used to implement
4017 // these class templates. We also try to follow any GCC documented behavior
4018 // in these expressions to ensure portability of standard libraries.
4019 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004020 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004021 // is_complete_type somewhat obviously cannot require a complete type.
4022 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004023 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004024
4025 // These traits are modeled on the type predicates in C++0x
4026 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4027 // requiring a complete type, as whether or not they return true cannot be
4028 // impacted by the completeness of the type.
4029 case UTT_IsVoid:
4030 case UTT_IsIntegral:
4031 case UTT_IsFloatingPoint:
4032 case UTT_IsArray:
4033 case UTT_IsPointer:
4034 case UTT_IsLvalueReference:
4035 case UTT_IsRvalueReference:
4036 case UTT_IsMemberFunctionPointer:
4037 case UTT_IsMemberObjectPointer:
4038 case UTT_IsEnum:
4039 case UTT_IsUnion:
4040 case UTT_IsClass:
4041 case UTT_IsFunction:
4042 case UTT_IsReference:
4043 case UTT_IsArithmetic:
4044 case UTT_IsFundamental:
4045 case UTT_IsObject:
4046 case UTT_IsScalar:
4047 case UTT_IsCompound:
4048 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004049 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004050
4051 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4052 // which requires some of its traits to have the complete type. However,
4053 // the completeness of the type cannot impact these traits' semantics, and
4054 // so they don't require it. This matches the comments on these traits in
4055 // Table 49.
4056 case UTT_IsConst:
4057 case UTT_IsVolatile:
4058 case UTT_IsSigned:
4059 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004060
4061 // This type trait always returns false, checking the type is moot.
4062 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004063 return true;
4064
David Majnemer213bea32015-11-16 06:58:51 +00004065 // C++14 [meta.unary.prop]:
4066 // If T is a non-union class type, T shall be a complete type.
4067 case UTT_IsEmpty:
4068 case UTT_IsPolymorphic:
4069 case UTT_IsAbstract:
4070 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4071 if (!RD->isUnion())
4072 return !S.RequireCompleteType(
4073 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4074 return true;
4075
4076 // C++14 [meta.unary.prop]:
4077 // If T is a class type, T shall be a complete type.
4078 case UTT_IsFinal:
4079 case UTT_IsSealed:
4080 if (ArgTy->getAsCXXRecordDecl())
4081 return !S.RequireCompleteType(
4082 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4083 return true;
4084
Richard Smithf03e9082017-06-01 00:28:16 +00004085 // C++1z [meta.unary.prop]:
4086 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004087 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004088 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004089 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004090 case UTT_IsStandardLayout:
4091 case UTT_IsPOD:
4092 case UTT_IsLiteral:
Richard Smithf03e9082017-06-01 00:28:16 +00004093 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4094 LLVM_FALLTHROUGH;
David Majnemer213bea32015-11-16 06:58:51 +00004095
Richard Smithf03e9082017-06-01 00:28:16 +00004096 // C++1z [meta.unary.prop]:
4097 // T shall be a complete type, cv void, or an array of unknown bound.
Alp Toker73287bf2014-01-20 00:24:09 +00004098 case UTT_IsDestructible:
4099 case UTT_IsNothrowDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004100 case UTT_IsTriviallyDestructible:
4101 // Per the GCC type traits documentation, the same constraints apply to these.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004102 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004103 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004104 case UTT_HasNothrowConstructor:
4105 case UTT_HasNothrowCopy:
4106 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004107 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004108 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004109 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004110 case UTT_HasTrivialCopy:
4111 case UTT_HasTrivialDestructor:
4112 case UTT_HasVirtualDestructor:
Richard Smithf03e9082017-06-01 00:28:16 +00004113 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004114 return true;
4115
4116 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004117 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004118 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004119}
4120
Joao Matosc9523d42013-03-27 01:34:16 +00004121static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4122 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004123 bool (CXXRecordDecl::*HasTrivial)() const,
4124 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004125 bool (CXXMethodDecl::*IsDesiredOp)() const)
4126{
4127 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4128 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4129 return true;
4130
4131 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4132 DeclarationNameInfo NameInfo(Name, KeyLoc);
4133 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4134 if (Self.LookupQualifiedName(Res, RD)) {
4135 bool FoundOperator = false;
4136 Res.suppressDiagnostics();
4137 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4138 Op != OpEnd; ++Op) {
4139 if (isa<FunctionTemplateDecl>(*Op))
4140 continue;
4141
4142 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4143 if((Operator->*IsDesiredOp)()) {
4144 FoundOperator = true;
4145 const FunctionProtoType *CPT =
4146 Operator->getType()->getAs<FunctionProtoType>();
4147 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004148 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004149 return false;
4150 }
4151 }
4152 return FoundOperator;
4153 }
4154 return false;
4155}
4156
Alp Toker95e7ff22014-01-01 05:57:51 +00004157static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004158 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004159 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004160
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004161 ASTContext &C = Self.Context;
4162 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004163 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004164 // Type trait expressions corresponding to the primary type category
4165 // predicates in C++0x [meta.unary.cat].
4166 case UTT_IsVoid:
4167 return T->isVoidType();
4168 case UTT_IsIntegral:
4169 return T->isIntegralType(C);
4170 case UTT_IsFloatingPoint:
4171 return T->isFloatingType();
4172 case UTT_IsArray:
4173 return T->isArrayType();
4174 case UTT_IsPointer:
4175 return T->isPointerType();
4176 case UTT_IsLvalueReference:
4177 return T->isLValueReferenceType();
4178 case UTT_IsRvalueReference:
4179 return T->isRValueReferenceType();
4180 case UTT_IsMemberFunctionPointer:
4181 return T->isMemberFunctionPointerType();
4182 case UTT_IsMemberObjectPointer:
4183 return T->isMemberDataPointerType();
4184 case UTT_IsEnum:
4185 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004186 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004187 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004188 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004189 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004190 case UTT_IsFunction:
4191 return T->isFunctionType();
4192
4193 // Type trait expressions which correspond to the convenient composition
4194 // predicates in C++0x [meta.unary.comp].
4195 case UTT_IsReference:
4196 return T->isReferenceType();
4197 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004198 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004199 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004200 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004201 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004202 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004203 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004204 // Note: semantic analysis depends on Objective-C lifetime types to be
4205 // considered scalar types. However, such types do not actually behave
4206 // like scalar types at run time (since they may require retain/release
4207 // operations), so we report them as non-scalar.
4208 if (T->isObjCLifetimeType()) {
4209 switch (T.getObjCLifetime()) {
4210 case Qualifiers::OCL_None:
4211 case Qualifiers::OCL_ExplicitNone:
4212 return true;
4213
4214 case Qualifiers::OCL_Strong:
4215 case Qualifiers::OCL_Weak:
4216 case Qualifiers::OCL_Autoreleasing:
4217 return false;
4218 }
4219 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004220
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004221 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004222 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004223 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004224 case UTT_IsMemberPointer:
4225 return T->isMemberPointerType();
4226
4227 // Type trait expressions which correspond to the type property predicates
4228 // in C++0x [meta.unary.prop].
4229 case UTT_IsConst:
4230 return T.isConstQualified();
4231 case UTT_IsVolatile:
4232 return T.isVolatileQualified();
4233 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004234 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004235 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004236 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004237 case UTT_IsStandardLayout:
4238 return T->isStandardLayoutType();
4239 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004240 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004241 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004242 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004243 case UTT_IsEmpty:
4244 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4245 return !RD->isUnion() && RD->isEmpty();
4246 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004247 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004248 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004249 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004250 return false;
4251 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004252 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004253 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004254 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004255 case UTT_IsAggregate:
4256 // Report vector extensions and complex types as aggregates because they
4257 // support aggregate initialization. GCC mirrors this behavior for vectors
4258 // but not _Complex.
4259 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4260 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004261 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4262 // even then only when it is used with the 'interface struct ...' syntax
4263 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004264 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004265 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004266 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004267 case UTT_IsSealed:
4268 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004269 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004270 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004271 case UTT_IsSigned:
4272 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004273 case UTT_IsUnsigned:
4274 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004275
4276 // Type trait expressions which query classes regarding their construction,
4277 // destruction, and copying. Rather than being based directly on the
4278 // related type predicates in the standard, they are specified by both
4279 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4280 // specifications.
4281 //
4282 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4283 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004284 //
4285 // Note that these builtins do not behave as documented in g++: if a class
4286 // has both a trivial and a non-trivial special member of a particular kind,
4287 // they return false! For now, we emulate this behavior.
4288 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4289 // does not correctly compute triviality in the presence of multiple special
4290 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004291 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004292 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4293 // If __is_pod (type) is true then the trait is true, else if type is
4294 // a cv class or union type (or array thereof) with a trivial default
4295 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004296 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004297 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004298 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4299 return RD->hasTrivialDefaultConstructor() &&
4300 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004301 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004302 case UTT_HasTrivialMoveConstructor:
4303 // This trait is implemented by MSVC 2012 and needed to parse the
4304 // standard library headers. Specifically this is used as the logic
4305 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004306 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004307 return true;
4308 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4309 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4310 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004311 case UTT_HasTrivialCopy:
4312 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4313 // If __is_pod (type) is true or type is a reference type then
4314 // the trait is true, else if type is a cv class or union type
4315 // with a trivial copy constructor ([class.copy]) then the trait
4316 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004317 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004318 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004319 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4320 return RD->hasTrivialCopyConstructor() &&
4321 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004322 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004323 case UTT_HasTrivialMoveAssign:
4324 // This trait is implemented by MSVC 2012 and needed to parse the
4325 // standard library headers. Specifically it is used as the logic
4326 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004327 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004328 return true;
4329 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4330 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4331 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004332 case UTT_HasTrivialAssign:
4333 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4334 // If type is const qualified or is a reference type then the
4335 // trait is false. Otherwise if __is_pod (type) is true then the
4336 // trait is true, else if type is a cv class or union type with
4337 // a trivial copy assignment ([class.copy]) then the trait is
4338 // true, else it is false.
4339 // Note: the const and reference restrictions are interesting,
4340 // given that const and reference members don't prevent a class
4341 // from having a trivial copy assignment operator (but do cause
4342 // errors if the copy assignment operator is actually used, q.v.
4343 // [class.copy]p12).
4344
Richard Smith92f241f2012-12-08 02:53:02 +00004345 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004346 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004347 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004348 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004349 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4350 return RD->hasTrivialCopyAssignment() &&
4351 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004352 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004353 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004354 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004355 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004356 // C++14 [meta.unary.prop]:
4357 // For reference types, is_destructible<T>::value is true.
4358 if (T->isReferenceType())
4359 return true;
4360
4361 // Objective-C++ ARC: autorelease types don't require destruction.
4362 if (T->isObjCLifetimeType() &&
4363 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4364 return true;
4365
4366 // C++14 [meta.unary.prop]:
4367 // For incomplete types and function types, is_destructible<T>::value is
4368 // false.
4369 if (T->isIncompleteType() || T->isFunctionType())
4370 return false;
4371
Richard Smithf03e9082017-06-01 00:28:16 +00004372 // A type that requires destruction (via a non-trivial destructor or ARC
4373 // lifetime semantics) is not trivially-destructible.
4374 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4375 return false;
4376
David Majnemerac73de92015-08-11 03:03:28 +00004377 // C++14 [meta.unary.prop]:
4378 // For object types and given U equal to remove_all_extents_t<T>, if the
4379 // expression std::declval<U&>().~U() is well-formed when treated as an
4380 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4381 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4382 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4383 if (!Destructor)
4384 return false;
4385 // C++14 [dcl.fct.def.delete]p2:
4386 // A program that refers to a deleted function implicitly or
4387 // explicitly, other than to declare it, is ill-formed.
4388 if (Destructor->isDeleted())
4389 return false;
4390 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4391 return false;
4392 if (UTT == UTT_IsNothrowDestructible) {
4393 const FunctionProtoType *CPT =
4394 Destructor->getType()->getAs<FunctionProtoType>();
4395 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4396 if (!CPT || !CPT->isNothrow(C))
4397 return false;
4398 }
4399 }
4400 return true;
4401
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004402 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004403 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004404 // If __is_pod (type) is true or type is a reference type
4405 // then the trait is true, else if type is a cv class or union
4406 // type (or array thereof) with a trivial destructor
4407 // ([class.dtor]) then the trait is true, else it is
4408 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004409 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004410 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004411
John McCall31168b02011-06-15 23:02:42 +00004412 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004413 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004414 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4415 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004416
Richard Smith92f241f2012-12-08 02:53:02 +00004417 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4418 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004419 return false;
4420 // TODO: Propagate nothrowness for implicitly declared special members.
4421 case UTT_HasNothrowAssign:
4422 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4423 // If type is const qualified or is a reference type then the
4424 // trait is false. Otherwise if __has_trivial_assign (type)
4425 // is true then the trait is true, else if type is a cv class
4426 // or union type with copy assignment operators that are known
4427 // not to throw an exception then the trait is true, else it is
4428 // false.
4429 if (C.getBaseElementType(T).isConstQualified())
4430 return false;
4431 if (T->isReferenceType())
4432 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004433 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004434 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004435
Joao Matosc9523d42013-03-27 01:34:16 +00004436 if (const RecordType *RT = T->getAs<RecordType>())
4437 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4438 &CXXRecordDecl::hasTrivialCopyAssignment,
4439 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4440 &CXXMethodDecl::isCopyAssignmentOperator);
4441 return false;
4442 case UTT_HasNothrowMoveAssign:
4443 // This trait is implemented by MSVC 2012 and needed to parse the
4444 // standard library headers. Specifically this is used as the logic
4445 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004446 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004447 return true;
4448
4449 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4450 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4451 &CXXRecordDecl::hasTrivialMoveAssignment,
4452 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4453 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004454 return false;
4455 case UTT_HasNothrowCopy:
4456 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4457 // If __has_trivial_copy (type) is true then the trait is true, else
4458 // if type is a cv class or union type with copy constructors that are
4459 // known not to throw an exception then the trait is true, else it is
4460 // false.
John McCall31168b02011-06-15 23:02:42 +00004461 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004462 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004463 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4464 if (RD->hasTrivialCopyConstructor() &&
4465 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004466 return true;
4467
4468 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004469 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004470 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004471 // A template constructor is never a copy constructor.
4472 // FIXME: However, it may actually be selected at the actual overload
4473 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004474 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004475 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004476 // UsingDecl itself is not a constructor
4477 if (isa<UsingDecl>(ND))
4478 continue;
4479 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004480 if (Constructor->isCopyConstructor(FoundTQs)) {
4481 FoundConstructor = true;
4482 const FunctionProtoType *CPT
4483 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004484 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4485 if (!CPT)
4486 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004487 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004488 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004489 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004490 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004491 }
4492 }
4493
Richard Smith938f40b2011-06-11 17:19:42 +00004494 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004495 }
4496 return false;
4497 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004498 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004499 // If __has_trivial_constructor (type) is true then the trait is
4500 // true, else if type is a cv class or union type (or array
4501 // thereof) with a default constructor that is known not to
4502 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004503 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004504 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004505 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4506 if (RD->hasTrivialDefaultConstructor() &&
4507 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004508 return true;
4509
Alp Tokerb4bca412014-01-20 00:23:47 +00004510 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004511 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004512 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004513 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004514 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004515 // UsingDecl itself is not a constructor
4516 if (isa<UsingDecl>(ND))
4517 continue;
4518 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004519 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004520 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004521 const FunctionProtoType *CPT
4522 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004523 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4524 if (!CPT)
4525 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004526 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004527 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004528 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004529 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004530 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004531 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004532 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004533 }
4534 return false;
4535 case UTT_HasVirtualDestructor:
4536 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4537 // If type is a class type with a virtual destructor ([class.dtor])
4538 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004539 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004540 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004541 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004542 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004543
4544 // These type trait expressions are modeled on the specifications for the
4545 // Embarcadero C++0x type trait functions:
4546 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4547 case UTT_IsCompleteType:
4548 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4549 // Returns True if and only if T is a complete type at the point of the
4550 // function call.
4551 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004552 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004553}
Sebastian Redl5822f082009-02-07 20:10:22 +00004554
Alp Tokercbb90342013-12-13 20:49:58 +00004555static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4556 QualType RhsT, SourceLocation KeyLoc);
4557
Douglas Gregor29c42f22012-02-24 07:38:34 +00004558static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4559 ArrayRef<TypeSourceInfo *> Args,
4560 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004561 if (Kind <= UTT_Last)
4562 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4563
Alp Tokercbb90342013-12-13 20:49:58 +00004564 if (Kind <= BTT_Last)
4565 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4566 Args[1]->getType(), RParenLoc);
4567
Douglas Gregor29c42f22012-02-24 07:38:34 +00004568 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004569 case clang::TT_IsConstructible:
4570 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004571 case clang::TT_IsTriviallyConstructible: {
4572 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004573 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004574 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004575 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004576 // definition for is_constructible, as defined below, is known to call
4577 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004578 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004579 // The predicate condition for a template specialization
4580 // is_constructible<T, Args...> shall be satisfied if and only if the
4581 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004582 // variable t:
4583 //
4584 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004585 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004586
4587 // Precondition: T and all types in the parameter pack Args shall be
4588 // complete types, (possibly cv-qualified) void, or arrays of
4589 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004590 for (const auto *TSI : Args) {
4591 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004592 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004593 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004594
Simon Pilgrim75c26882016-09-30 14:25:09 +00004595 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004596 diag::err_incomplete_type_used_in_type_trait_expr))
4597 return false;
4598 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004599
David Majnemer9658ecc2015-11-13 05:32:43 +00004600 // Make sure the first argument is not incomplete nor a function type.
4601 QualType T = Args[0]->getType();
4602 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004603 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004604
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004605 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004606 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004607 if (RD && RD->isAbstract())
4608 return false;
4609
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004610 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4611 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004612 ArgExprs.reserve(Args.size() - 1);
4613 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004614 QualType ArgTy = Args[I]->getType();
4615 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4616 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004617 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004618 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4619 ArgTy.getNonLValueExprType(S.Context),
4620 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004621 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004622 for (Expr &E : OpaqueArgExprs)
4623 ArgExprs.push_back(&E);
4624
Simon Pilgrim75c26882016-09-30 14:25:09 +00004625 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004626 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004627 EnterExpressionEvaluationContext Unevaluated(
4628 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004629 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4630 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4631 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4632 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4633 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004634 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004635 if (Init.Failed())
4636 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004637
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004638 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004639 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4640 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004641
Alp Toker73287bf2014-01-20 00:24:09 +00004642 if (Kind == clang::TT_IsConstructible)
4643 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004644
Alp Toker73287bf2014-01-20 00:24:09 +00004645 if (Kind == clang::TT_IsNothrowConstructible)
4646 return S.canThrow(Result.get()) == CT_Cannot;
4647
4648 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004649 // Under Objective-C ARC and Weak, if the destination has non-trivial
4650 // Objective-C lifetime, this is a non-trivial construction.
4651 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004652 return false;
4653
4654 // The initialization succeeded; now make sure there are no non-trivial
4655 // calls.
4656 return !Result.get()->hasNonTrivialCall(S.Context);
4657 }
4658
4659 llvm_unreachable("unhandled type trait");
4660 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004661 }
Alp Tokercbb90342013-12-13 20:49:58 +00004662 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004663 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004664
Douglas Gregor29c42f22012-02-24 07:38:34 +00004665 return false;
4666}
4667
Simon Pilgrim75c26882016-09-30 14:25:09 +00004668ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4669 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004670 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004671 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004672
Alp Toker95e7ff22014-01-01 05:57:51 +00004673 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4674 *this, Kind, KWLoc, Args[0]->getType()))
4675 return ExprError();
4676
Douglas Gregor29c42f22012-02-24 07:38:34 +00004677 bool Dependent = false;
4678 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4679 if (Args[I]->getType()->isDependentType()) {
4680 Dependent = true;
4681 break;
4682 }
4683 }
Alp Tokercbb90342013-12-13 20:49:58 +00004684
4685 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004686 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004687 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4688
4689 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4690 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004691}
4692
Alp Toker88f64e62013-12-13 21:19:30 +00004693ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4694 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004695 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004696 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004697 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004698
Douglas Gregor29c42f22012-02-24 07:38:34 +00004699 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4700 TypeSourceInfo *TInfo;
4701 QualType T = GetTypeFromParser(Args[I], &TInfo);
4702 if (!TInfo)
4703 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004704
4705 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004706 }
Alp Tokercbb90342013-12-13 20:49:58 +00004707
Douglas Gregor29c42f22012-02-24 07:38:34 +00004708 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4709}
4710
Alp Tokercbb90342013-12-13 20:49:58 +00004711static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4712 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004713 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4714 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004715
4716 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004717 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004718 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004719 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004720 // Base and Derived are not unions and name the same class type without
4721 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004722
John McCall388ef532011-01-28 22:02:36 +00004723 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004724 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004725 if (!rhsRecord || !lhsRecord) {
4726 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4727 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4728 if (!LHSObjTy || !RHSObjTy)
4729 return false;
4730
4731 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4732 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4733 if (!BaseInterface || !DerivedInterface)
4734 return false;
4735
4736 if (Self.RequireCompleteType(
4737 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4738 return false;
4739
4740 return BaseInterface->isSuperClassOf(DerivedInterface);
4741 }
John McCall388ef532011-01-28 22:02:36 +00004742
4743 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4744 == (lhsRecord == rhsRecord));
4745
4746 if (lhsRecord == rhsRecord)
4747 return !lhsRecord->getDecl()->isUnion();
4748
4749 // C++0x [meta.rel]p2:
4750 // If Base and Derived are class types and are different types
4751 // (ignoring possible cv-qualifiers) then Derived shall be a
4752 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004753 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004754 diag::err_incomplete_type_used_in_type_trait_expr))
4755 return false;
4756
4757 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4758 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4759 }
John Wiegley65497cc2011-04-27 23:09:49 +00004760 case BTT_IsSame:
4761 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004762 case BTT_TypeCompatible:
4763 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4764 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004765 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004766 case BTT_IsConvertibleTo: {
4767 // C++0x [meta.rel]p4:
4768 // Given the following function prototype:
4769 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004770 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004771 // typename add_rvalue_reference<T>::type create();
4772 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004773 // the predicate condition for a template specialization
4774 // is_convertible<From, To> shall be satisfied if and only if
4775 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004776 // well-formed, including any implicit conversions to the return
4777 // type of the function:
4778 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004779 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004780 // return create<From>();
4781 // }
4782 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004783 // Access checking is performed as if in a context unrelated to To and
4784 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004785 // of the return-statement (including conversions to the return type)
4786 // is considered.
4787 //
4788 // We model the initialization as a copy-initialization of a temporary
4789 // of the appropriate type, which for this expression is identical to the
4790 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004791
4792 // Functions aren't allowed to return function or array types.
4793 if (RhsT->isFunctionType() || RhsT->isArrayType())
4794 return false;
4795
4796 // A return statement in a void function must have void type.
4797 if (RhsT->isVoidType())
4798 return LhsT->isVoidType();
4799
4800 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004801 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004802 return false;
4803
4804 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004805 if (LhsT->isObjectType() || LhsT->isFunctionType())
4806 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004807
4808 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004809 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004810 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004811 Expr::getValueKindForType(LhsT));
4812 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004813 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004814 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004815
4816 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004817 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004818 EnterExpressionEvaluationContext Unevaluated(
4819 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004820 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4821 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004822 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004823 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004824 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004825
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004826 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004827 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4828 }
Alp Toker73287bf2014-01-20 00:24:09 +00004829
David Majnemerb3d96882016-05-23 17:21:55 +00004830 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004831 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004832 case BTT_IsTriviallyAssignable: {
4833 // C++11 [meta.unary.prop]p3:
4834 // is_trivially_assignable is defined as:
4835 // is_assignable<T, U>::value is true and the assignment, as defined by
4836 // is_assignable, is known to call no operation that is not trivial
4837 //
4838 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004839 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004840 // treated as an unevaluated operand (Clause 5).
4841 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004842 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004843 // void, or arrays of unknown bound.
4844 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004845 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004846 diag::err_incomplete_type_used_in_type_trait_expr))
4847 return false;
4848 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004849 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004850 diag::err_incomplete_type_used_in_type_trait_expr))
4851 return false;
4852
4853 // cv void is never assignable.
4854 if (LhsT->isVoidType() || RhsT->isVoidType())
4855 return false;
4856
Simon Pilgrim75c26882016-09-30 14:25:09 +00004857 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004858 // declval<U>().
4859 if (LhsT->isObjectType() || LhsT->isFunctionType())
4860 LhsT = Self.Context.getRValueReferenceType(LhsT);
4861 if (RhsT->isObjectType() || RhsT->isFunctionType())
4862 RhsT = Self.Context.getRValueReferenceType(RhsT);
4863 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4864 Expr::getValueKindForType(LhsT));
4865 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4866 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004867
4868 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004869 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004870 EnterExpressionEvaluationContext Unevaluated(
4871 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004872 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4873 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004874 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4875 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004876 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4877 return false;
4878
David Majnemerb3d96882016-05-23 17:21:55 +00004879 if (BTT == BTT_IsAssignable)
4880 return true;
4881
Alp Toker73287bf2014-01-20 00:24:09 +00004882 if (BTT == BTT_IsNothrowAssignable)
4883 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004884
Alp Toker73287bf2014-01-20 00:24:09 +00004885 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004886 // Under Objective-C ARC and Weak, if the destination has non-trivial
4887 // Objective-C lifetime, this is a non-trivial assignment.
4888 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004889 return false;
4890
4891 return !Result.get()->hasNonTrivialCall(Self.Context);
4892 }
4893
4894 llvm_unreachable("unhandled type trait");
4895 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004896 }
Alp Tokercbb90342013-12-13 20:49:58 +00004897 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004898 }
4899 llvm_unreachable("Unknown type trait or not implemented");
4900}
4901
John Wiegley6242b6a2011-04-28 00:16:57 +00004902ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4903 SourceLocation KWLoc,
4904 ParsedType Ty,
4905 Expr* DimExpr,
4906 SourceLocation RParen) {
4907 TypeSourceInfo *TSInfo;
4908 QualType T = GetTypeFromParser(Ty, &TSInfo);
4909 if (!TSInfo)
4910 TSInfo = Context.getTrivialTypeSourceInfo(T);
4911
4912 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4913}
4914
4915static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4916 QualType T, Expr *DimExpr,
4917 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004918 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004919
4920 switch(ATT) {
4921 case ATT_ArrayRank:
4922 if (T->isArrayType()) {
4923 unsigned Dim = 0;
4924 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4925 ++Dim;
4926 T = AT->getElementType();
4927 }
4928 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004929 }
John Wiegleyd3522222011-04-28 02:06:46 +00004930 return 0;
4931
John Wiegley6242b6a2011-04-28 00:16:57 +00004932 case ATT_ArrayExtent: {
4933 llvm::APSInt Value;
4934 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004935 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004936 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004937 false).isInvalid())
4938 return 0;
4939 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004940 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4941 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004942 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004943 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004944 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004945
4946 if (T->isArrayType()) {
4947 unsigned D = 0;
4948 bool Matched = false;
4949 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4950 if (Dim == D) {
4951 Matched = true;
4952 break;
4953 }
4954 ++D;
4955 T = AT->getElementType();
4956 }
4957
John Wiegleyd3522222011-04-28 02:06:46 +00004958 if (Matched && T->isArrayType()) {
4959 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4960 return CAT->getSize().getLimitedValue();
4961 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004962 }
John Wiegleyd3522222011-04-28 02:06:46 +00004963 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004964 }
4965 }
4966 llvm_unreachable("Unknown type trait or not implemented");
4967}
4968
4969ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4970 SourceLocation KWLoc,
4971 TypeSourceInfo *TSInfo,
4972 Expr* DimExpr,
4973 SourceLocation RParen) {
4974 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004975
Chandler Carruthc5276e52011-05-01 08:48:21 +00004976 // FIXME: This should likely be tracked as an APInt to remove any host
4977 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004978 uint64_t Value = 0;
4979 if (!T->isDependentType())
4980 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4981
Chandler Carruthc5276e52011-05-01 08:48:21 +00004982 // While the specification for these traits from the Embarcadero C++
4983 // compiler's documentation says the return type is 'unsigned int', Clang
4984 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4985 // compiler, there is no difference. On several other platforms this is an
4986 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004987 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4988 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004989}
4990
John Wiegleyf9f65842011-04-25 06:54:41 +00004991ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004992 SourceLocation KWLoc,
4993 Expr *Queried,
4994 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004995 // If error parsing the expression, ignore.
4996 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004997 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004998
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004999 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005000
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005001 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005002}
5003
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005004static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5005 switch (ET) {
5006 case ET_IsLValueExpr: return E->isLValue();
5007 case ET_IsRValueExpr: return E->isRValue();
5008 }
5009 llvm_unreachable("Expression trait not covered by switch");
5010}
5011
John Wiegleyf9f65842011-04-25 06:54:41 +00005012ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005013 SourceLocation KWLoc,
5014 Expr *Queried,
5015 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005016 if (Queried->isTypeDependent()) {
5017 // Delay type-checking for type-dependent expressions.
5018 } else if (Queried->getType()->isPlaceholderType()) {
5019 ExprResult PE = CheckPlaceholderExpr(Queried);
5020 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005021 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005022 }
5023
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005024 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005025
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005026 return new (Context)
5027 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005028}
5029
Richard Trieu82402a02011-09-15 21:56:47 +00005030QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005031 ExprValueKind &VK,
5032 SourceLocation Loc,
5033 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005034 assert(!LHS.get()->getType()->isPlaceholderType() &&
5035 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005036 "placeholders should have been weeded out by now");
5037
Richard Smith4baaa5a2016-12-03 01:14:32 +00005038 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5039 // temporary materialization conversion otherwise.
5040 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005041 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005042 else if (LHS.get()->isRValue())
5043 LHS = TemporaryMaterializationConversion(LHS.get());
5044 if (LHS.isInvalid())
5045 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005046
5047 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005048 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005049 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005050
Sebastian Redl5822f082009-02-07 20:10:22 +00005051 const char *OpSpelling = isIndirect ? "->*" : ".*";
5052 // C++ 5.5p2
5053 // The binary operator .* [p3: ->*] binds its second operand, which shall
5054 // be of type "pointer to member of T" (where T is a completely-defined
5055 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005056 QualType RHSType = RHS.get()->getType();
5057 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005058 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005059 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005060 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005061 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005062 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005063
Sebastian Redl5822f082009-02-07 20:10:22 +00005064 QualType Class(MemPtr->getClass(), 0);
5065
Douglas Gregord07ba342010-10-13 20:41:14 +00005066 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5067 // member pointer points must be completely-defined. However, there is no
5068 // reason for this semantic distinction, and the rule is not enforced by
5069 // other compilers. Therefore, we do not check this property, as it is
5070 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005071
Sebastian Redl5822f082009-02-07 20:10:22 +00005072 // C++ 5.5p2
5073 // [...] to its first operand, which shall be of class T or of a class of
5074 // which T is an unambiguous and accessible base class. [p3: a pointer to
5075 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005076 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005077 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005078 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5079 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005080 else {
5081 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005082 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005083 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005084 return QualType();
5085 }
5086 }
5087
Richard Trieu82402a02011-09-15 21:56:47 +00005088 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005089 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005090 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5091 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005092 return QualType();
5093 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005094
Richard Smith0f59cb32015-12-18 21:45:41 +00005095 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005096 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005097 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005098 return QualType();
5099 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005100
5101 CXXCastPath BasePath;
5102 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5103 SourceRange(LHS.get()->getLocStart(),
5104 RHS.get()->getLocEnd()),
5105 &BasePath))
5106 return QualType();
5107
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005108 // Cast LHS to type of use.
5109 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005110 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005111 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005112 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005113 }
5114
Richard Trieu82402a02011-09-15 21:56:47 +00005115 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005116 // Diagnose use of pointer-to-member type which when used as
5117 // the functional cast in a pointer-to-member expression.
5118 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5119 return QualType();
5120 }
John McCall7decc9e2010-11-18 06:31:45 +00005121
Sebastian Redl5822f082009-02-07 20:10:22 +00005122 // C++ 5.5p2
5123 // The result is an object or a function of the type specified by the
5124 // second operand.
5125 // The cv qualifiers are the union of those in the pointer and the left side,
5126 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005127 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005128 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005129
Douglas Gregor1d042092011-01-26 16:40:18 +00005130 // C++0x [expr.mptr.oper]p6:
5131 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132 // ill-formed if the second operand is a pointer to member function with
5133 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5134 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005135 // is a pointer to member function with ref-qualifier &&.
5136 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5137 switch (Proto->getRefQualifier()) {
5138 case RQ_None:
5139 // Do nothing
5140 break;
5141
5142 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005143 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005144 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005145 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005146 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005147
Douglas Gregor1d042092011-01-26 16:40:18 +00005148 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005149 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005150 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005151 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005152 break;
5153 }
5154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
John McCall7decc9e2010-11-18 06:31:45 +00005156 // C++ [expr.mptr.oper]p6:
5157 // The result of a .* expression whose second operand is a pointer
5158 // to a data member is of the same value category as its
5159 // first operand. The result of a .* expression whose second
5160 // operand is a pointer to a member function is a prvalue. The
5161 // result of an ->* expression is an lvalue if its second operand
5162 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005163 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005164 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005165 return Context.BoundMemberTy;
5166 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005167 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005168 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005169 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005170 }
John McCall7decc9e2010-11-18 06:31:45 +00005171
Sebastian Redl5822f082009-02-07 20:10:22 +00005172 return Result;
5173}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005174
Richard Smith2414bca2016-04-25 19:30:37 +00005175/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005176///
5177/// This is part of the parameter validation for the ? operator. If either
5178/// value operand is a class type, the two operands are attempted to be
5179/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005180/// It returns true if the program is ill-formed and has already been diagnosed
5181/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005182static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5183 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005184 bool &HaveConversion,
5185 QualType &ToType) {
5186 HaveConversion = false;
5187 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005188
5189 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005190 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005191 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005192 // The process for determining whether an operand expression E1 of type T1
5193 // can be converted to match an operand expression E2 of type T2 is defined
5194 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005195 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5196 // implicitly converted to type "lvalue reference to T2", subject to the
5197 // constraint that in the conversion the reference must bind directly to
5198 // an lvalue.
5199 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5200 // implicitly conveted to the type "rvalue reference to R2", subject to
5201 // the constraint that the reference must bind directly.
5202 if (To->isLValue() || To->isXValue()) {
5203 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5204 : Self.Context.getRValueReferenceType(ToType);
5205
Douglas Gregor838fcc32010-03-26 20:14:36 +00005206 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005208 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005209 if (InitSeq.isDirectReferenceBinding()) {
5210 ToType = T;
5211 HaveConversion = true;
5212 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005213 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005214
Douglas Gregor838fcc32010-03-26 20:14:36 +00005215 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005216 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005217 }
John McCall65eb8792010-02-25 01:37:24 +00005218
Sebastian Redl1a99f442009-04-16 17:51:27 +00005219 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5220 // -- if E1 and E2 have class type, and the underlying class types are
5221 // the same or one is a base class of the other:
5222 QualType FTy = From->getType();
5223 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005224 const RecordType *FRec = FTy->getAs<RecordType>();
5225 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005227 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5228 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5229 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005230 // E1 can be converted to match E2 if the class of T2 is the
5231 // same type as, or a base class of, the class of T1, and
5232 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005233 if (FRec == TRec || FDerivedFromT) {
5234 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005235 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005236 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005237 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005238 HaveConversion = true;
5239 return false;
5240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005241
Douglas Gregor838fcc32010-03-26 20:14:36 +00005242 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005243 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005244 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005246
Douglas Gregor838fcc32010-03-26 20:14:36 +00005247 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249
Douglas Gregor838fcc32010-03-26 20:14:36 +00005250 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5251 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005252 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005253 // an rvalue).
5254 //
5255 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5256 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005257 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005258
Douglas Gregor838fcc32010-03-26 20:14:36 +00005259 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005260 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005261 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005262 ToType = TTy;
5263 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005264 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005265
Sebastian Redl1a99f442009-04-16 17:51:27 +00005266 return false;
5267}
5268
5269/// \brief Try to find a common type for two according to C++0x 5.16p5.
5270///
5271/// This is part of the parameter validation for the ? operator. If either
5272/// value operand is a class type, overload resolution is used to find a
5273/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005274static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005275 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005276 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005277 OverloadCandidateSet CandidateSet(QuestionLoc,
5278 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005279 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005280 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005281
5282 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005283 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005284 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005285 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005286 ExprResult LHSRes = Self.PerformImplicitConversion(
5287 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5288 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005289 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005290 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005291 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005292
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005293 ExprResult RHSRes = Self.PerformImplicitConversion(
5294 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5295 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005296 if (RHSRes.isInvalid())
5297 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005298 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005299 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005300 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005301 return false;
John Wiegley01296292011-04-08 18:41:53 +00005302 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005303
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005304 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005305
5306 // Emit a better diagnostic if one of the expressions is a null pointer
5307 // constant and the other is a pointer type. In this case, the user most
5308 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005309 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005310 return true;
5311
5312 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005313 << LHS.get()->getType() << RHS.get()->getType()
5314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005315 return true;
5316
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005317 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005318 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005319 << LHS.get()->getType() << RHS.get()->getType()
5320 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005321 // FIXME: Print the possible common types by printing the return types of
5322 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005323 break;
5324
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005325 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005326 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 }
5328 return true;
5329}
5330
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005331/// \brief Perform an "extended" implicit conversion as returned by
5332/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005333static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005334 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005335 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005336 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005337 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005338 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005339 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005340 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005341 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005342
John Wiegley01296292011-04-08 18:41:53 +00005343 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005344 return false;
5345}
5346
Sebastian Redl1a99f442009-04-16 17:51:27 +00005347/// \brief Check the operands of ?: under C++ semantics.
5348///
5349/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5350/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005351QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5352 ExprResult &RHS, ExprValueKind &VK,
5353 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005354 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005355 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5356 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005357
Richard Smith45edb702012-08-07 22:06:48 +00005358 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005359 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005360 //
5361 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5362 // a is that of a integer vector with the same number of elements and
5363 // size as the vectors of b and c. If one of either b or c is a scalar
5364 // it is implicitly converted to match the type of the vector.
5365 // Otherwise the expression is ill-formed. If both b and c are scalars,
5366 // then b and c are checked and converted to the type of a if possible.
5367 // Unlike the OpenCL ?: operator, the expression is evaluated as
5368 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005369 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005370 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005371 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005372 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005373 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005374 }
5375
John McCall7decc9e2010-11-18 06:31:45 +00005376 // Assume r-value.
5377 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005378 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005379
Sebastian Redl1a99f442009-04-16 17:51:27 +00005380 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005381 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005382 return Context.DependentTy;
5383
Richard Smith45edb702012-08-07 22:06:48 +00005384 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005385 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005386 QualType LTy = LHS.get()->getType();
5387 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005388 bool LVoid = LTy->isVoidType();
5389 bool RVoid = RTy->isVoidType();
5390 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005391 // ... one of the following shall hold:
5392 // -- The second or the third operand (but not both) is a (possibly
5393 // parenthesized) throw-expression; the result is of the type
5394 // and value category of the other.
5395 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5396 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5397 if (LThrow != RThrow) {
5398 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5399 VK = NonThrow->getValueKind();
5400 // DR (no number yet): the result is a bit-field if the
5401 // non-throw-expression operand is a bit-field.
5402 OK = NonThrow->getObjectKind();
5403 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005404 }
5405
Sebastian Redl1a99f442009-04-16 17:51:27 +00005406 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005407 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005408 if (LVoid && RVoid)
5409 return Context.VoidTy;
5410
5411 // Neither holds, error.
5412 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5413 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005414 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005415 return QualType();
5416 }
5417
5418 // Neither is void.
5419
Richard Smithf2b084f2012-08-08 06:13:49 +00005420 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005421 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005422 // either has (cv) class type [...] an attempt is made to convert each of
5423 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005425 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005426 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005427 QualType L2RType, R2LType;
5428 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005429 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005430 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005431 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005432 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005433
Sebastian Redl1a99f442009-04-16 17:51:27 +00005434 // If both can be converted, [...] the program is ill-formed.
5435 if (HaveL2R && HaveR2L) {
5436 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005437 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005438 return QualType();
5439 }
5440
5441 // If exactly one conversion is possible, that conversion is applied to
5442 // the chosen operand and the converted operands are used in place of the
5443 // original operands for the remainder of this section.
5444 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005445 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005446 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005447 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005448 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005449 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005450 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005451 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005452 }
5453 }
5454
Richard Smithf2b084f2012-08-08 06:13:49 +00005455 // C++11 [expr.cond]p3
5456 // if both are glvalues of the same value category and the same type except
5457 // for cv-qualification, an attempt is made to convert each of those
5458 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005459 // FIXME:
5460 // Resolving a defect in P0012R1: we extend this to cover all cases where
5461 // one of the operands is reference-compatible with the other, in order
5462 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005463 ExprValueKind LVK = LHS.get()->getValueKind();
5464 ExprValueKind RVK = RHS.get()->getValueKind();
5465 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005466 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005467 // DerivedToBase was already handled by the class-specific case above.
5468 // FIXME: Should we allow ObjC conversions here?
5469 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5470 if (CompareReferenceRelationship(
5471 QuestionLoc, LTy, RTy, DerivedToBase,
5472 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005473 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5474 // [...] subject to the constraint that the reference must bind
5475 // directly [...]
5476 !RHS.get()->refersToBitField() &&
5477 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005478 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005479 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005480 } else if (CompareReferenceRelationship(
5481 QuestionLoc, RTy, LTy, DerivedToBase,
5482 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005483 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5484 !LHS.get()->refersToBitField() &&
5485 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005486 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5487 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005488 }
5489 }
5490
5491 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005492 // If the second and third operands are glvalues of the same value
5493 // category and have the same type, the result is of that type and
5494 // value category and it is a bit-field if the second or the third
5495 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005496 // We only extend this to bitfields, not to the crazy other kinds of
5497 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005498 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005499 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005500 LHS.get()->isOrdinaryOrBitFieldObject() &&
5501 RHS.get()->isOrdinaryOrBitFieldObject()) {
5502 VK = LHS.get()->getValueKind();
5503 if (LHS.get()->getObjectKind() == OK_BitField ||
5504 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005505 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005506
5507 // If we have function pointer types, unify them anyway to unify their
5508 // exception specifications, if any.
5509 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5510 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005511 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005512 /*ConvertArgs*/false);
5513 LTy = Context.getQualifiedType(LTy, Qs);
5514
5515 assert(!LTy.isNull() && "failed to find composite pointer type for "
5516 "canonically equivalent function ptr types");
5517 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5518 }
5519
John McCall7decc9e2010-11-18 06:31:45 +00005520 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005521 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005522
Richard Smithf2b084f2012-08-08 06:13:49 +00005523 // C++11 [expr.cond]p5
5524 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005525 // do not have the same type, and either has (cv) class type, ...
5526 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5527 // ... overload resolution is used to determine the conversions (if any)
5528 // to be applied to the operands. If the overload resolution fails, the
5529 // program is ill-formed.
5530 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5531 return QualType();
5532 }
5533
Richard Smithf2b084f2012-08-08 06:13:49 +00005534 // C++11 [expr.cond]p6
5535 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005536 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005537 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5538 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005539 if (LHS.isInvalid() || RHS.isInvalid())
5540 return QualType();
5541 LTy = LHS.get()->getType();
5542 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005543
5544 // After those conversions, one of the following shall hold:
5545 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005546 // is of that type. If the operands have class type, the result
5547 // is a prvalue temporary of the result type, which is
5548 // copy-initialized from either the second operand or the third
5549 // operand depending on the value of the first operand.
5550 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5551 if (LTy->isRecordType()) {
5552 // The operands have class type. Make a temporary copy.
5553 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005554
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5556 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005557 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005558 if (LHSCopy.isInvalid())
5559 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005560
5561 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5562 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005563 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005564 if (RHSCopy.isInvalid())
5565 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566
John Wiegley01296292011-04-08 18:41:53 +00005567 LHS = LHSCopy;
5568 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005569 }
5570
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005571 // If we have function pointer types, unify them anyway to unify their
5572 // exception specifications, if any.
5573 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5574 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5575 assert(!LTy.isNull() && "failed to find composite pointer type for "
5576 "canonically equivalent function ptr types");
5577 }
5578
Sebastian Redl1a99f442009-04-16 17:51:27 +00005579 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005580 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005581
Douglas Gregor46188682010-05-18 22:42:18 +00005582 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005583 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005584 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5585 /*AllowBothBool*/true,
5586 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005587
Sebastian Redl1a99f442009-04-16 17:51:27 +00005588 // -- The second and third operands have arithmetic or enumeration type;
5589 // the usual arithmetic conversions are performed to bring them to a
5590 // common type, and the result is of that type.
5591 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005592 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005593 if (LHS.isInvalid() || RHS.isInvalid())
5594 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005595 if (ResTy.isNull()) {
5596 Diag(QuestionLoc,
5597 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5599 return QualType();
5600 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005601
5602 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5603 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5604
5605 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005606 }
5607
5608 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005609 // type and the other is a null pointer constant, or both are null
5610 // pointer constants, at least one of which is non-integral; pointer
5611 // conversions and qualification conversions are performed to bring them
5612 // to their composite pointer type. The result is of the composite
5613 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005614 // -- The second and third operands have pointer to member type, or one has
5615 // pointer to member type and the other is a null pointer constant;
5616 // pointer to member conversions and qualification conversions are
5617 // performed to bring them to a common type, whose cv-qualification
5618 // shall match the cv-qualification of either the second or the third
5619 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005620 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5621 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005622 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Douglas Gregor697a3912010-04-01 22:47:07 +00005624 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005625 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5626 if (!Composite.isNull())
5627 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005628
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005629 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005630 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005631 return QualType();
5632
Sebastian Redl1a99f442009-04-16 17:51:27 +00005633 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005634 << LHS.get()->getType() << RHS.get()->getType()
5635 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005636 return QualType();
5637}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005638
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005639static FunctionProtoType::ExceptionSpecInfo
5640mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5641 FunctionProtoType::ExceptionSpecInfo ESI2,
5642 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5643 ExceptionSpecificationType EST1 = ESI1.Type;
5644 ExceptionSpecificationType EST2 = ESI2.Type;
5645
5646 // If either of them can throw anything, that is the result.
5647 if (EST1 == EST_None) return ESI1;
5648 if (EST2 == EST_None) return ESI2;
5649 if (EST1 == EST_MSAny) return ESI1;
5650 if (EST2 == EST_MSAny) return ESI2;
5651
5652 // If either of them is non-throwing, the result is the other.
5653 if (EST1 == EST_DynamicNone) return ESI2;
5654 if (EST2 == EST_DynamicNone) return ESI1;
5655 if (EST1 == EST_BasicNoexcept) return ESI2;
5656 if (EST2 == EST_BasicNoexcept) return ESI1;
5657
5658 // If either of them is a non-value-dependent computed noexcept, that
5659 // determines the result.
5660 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5661 !ESI2.NoexceptExpr->isValueDependent())
5662 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5663 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5664 !ESI1.NoexceptExpr->isValueDependent())
5665 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5666 // If we're left with value-dependent computed noexcept expressions, we're
5667 // stuck. Before C++17, we can just drop the exception specification entirely,
5668 // since it's not actually part of the canonical type. And this should never
5669 // happen in C++17, because it would mean we were computing the composite
5670 // pointer type of dependent types, which should never happen.
5671 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5672 assert(!S.getLangOpts().CPlusPlus1z &&
5673 "computing composite pointer type of dependent types");
5674 return FunctionProtoType::ExceptionSpecInfo();
5675 }
5676
5677 // Switch over the possibilities so that people adding new values know to
5678 // update this function.
5679 switch (EST1) {
5680 case EST_None:
5681 case EST_DynamicNone:
5682 case EST_MSAny:
5683 case EST_BasicNoexcept:
5684 case EST_ComputedNoexcept:
5685 llvm_unreachable("handled above");
5686
5687 case EST_Dynamic: {
5688 // This is the fun case: both exception specifications are dynamic. Form
5689 // the union of the two lists.
5690 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5691 llvm::SmallPtrSet<QualType, 8> Found;
5692 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5693 for (QualType E : Exceptions)
5694 if (Found.insert(S.Context.getCanonicalType(E)).second)
5695 ExceptionTypeStorage.push_back(E);
5696
5697 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5698 Result.Exceptions = ExceptionTypeStorage;
5699 return Result;
5700 }
5701
5702 case EST_Unevaluated:
5703 case EST_Uninstantiated:
5704 case EST_Unparsed:
5705 llvm_unreachable("shouldn't see unresolved exception specifications here");
5706 }
5707
5708 llvm_unreachable("invalid ExceptionSpecificationType");
5709}
5710
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005711/// \brief Find a merged pointer type and convert the two expressions to it.
5712///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005713/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005714/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005715/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005716/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005717///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005718/// \param Loc The location of the operator requiring these two expressions to
5719/// be converted to the composite pointer type.
5720///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005721/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005722QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005723 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005724 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005725 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005726
5727 // C++1z [expr]p14:
5728 // The composite pointer type of two operands p1 and p2 having types T1
5729 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005730 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005731
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005732 // where at least one is a pointer or pointer to member type or
5733 // std::nullptr_t is:
5734 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5735 T1->isNullPtrType();
5736 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5737 T2->isNullPtrType();
5738 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005739 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005740
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005741 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5742 // This can't actually happen, following the standard, but we also use this
5743 // to implement the end of [expr.conv], which hits this case.
5744 //
5745 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5746 if (T1IsPointerLike &&
5747 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005748 if (ConvertArgs)
5749 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5750 ? CK_NullToMemberPointer
5751 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005752 return T1;
5753 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005754 if (T2IsPointerLike &&
5755 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005756 if (ConvertArgs)
5757 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5758 ? CK_NullToMemberPointer
5759 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005760 return T2;
5761 }
Mike Stump11289f42009-09-09 15:08:12 +00005762
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005763 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005764 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005765 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005766 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5767 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005768
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005769 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5770 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5771 // the union of cv1 and cv2;
5772 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5773 // "pointer to function", where the function types are otherwise the same,
5774 // "pointer to function";
5775 // FIXME: This rule is defective: it should also permit removing noexcept
5776 // from a pointer to member function. As a Clang extension, we also
5777 // permit removing 'noreturn', so we generalize this rule to;
5778 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5779 // "pointer to member function" and the pointee types can be unified
5780 // by a function pointer conversion, that conversion is applied
5781 // before checking the following rules.
5782 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5783 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5784 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5785 // respectively;
5786 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5787 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5788 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5789 // T1 or the cv-combined type of T1 and T2, respectively;
5790 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5791 // T2;
5792 //
5793 // If looked at in the right way, these bullets all do the same thing.
5794 // What we do here is, we build the two possible cv-combined types, and try
5795 // the conversions in both directions. If only one works, or if the two
5796 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005797 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005798 //
5799 // Note that this will fail to find a composite pointer type for "pointer
5800 // to void" and "pointer to function". We can't actually perform the final
5801 // conversion in this case, even though a composite pointer type formally
5802 // exists.
5803 SmallVector<unsigned, 4> QualifierUnion;
5804 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005805 QualType Composite1 = T1;
5806 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005808 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005809 const PointerType *Ptr1, *Ptr2;
5810 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5811 (Ptr2 = Composite2->getAs<PointerType>())) {
5812 Composite1 = Ptr1->getPointeeType();
5813 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005814
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005815 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005816 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005817 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005818 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005819
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005820 QualifierUnion.push_back(
5821 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005822 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005823 continue;
5824 }
Mike Stump11289f42009-09-09 15:08:12 +00005825
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005826 const MemberPointerType *MemPtr1, *MemPtr2;
5827 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5828 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5829 Composite1 = MemPtr1->getPointeeType();
5830 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005831
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005832 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005833 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005834 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005835 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005836
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005837 QualifierUnion.push_back(
5838 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5839 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5840 MemPtr2->getClass()));
5841 continue;
5842 }
Mike Stump11289f42009-09-09 15:08:12 +00005843
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005844 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005845
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005846 // Cannot unwrap any more types.
5847 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005848 }
Mike Stump11289f42009-09-09 15:08:12 +00005849
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005850 // Apply the function pointer conversion to unify the types. We've already
5851 // unwrapped down to the function types, and we want to merge rather than
5852 // just convert, so do this ourselves rather than calling
5853 // IsFunctionConversion.
5854 //
5855 // FIXME: In order to match the standard wording as closely as possible, we
5856 // currently only do this under a single level of pointers. Ideally, we would
5857 // allow this in general, and set NeedConstBefore to the relevant depth on
5858 // the side(s) where we changed anything.
5859 if (QualifierUnion.size() == 1) {
5860 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5861 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5862 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5863 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5864
5865 // The result is noreturn if both operands are.
5866 bool Noreturn =
5867 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5868 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5869 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5870
5871 // The result is nothrow if both operands are.
5872 SmallVector<QualType, 8> ExceptionTypeStorage;
5873 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5874 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5875 ExceptionTypeStorage);
5876
5877 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5878 FPT1->getParamTypes(), EPI1);
5879 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5880 FPT2->getParamTypes(), EPI2);
5881 }
5882 }
5883 }
5884
Richard Smith5e9746f2016-10-21 22:00:42 +00005885 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005886 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005887 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005888 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005889 for (unsigned I = 0; I != NeedConstBefore; ++I)
5890 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005891 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005894 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005895 auto MOC = MemberOfClass.rbegin();
5896 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5897 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5898 auto Classes = *MOC++;
5899 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005900 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005901 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005902 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005903 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005904 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005905 } else {
5906 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005907 Composite1 =
5908 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5909 Composite2 =
5910 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005911 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005912 }
5913
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005914 struct Conversion {
5915 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005916 Expr *&E1, *&E2;
5917 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005918 InitializedEntity Entity;
5919 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005920 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005921 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005922
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005923 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5924 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005925 : S(S), E1(E1), E2(E2), Composite(Composite),
5926 Entity(InitializedEntity::InitializeTemporary(Composite)),
5927 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5928 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5929 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005930
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005931 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005932 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5933 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005934 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005935 E1 = E1Result.getAs<Expr>();
5936
5937 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5938 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005939 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005940 E2 = E2Result.getAs<Expr>();
5941
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005942 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005943 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005944 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005945
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005946 // Try to convert to each composite pointer type.
5947 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005948 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5949 if (ConvertArgs && C1.perform())
5950 return QualType();
5951 return C1.Composite;
5952 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005953 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005954
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005955 if (C1.Viable == C2.Viable) {
5956 // Either Composite1 and Composite2 are viable and are different, or
5957 // neither is viable.
5958 // FIXME: How both be viable and different?
5959 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005960 }
5961
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005962 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005963 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5964 return QualType();
5965
5966 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005967}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005968
John McCalldadc5752010-08-24 06:29:42 +00005969ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005970 if (!E)
5971 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972
John McCall31168b02011-06-15 23:02:42 +00005973 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5974
5975 // If the result is a glvalue, we shouldn't bind it.
5976 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005977 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005978
John McCall31168b02011-06-15 23:02:42 +00005979 // In ARC, calls that return a retainable type can return retained,
5980 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005981 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005982 E->getType()->isObjCRetainableType()) {
5983
5984 bool ReturnsRetained;
5985
5986 // For actual calls, we compute this by examining the type of the
5987 // called value.
5988 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5989 Expr *Callee = Call->getCallee()->IgnoreParens();
5990 QualType T = Callee->getType();
5991
5992 if (T == Context.BoundMemberTy) {
5993 // Handle pointer-to-members.
5994 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5995 T = BinOp->getRHS()->getType();
5996 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5997 T = Mem->getMemberDecl()->getType();
5998 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005999
John McCall31168b02011-06-15 23:02:42 +00006000 if (const PointerType *Ptr = T->getAs<PointerType>())
6001 T = Ptr->getPointeeType();
6002 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6003 T = Ptr->getPointeeType();
6004 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6005 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006006
John McCall31168b02011-06-15 23:02:42 +00006007 const FunctionType *FTy = T->getAs<FunctionType>();
6008 assert(FTy && "call to value not of function type?");
6009 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6010
6011 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6012 // type always produce a +1 object.
6013 } else if (isa<StmtExpr>(E)) {
6014 ReturnsRetained = true;
6015
Ted Kremeneke65b0862012-03-06 20:05:56 +00006016 // We hit this case with the lambda conversion-to-block optimization;
6017 // we don't want any extra casts here.
6018 } else if (isa<CastExpr>(E) &&
6019 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006020 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006021
John McCall31168b02011-06-15 23:02:42 +00006022 // For message sends and property references, we try to find an
6023 // actual method. FIXME: we should infer retention by selector in
6024 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006025 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006026 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006027 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6028 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006029 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6030 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006031 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006032 // Don't do reclaims if we're using the zero-element array
6033 // constant.
6034 if (ArrayLit->getNumElements() == 0 &&
6035 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6036 return E;
6037
Ted Kremeneke65b0862012-03-06 20:05:56 +00006038 D = ArrayLit->getArrayWithObjectsMethod();
6039 } else if (ObjCDictionaryLiteral *DictLit
6040 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006041 // Don't do reclaims if we're using the zero-element dictionary
6042 // constant.
6043 if (DictLit->getNumElements() == 0 &&
6044 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6045 return E;
6046
Ted Kremeneke65b0862012-03-06 20:05:56 +00006047 D = DictLit->getDictWithObjectsMethod();
6048 }
John McCall31168b02011-06-15 23:02:42 +00006049
6050 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006051
6052 // Don't do reclaims on performSelector calls; despite their
6053 // return type, the invoked method doesn't necessarily actually
6054 // return an object.
6055 if (!ReturnsRetained &&
6056 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006057 return E;
John McCall31168b02011-06-15 23:02:42 +00006058 }
6059
John McCall16de4d22011-11-14 19:53:16 +00006060 // Don't reclaim an object of Class type.
6061 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006062 return E;
John McCall16de4d22011-11-14 19:53:16 +00006063
Tim Shen4a05bb82016-06-21 20:29:17 +00006064 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006065
John McCall2d637d22011-09-10 06:18:15 +00006066 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6067 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006068 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6069 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006070 }
6071
David Blaikiebbafb8a2012-03-11 07:00:24 +00006072 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006073 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006074
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006075 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6076 // a fast path for the common case that the type is directly a RecordType.
6077 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006078 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006079 while (!RT) {
6080 switch (T->getTypeClass()) {
6081 case Type::Record:
6082 RT = cast<RecordType>(T);
6083 break;
6084 case Type::ConstantArray:
6085 case Type::IncompleteArray:
6086 case Type::VariableArray:
6087 case Type::DependentSizedArray:
6088 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6089 break;
6090 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006091 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006092 }
6093 }
Mike Stump11289f42009-09-09 15:08:12 +00006094
Richard Smithfd555f62012-02-22 02:04:18 +00006095 // That should be enough to guarantee that this type is complete, if we're
6096 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006097 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006098 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006099 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006100
6101 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006102 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006103
John McCall31168b02011-06-15 23:02:42 +00006104 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006105 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006106 CheckDestructorAccess(E->getExprLoc(), Destructor,
6107 PDiag(diag::err_access_dtor_temp)
6108 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006109 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6110 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006111
Richard Smithfd555f62012-02-22 02:04:18 +00006112 // If destructor is trivial, we can avoid the extra copy.
6113 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006114 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006115
John McCall28fc7092011-11-10 05:35:25 +00006116 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006117 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006118 }
Richard Smitheec915d62012-02-18 04:13:32 +00006119
6120 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006121 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6122
6123 if (IsDecltype)
6124 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6125
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006126 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006127}
6128
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129ExprResult
John McCall5d413782010-12-06 08:20:24 +00006130Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006131 if (SubExpr.isInvalid())
6132 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006133
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006134 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006135}
6136
John McCall28fc7092011-11-10 05:35:25 +00006137Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006138 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006139
Eli Friedman3bda6b12012-02-02 23:15:15 +00006140 CleanupVarDeclMarking();
6141
John McCall28fc7092011-11-10 05:35:25 +00006142 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6143 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006144 assert(Cleanup.exprNeedsCleanups() ||
6145 ExprCleanupObjects.size() == FirstCleanup);
6146 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006147 return SubExpr;
6148
Craig Topper5fc8fc22014-08-27 06:28:36 +00006149 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6150 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006151
Tim Shen4a05bb82016-06-21 20:29:17 +00006152 auto *E = ExprWithCleanups::Create(
6153 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006154 DiscardCleanupsInEvaluationContext();
6155
6156 return E;
6157}
6158
John McCall5d413782010-12-06 08:20:24 +00006159Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006160 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006161
Eli Friedman3bda6b12012-02-02 23:15:15 +00006162 CleanupVarDeclMarking();
6163
Tim Shen4a05bb82016-06-21 20:29:17 +00006164 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006165 return SubStmt;
6166
6167 // FIXME: In order to attach the temporaries, wrap the statement into
6168 // a StmtExpr; currently this is only used for asm statements.
6169 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6170 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006171 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006172 SourceLocation(),
6173 SourceLocation());
6174 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6175 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006176 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006177}
6178
Richard Smithfd555f62012-02-22 02:04:18 +00006179/// Process the expression contained within a decltype. For such expressions,
6180/// certain semantic checks on temporaries are delayed until this point, and
6181/// are omitted for the 'topmost' call in the decltype expression. If the
6182/// topmost call bound a temporary, strip that temporary off the expression.
6183ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006184 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006185
6186 // C++11 [expr.call]p11:
6187 // If a function call is a prvalue of object type,
6188 // -- if the function call is either
6189 // -- the operand of a decltype-specifier, or
6190 // -- the right operand of a comma operator that is the operand of a
6191 // decltype-specifier,
6192 // a temporary object is not introduced for the prvalue.
6193
6194 // Recursively rebuild ParenExprs and comma expressions to strip out the
6195 // outermost CXXBindTemporaryExpr, if any.
6196 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6197 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6198 if (SubExpr.isInvalid())
6199 return ExprError();
6200 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006201 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006202 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006203 }
6204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6205 if (BO->getOpcode() == BO_Comma) {
6206 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6207 if (RHS.isInvalid())
6208 return ExprError();
6209 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006210 return E;
6211 return new (Context) BinaryOperator(
6212 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006213 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006214 }
6215 }
6216
6217 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006218 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6219 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006220 if (TopCall)
6221 E = TopCall;
6222 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006223 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006224
6225 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006226 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006227
Richard Smithf86b0ae2012-07-28 19:54:11 +00006228 // In MS mode, don't perform any extra checking of call return types within a
6229 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006230 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006231 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006232
Richard Smithfd555f62012-02-22 02:04:18 +00006233 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006234 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6235 I != N; ++I) {
6236 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006237 if (Call == TopCall)
6238 continue;
6239
David Majnemerced8bdf2015-02-25 17:36:15 +00006240 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006241 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006242 Call, Call->getDirectCallee()))
6243 return ExprError();
6244 }
6245
6246 // Now all relevant types are complete, check the destructors are accessible
6247 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006248 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6249 I != N; ++I) {
6250 CXXBindTemporaryExpr *Bind =
6251 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006252 if (Bind == TopBind)
6253 continue;
6254
6255 CXXTemporary *Temp = Bind->getTemporary();
6256
6257 CXXRecordDecl *RD =
6258 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6259 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6260 Temp->setDestructor(Destructor);
6261
Richard Smith7d847b12012-05-11 22:20:10 +00006262 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6263 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006264 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006265 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006266 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6267 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006268
6269 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006270 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006271 }
6272
6273 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006274 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006275}
6276
Richard Smith79c927b2013-11-06 19:31:51 +00006277/// Note a set of 'operator->' functions that were used for a member access.
6278static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006279 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006280 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6281 // FIXME: Make this configurable?
6282 unsigned Limit = 9;
6283 if (OperatorArrows.size() > Limit) {
6284 // Produce Limit-1 normal notes and one 'skipping' note.
6285 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6286 SkipCount = OperatorArrows.size() - (Limit - 1);
6287 }
6288
6289 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6290 if (I == SkipStart) {
6291 S.Diag(OperatorArrows[I]->getLocation(),
6292 diag::note_operator_arrows_suppressed)
6293 << SkipCount;
6294 I += SkipCount;
6295 } else {
6296 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6297 << OperatorArrows[I]->getCallResultType();
6298 ++I;
6299 }
6300 }
6301}
6302
Nico Weber964d3322015-02-16 22:35:45 +00006303ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6304 SourceLocation OpLoc,
6305 tok::TokenKind OpKind,
6306 ParsedType &ObjectType,
6307 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006308 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006309 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006310 if (Result.isInvalid()) return ExprError();
6311 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006312
John McCall526ab472011-10-25 17:37:35 +00006313 Result = CheckPlaceholderExpr(Base);
6314 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006315 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006316
John McCallb268a282010-08-23 23:25:46 +00006317 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006318 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006319 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006320 // If we have a pointer to a dependent type and are using the -> operator,
6321 // the object type is the type that the pointer points to. We might still
6322 // have enough information about that type to do something useful.
6323 if (OpKind == tok::arrow)
6324 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6325 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006326
John McCallba7bf592010-08-24 05:47:05 +00006327 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006328 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006329 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006330 }
Mike Stump11289f42009-09-09 15:08:12 +00006331
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006332 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006333 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006334 // returned, with the original second operand.
6335 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006336 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006337 bool NoArrowOperatorFound = false;
6338 bool FirstIteration = true;
6339 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006340 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006341 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006342 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006343 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006344
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006345 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006346 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6347 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006348 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006349 noteOperatorArrows(*this, OperatorArrows);
6350 Diag(OpLoc, diag::note_operator_arrow_depth)
6351 << getLangOpts().ArrowDepth;
6352 return ExprError();
6353 }
6354
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006355 Result = BuildOverloadedArrowExpr(
6356 S, Base, OpLoc,
6357 // When in a template specialization and on the first loop iteration,
6358 // potentially give the default diagnostic (with the fixit in a
6359 // separate note) instead of having the error reported back to here
6360 // and giving a diagnostic with a fixit attached to the error itself.
6361 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006362 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006363 : &NoArrowOperatorFound);
6364 if (Result.isInvalid()) {
6365 if (NoArrowOperatorFound) {
6366 if (FirstIteration) {
6367 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006368 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006369 << FixItHint::CreateReplacement(OpLoc, ".");
6370 OpKind = tok::period;
6371 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006372 }
6373 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6374 << BaseType << Base->getSourceRange();
6375 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006376 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006377 Diag(CD->getLocStart(),
6378 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006379 }
6380 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006381 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006382 }
John McCallb268a282010-08-23 23:25:46 +00006383 Base = Result.get();
6384 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006385 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006386 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006387 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006388 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006389 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6390 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006391 return ExprError();
6392 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006393 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006394 }
Mike Stump11289f42009-09-09 15:08:12 +00006395
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006396 if (OpKind == tok::arrow &&
6397 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006398 BaseType = BaseType->getPointeeType();
6399 }
Mike Stump11289f42009-09-09 15:08:12 +00006400
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006401 // Objective-C properties allow "." access on Objective-C pointer types,
6402 // so adjust the base type to the object type itself.
6403 if (BaseType->isObjCObjectPointerType())
6404 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006405
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006406 // C++ [basic.lookup.classref]p2:
6407 // [...] If the type of the object expression is of pointer to scalar
6408 // type, the unqualified-id is looked up in the context of the complete
6409 // postfix-expression.
6410 //
6411 // This also indicates that we could be parsing a pseudo-destructor-name.
6412 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006413 // expressions or normal member (ivar or property) access expressions, and
6414 // it's legal for the type to be incomplete if this is a pseudo-destructor
6415 // call. We'll do more incomplete-type checks later in the lookup process,
6416 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006417 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006418 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006419 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006420 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006421 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006422 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006423 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006424 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006425 }
Mike Stump11289f42009-09-09 15:08:12 +00006426
Douglas Gregor3024f072012-04-16 07:05:22 +00006427 // The object type must be complete (or dependent), or
6428 // C++11 [expr.prim.general]p3:
6429 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006430 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006431 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006432 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006433 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006434 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006435 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006436
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006437 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006438 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006439 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006440 // type C (or of pointer to a class type C), the unqualified-id is looked
6441 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006442 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006443 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006444}
6445
Simon Pilgrim75c26882016-09-30 14:25:09 +00006446static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006447 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006448 if (Base->hasPlaceholderType()) {
6449 ExprResult result = S.CheckPlaceholderExpr(Base);
6450 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006451 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006452 }
6453 ObjectType = Base->getType();
6454
David Blaikie1d578782011-12-16 16:03:09 +00006455 // C++ [expr.pseudo]p2:
6456 // The left-hand side of the dot operator shall be of scalar type. The
6457 // left-hand side of the arrow operator shall be of pointer to scalar type.
6458 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006459 // Note that this is rather different from the normal handling for the
6460 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006461 if (OpKind == tok::arrow) {
6462 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6463 ObjectType = Ptr->getPointeeType();
6464 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006465 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006466 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6467 << ObjectType << true
6468 << FixItHint::CreateReplacement(OpLoc, ".");
6469 if (S.isSFINAEContext())
6470 return true;
6471
6472 OpKind = tok::period;
6473 }
6474 }
6475
6476 return false;
6477}
6478
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006479/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6480/// pointer objects.
6481static bool
6482canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6483 QualType DestructedType) {
6484 // If this is a record type, check if its destructor is callable.
6485 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6486 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6487 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6488 return false;
6489 }
6490
6491 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6492 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6493 DestructedType->isVectorType();
6494}
6495
John McCalldadc5752010-08-24 06:29:42 +00006496ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006497 SourceLocation OpLoc,
6498 tok::TokenKind OpKind,
6499 const CXXScopeSpec &SS,
6500 TypeSourceInfo *ScopeTypeInfo,
6501 SourceLocation CCLoc,
6502 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006503 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006504 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006505
Eli Friedman0ce4de42012-01-25 04:35:06 +00006506 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006507 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6508 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006509
Douglas Gregorc5c57342012-09-10 14:57:06 +00006510 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6511 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006512 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006513 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006514 else {
Nico Weber58829272012-01-23 05:50:57 +00006515 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6516 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006517 return ExprError();
6518 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006519 }
6520
6521 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006522 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006523 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006524 if (DestructedTypeInfo) {
6525 QualType DestructedType = DestructedTypeInfo->getType();
6526 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006527 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006528 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6529 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006530 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6531 // Foo *foo;
6532 // foo.~Foo();
6533 if (OpKind == tok::period && ObjectType->isPointerType() &&
6534 Context.hasSameUnqualifiedType(DestructedType,
6535 ObjectType->getPointeeType())) {
6536 auto Diagnostic =
6537 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6538 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006539
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006540 // Issue a fixit only when the destructor is valid.
6541 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6542 *this, DestructedType))
6543 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6544
6545 // Recover by setting the object type to the destructed type and the
6546 // operator to '->'.
6547 ObjectType = DestructedType;
6548 OpKind = tok::arrow;
6549 } else {
6550 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6551 << ObjectType << DestructedType << Base->getSourceRange()
6552 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6553
6554 // Recover by setting the destructed type to the object type.
6555 DestructedType = ObjectType;
6556 DestructedTypeInfo =
6557 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6558 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6559 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006560 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006561 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006562
John McCall31168b02011-06-15 23:02:42 +00006563 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6564 // Okay: just pretend that the user provided the correctly-qualified
6565 // type.
6566 } else {
6567 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6568 << ObjectType << DestructedType << Base->getSourceRange()
6569 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6570 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006571
John McCall31168b02011-06-15 23:02:42 +00006572 // Recover by setting the destructed type to the object type.
6573 DestructedType = ObjectType;
6574 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6575 DestructedTypeStart);
6576 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6577 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006578 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006580
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006581 // C++ [expr.pseudo]p2:
6582 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6583 // form
6584 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006585 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006586 //
6587 // shall designate the same scalar type.
6588 if (ScopeTypeInfo) {
6589 QualType ScopeType = ScopeTypeInfo->getType();
6590 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006591 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006593 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006594 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006595 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006596 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006598 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006599 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006600 }
6601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602
John McCallb268a282010-08-23 23:25:46 +00006603 Expr *Result
6604 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6605 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006606 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006607 ScopeTypeInfo,
6608 CCLoc,
6609 TildeLoc,
6610 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006611
David Majnemerced8bdf2015-02-25 17:36:15 +00006612 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006613}
6614
John McCalldadc5752010-08-24 06:29:42 +00006615ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006616 SourceLocation OpLoc,
6617 tok::TokenKind OpKind,
6618 CXXScopeSpec &SS,
6619 UnqualifiedId &FirstTypeName,
6620 SourceLocation CCLoc,
6621 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006622 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006623 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6624 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6625 "Invalid first type name in pseudo-destructor");
6626 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6627 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6628 "Invalid second type name in pseudo-destructor");
6629
Eli Friedman0ce4de42012-01-25 04:35:06 +00006630 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006631 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6632 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006633
6634 // Compute the object type that we should use for name lookup purposes. Only
6635 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006636 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006637 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006638 if (ObjectType->isRecordType())
6639 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006640 else if (ObjectType->isDependentType())
6641 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006643
6644 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006645 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006646 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006647 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006648 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006649 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006650 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006651 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006652 S, &SS, true, false, ObjectTypePtrForLookup,
6653 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006654 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006655 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6656 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006658 // couldn't find anything useful in scope. Just store the identifier and
6659 // it's location, and we'll perform (qualified) name lookup again at
6660 // template instantiation time.
6661 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6662 SecondTypeName.StartLocation);
6663 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006665 diag::err_pseudo_dtor_destructor_non_type)
6666 << SecondTypeName.Identifier << ObjectType;
6667 if (isSFINAEContext())
6668 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006670 // Recover by assuming we had the right type all along.
6671 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006672 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006673 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006674 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006675 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006676 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006677 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006678 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006679 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006680 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006681 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006682 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006683 TemplateId->TemplateNameLoc,
6684 TemplateId->LAngleLoc,
6685 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006686 TemplateId->RAngleLoc,
6687 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006688 if (T.isInvalid() || !T.get()) {
6689 // Recover by assuming we had the right type all along.
6690 DestructedType = ObjectType;
6691 } else
6692 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006693 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
6695 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006696 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006697 if (!DestructedType.isNull()) {
6698 if (!DestructedTypeInfo)
6699 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006700 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006701 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006704 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006705 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006706 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006708 FirstTypeName.Identifier) {
6709 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006710 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006711 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006712 S, &SS, true, false, ObjectTypePtrForLookup,
6713 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006714 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006716 diag::err_pseudo_dtor_destructor_non_type)
6717 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006718
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006719 if (isSFINAEContext())
6720 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006722 // Just drop this type. It's unnecessary anyway.
6723 ScopeType = QualType();
6724 } else
6725 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006726 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006727 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006728 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006729 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006730 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006731 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006732 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006733 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006734 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006735 TemplateId->TemplateNameLoc,
6736 TemplateId->LAngleLoc,
6737 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006738 TemplateId->RAngleLoc,
6739 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006740 if (T.isInvalid() || !T.get()) {
6741 // Recover by dropping this type.
6742 ScopeType = QualType();
6743 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006744 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006745 }
6746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006747
Douglas Gregor90ad9222010-02-24 23:02:30 +00006748 if (!ScopeType.isNull() && !ScopeTypeInfo)
6749 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6750 FirstTypeName.StartLocation);
6751
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752
John McCallb268a282010-08-23 23:25:46 +00006753 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006754 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006755 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006756}
6757
David Blaikie1d578782011-12-16 16:03:09 +00006758ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6759 SourceLocation OpLoc,
6760 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006761 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006762 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006763 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006764 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6765 return ExprError();
6766
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006767 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6768 false);
David Blaikie1d578782011-12-16 16:03:09 +00006769
6770 TypeLocBuilder TLB;
6771 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6772 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6773 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6774 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6775
6776 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006777 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006778 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006779}
6780
John Wiegley01296292011-04-08 18:41:53 +00006781ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006782 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006783 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006784 if (Method->getParent()->isLambda() &&
6785 Method->getConversionType()->isBlockPointerType()) {
6786 // This is a lambda coversion to block pointer; check if the argument
6787 // is a LambdaExpr.
6788 Expr *SubE = E;
6789 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6790 if (CE && CE->getCastKind() == CK_NoOp)
6791 SubE = CE->getSubExpr();
6792 SubE = SubE->IgnoreParens();
6793 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6794 SubE = BE->getSubExpr();
6795 if (isa<LambdaExpr>(SubE)) {
6796 // For the conversion to block pointer on a lambda expression, we
6797 // construct a special BlockLiteral instead; this doesn't really make
6798 // a difference in ARC, but outside of ARC the resulting block literal
6799 // follows the normal lifetime rules for block literals instead of being
6800 // autoreleased.
6801 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00006802 PushExpressionEvaluationContext(
6803 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006804 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6805 E->getExprLoc(),
6806 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006807 PopExpressionEvaluationContext();
6808
Eli Friedman98b01ed2012-03-01 04:01:32 +00006809 if (Exp.isInvalid())
6810 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6811 return Exp;
6812 }
6813 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006814
Craig Topperc3ec1492014-05-26 06:22:03 +00006815 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006816 FoundDecl, Method);
6817 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006818 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006819
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006820 MemberExpr *ME = new (Context) MemberExpr(
6821 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6822 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006823 if (HadMultipleCandidates)
6824 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006825 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006826
Alp Toker314cc812014-01-25 16:55:45 +00006827 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006828 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6829 ResultType = ResultType.getNonLValueExprType(Context);
6830
Douglas Gregor27381f32009-11-23 12:27:39 +00006831 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006832 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006833 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006834
6835 if (CheckFunctionCall(Method, CE,
6836 Method->getType()->castAs<FunctionProtoType>()))
6837 return ExprError();
6838
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006839 return CE;
6840}
6841
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006842ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6843 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006844 // If the operand is an unresolved lookup expression, the expression is ill-
6845 // formed per [over.over]p1, because overloaded function names cannot be used
6846 // without arguments except in explicit contexts.
6847 ExprResult R = CheckPlaceholderExpr(Operand);
6848 if (R.isInvalid())
6849 return R;
6850
6851 // The operand may have been modified when checking the placeholder type.
6852 Operand = R.get();
6853
Richard Smith51ec0cf2017-02-21 01:17:38 +00006854 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006855 // The expression operand for noexcept is in an unevaluated expression
6856 // context, so side effects could result in unintended consequences.
6857 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6858 }
6859
Richard Smithf623c962012-04-17 00:58:00 +00006860 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006861 return new (Context)
6862 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006863}
6864
6865ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6866 Expr *Operand, SourceLocation RParen) {
6867 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006868}
6869
Eli Friedmanf798f652012-05-24 22:04:19 +00006870static bool IsSpecialDiscardedValue(Expr *E) {
6871 // In C++11, discarded-value expressions of a certain form are special,
6872 // according to [expr]p10:
6873 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6874 // expression is an lvalue of volatile-qualified type and it has
6875 // one of the following forms:
6876 E = E->IgnoreParens();
6877
Eli Friedmanc49c2262012-05-24 22:36:31 +00006878 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006879 if (isa<DeclRefExpr>(E))
6880 return true;
6881
Eli Friedmanc49c2262012-05-24 22:36:31 +00006882 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006883 if (isa<ArraySubscriptExpr>(E))
6884 return true;
6885
Eli Friedmanc49c2262012-05-24 22:36:31 +00006886 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006887 if (isa<MemberExpr>(E))
6888 return true;
6889
Eli Friedmanc49c2262012-05-24 22:36:31 +00006890 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006891 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6892 if (UO->getOpcode() == UO_Deref)
6893 return true;
6894
6895 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006896 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006897 if (BO->isPtrMemOp())
6898 return true;
6899
Eli Friedmanc49c2262012-05-24 22:36:31 +00006900 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006901 if (BO->getOpcode() == BO_Comma)
6902 return IsSpecialDiscardedValue(BO->getRHS());
6903 }
6904
Eli Friedmanc49c2262012-05-24 22:36:31 +00006905 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006906 // operands are one of the above, or
6907 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6908 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6909 IsSpecialDiscardedValue(CO->getFalseExpr());
6910 // The related edge case of "*x ?: *x".
6911 if (BinaryConditionalOperator *BCO =
6912 dyn_cast<BinaryConditionalOperator>(E)) {
6913 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6914 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6915 IsSpecialDiscardedValue(BCO->getFalseExpr());
6916 }
6917
6918 // Objective-C++ extensions to the rule.
6919 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6920 return true;
6921
6922 return false;
6923}
6924
John McCall34376a62010-12-04 03:47:34 +00006925/// Perform the conversions required for an expression used in a
6926/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006927ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006928 if (E->hasPlaceholderType()) {
6929 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006930 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006931 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006932 }
6933
John McCallfee942d2010-12-02 02:07:15 +00006934 // C99 6.3.2.1:
6935 // [Except in specific positions,] an lvalue that does not have
6936 // array type is converted to the value stored in the
6937 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006938 if (E->isRValue()) {
6939 // In C, function designators (i.e. expressions of function type)
6940 // are r-values, but we still want to do function-to-pointer decay
6941 // on them. This is both technically correct and convenient for
6942 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006943 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006944 return DefaultFunctionArrayConversion(E);
6945
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006946 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006947 }
John McCallfee942d2010-12-02 02:07:15 +00006948
Eli Friedmanf798f652012-05-24 22:04:19 +00006949 if (getLangOpts().CPlusPlus) {
6950 // The C++11 standard defines the notion of a discarded-value expression;
6951 // normally, we don't need to do anything to handle it, but if it is a
6952 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6953 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006954 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006955 E->getType().isVolatileQualified() &&
6956 IsSpecialDiscardedValue(E)) {
6957 ExprResult Res = DefaultLvalueConversion(E);
6958 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006959 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006960 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006961 }
Richard Smith122f88d2016-12-06 23:52:28 +00006962
6963 // C++1z:
6964 // If the expression is a prvalue after this optional conversion, the
6965 // temporary materialization conversion is applied.
6966 //
6967 // We skip this step: IR generation is able to synthesize the storage for
6968 // itself in the aggregate case, and adding the extra node to the AST is
6969 // just clutter.
6970 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6971 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006972 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006973 }
John McCall34376a62010-12-04 03:47:34 +00006974
6975 // GCC seems to also exclude expressions of incomplete enum type.
6976 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6977 if (!T->getDecl()->isComplete()) {
6978 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006979 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006980 return E;
John McCall34376a62010-12-04 03:47:34 +00006981 }
6982 }
6983
John Wiegley01296292011-04-08 18:41:53 +00006984 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6985 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006986 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006987 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006988
John McCallca61b652010-12-04 12:29:11 +00006989 if (!E->getType()->isVoidType())
6990 RequireCompleteType(E->getExprLoc(), E->getType(),
6991 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006992 return E;
John McCall34376a62010-12-04 03:47:34 +00006993}
6994
Faisal Valia17d19f2013-11-07 05:17:06 +00006995// If we can unambiguously determine whether Var can never be used
6996// in a constant expression, return true.
6997// - if the variable and its initializer are non-dependent, then
6998// we can unambiguously check if the variable is a constant expression.
6999// - if the initializer is not value dependent - we can determine whether
7000// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007001// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007002// never be a constant expression.
7003// - FXIME: if the initializer is dependent, we can still do some analysis and
7004// identify certain cases unambiguously as non-const by using a Visitor:
7005// - such as those that involve odr-use of a ParmVarDecl, involve a new
7006// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007007static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007008 ASTContext &Context) {
7009 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007010 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007011
7012 // If there is no initializer - this can not be a constant expression.
7013 if (!Var->getAnyInitializer(DefVD)) return true;
7014 assert(DefVD);
7015 if (DefVD->isWeak()) return false;
7016 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007017
Faisal Valia17d19f2013-11-07 05:17:06 +00007018 Expr *Init = cast<Expr>(Eval->Value);
7019
7020 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007021 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7022 // of value-dependent expressions, and use it here to determine whether the
7023 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007024 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007025 }
7026
Simon Pilgrim75c26882016-09-30 14:25:09 +00007027 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007028}
7029
Simon Pilgrim75c26882016-09-30 14:25:09 +00007030/// \brief Check if the current lambda has any potential captures
7031/// that must be captured by any of its enclosing lambdas that are ready to
7032/// capture. If there is a lambda that can capture a nested
7033/// potential-capture, go ahead and do so. Also, check to see if any
7034/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007035/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007036
Faisal Valiab3d6462013-12-07 20:22:44 +00007037static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7038 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7039
Simon Pilgrim75c26882016-09-30 14:25:09 +00007040 assert(!S.isUnevaluatedContext());
7041 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007042#ifndef NDEBUG
7043 DeclContext *DC = S.CurContext;
7044 while (DC && isa<CapturedDecl>(DC))
7045 DC = DC->getParent();
7046 assert(
7047 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007048 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007049#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007050
7051 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7052
7053 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7054 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007055
Faisal Valiab3d6462013-12-07 20:22:44 +00007056 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007057 // lambda (within a generic outer lambda), must be captured by an
7058 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007059 const unsigned NumPotentialCaptures =
7060 CurrentLSI->getNumPotentialVariableCaptures();
7061 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007062 Expr *VarExpr = nullptr;
7063 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007064 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007065 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007066 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007067 // need to check enclosing lambda's for speculative captures.
7068 // For e.g.:
7069 // Even though 'x' is not odr-used, it should be captured.
7070 // int test() {
7071 // const int x = 10;
7072 // auto L = [=](auto a) {
7073 // (void) +x + a;
7074 // };
7075 // }
7076 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007077 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007078 continue;
7079
7080 // If we have a capture-capable lambda for the variable, go ahead and
7081 // capture the variable in that lambda (and all its enclosing lambdas).
7082 if (const Optional<unsigned> Index =
7083 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7084 FunctionScopesArrayRef, Var, S)) {
7085 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7086 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7087 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007088 }
7089 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007090 VariableCanNeverBeAConstantExpression(Var, S.Context);
7091 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7092 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007093 // can not be used in a constant expression - which means
7094 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007095 // capture violation early, if the variable is un-captureable.
7096 // This is purely for diagnosing errors early. Otherwise, this
7097 // error would get diagnosed when the lambda becomes capture ready.
7098 QualType CaptureType, DeclRefType;
7099 SourceLocation ExprLoc = VarExpr->getExprLoc();
7100 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007101 /*EllipsisLoc*/ SourceLocation(),
7102 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007103 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007104 // We will never be able to capture this variable, and we need
7105 // to be able to in any and all instantiations, so diagnose it.
7106 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007107 /*EllipsisLoc*/ SourceLocation(),
7108 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007109 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007110 }
7111 }
7112 }
7113
Faisal Valiab3d6462013-12-07 20:22:44 +00007114 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007115 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007116 // If we have a capture-capable lambda for 'this', go ahead and capture
7117 // 'this' in that lambda (and all its enclosing lambdas).
7118 if (const Optional<unsigned> Index =
7119 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007120 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007121 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7122 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7123 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7124 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007125 }
7126 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007127
7128 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007129 CurrentLSI->clearPotentialCaptures();
7130}
7131
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007132static ExprResult attemptRecovery(Sema &SemaRef,
7133 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007134 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007135 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7136 Consumer.getLookupResult().getLookupKind());
7137 const CXXScopeSpec *SS = Consumer.getSS();
7138 CXXScopeSpec NewSS;
7139
7140 // Use an approprate CXXScopeSpec for building the expr.
7141 if (auto *NNS = TC.getCorrectionSpecifier())
7142 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7143 else if (SS && !TC.WillReplaceSpecifier())
7144 NewSS = *SS;
7145
Richard Smithde6d6c42015-12-29 19:43:10 +00007146 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007147 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007148 R.addDecl(ND);
7149 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007150 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007151 CXXRecordDecl *Record = nullptr;
7152 if (auto *NNS = TC.getCorrectionSpecifier())
7153 Record = NNS->getAsType()->getAsCXXRecordDecl();
7154 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007155 Record =
7156 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7157 if (Record)
7158 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007159
7160 // Detect and handle the case where the decl might be an implicit
7161 // member.
7162 bool MightBeImplicitMember;
7163 if (!Consumer.isAddressOfOperand())
7164 MightBeImplicitMember = true;
7165 else if (!NewSS.isEmpty())
7166 MightBeImplicitMember = false;
7167 else if (R.isOverloadedResult())
7168 MightBeImplicitMember = false;
7169 else if (R.isUnresolvableResult())
7170 MightBeImplicitMember = true;
7171 else
7172 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7173 isa<IndirectFieldDecl>(ND) ||
7174 isa<MSPropertyDecl>(ND);
7175
7176 if (MightBeImplicitMember)
7177 return SemaRef.BuildPossibleImplicitMemberExpr(
7178 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007179 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007180 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7181 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7182 Ivar->getIdentifier());
7183 }
7184 }
7185
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007186 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7187 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007188}
7189
Kaelyn Takata6c759512014-10-27 18:07:37 +00007190namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007191class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7192 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7193
7194public:
7195 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7196 : TypoExprs(TypoExprs) {}
7197 bool VisitTypoExpr(TypoExpr *TE) {
7198 TypoExprs.insert(TE);
7199 return true;
7200 }
7201};
7202
Kaelyn Takata6c759512014-10-27 18:07:37 +00007203class TransformTypos : public TreeTransform<TransformTypos> {
7204 typedef TreeTransform<TransformTypos> BaseTransform;
7205
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007206 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7207 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007208 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007209 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007210 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007211 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007212
7213 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7214 /// If the TypoExprs were successfully corrected, then the diagnostics should
7215 /// suggest the corrections. Otherwise the diagnostics will not suggest
7216 /// anything (having been passed an empty TypoCorrection).
7217 void EmitAllDiagnostics() {
7218 for (auto E : TypoExprs) {
7219 TypoExpr *TE = cast<TypoExpr>(E);
7220 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007221 if (State.DiagHandler) {
7222 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7223 ExprResult Replacement = TransformCache[TE];
7224
7225 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7226 // TypoCorrection, replacing the existing decls. This ensures the right
7227 // NamedDecl is used in diagnostics e.g. in the case where overload
7228 // resolution was used to select one from several possible decls that
7229 // had been stored in the TypoCorrection.
7230 if (auto *ND = getDeclFromExpr(
7231 Replacement.isInvalid() ? nullptr : Replacement.get()))
7232 TC.setCorrectionDecl(ND);
7233
7234 State.DiagHandler(TC);
7235 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007236 SemaRef.clearDelayedTypo(TE);
7237 }
7238 }
7239
7240 /// \brief If corrections for the first TypoExpr have been exhausted for a
7241 /// given combination of the other TypoExprs, retry those corrections against
7242 /// the next combination of substitutions for the other TypoExprs by advancing
7243 /// to the next potential correction of the second TypoExpr. For the second
7244 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7245 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7246 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7247 /// TransformCache). Returns true if there is still any untried combinations
7248 /// of corrections.
7249 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7250 for (auto TE : TypoExprs) {
7251 auto &State = SemaRef.getTypoExprState(TE);
7252 TransformCache.erase(TE);
7253 if (!State.Consumer->finished())
7254 return true;
7255 State.Consumer->resetCorrectionStream();
7256 }
7257 return false;
7258 }
7259
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007260 NamedDecl *getDeclFromExpr(Expr *E) {
7261 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7262 E = OverloadResolution[OE];
7263
7264 if (!E)
7265 return nullptr;
7266 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007267 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007268 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007269 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007270 // FIXME: Add any other expr types that could be be seen by the delayed typo
7271 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007272 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007273 return nullptr;
7274 }
7275
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007276 ExprResult TryTransform(Expr *E) {
7277 Sema::SFINAETrap Trap(SemaRef);
7278 ExprResult Res = TransformExpr(E);
7279 if (Trap.hasErrorOccurred() || Res.isInvalid())
7280 return ExprError();
7281
7282 return ExprFilter(Res.get());
7283 }
7284
Kaelyn Takata6c759512014-10-27 18:07:37 +00007285public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007286 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7287 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007288
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007289 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7290 MultiExprArg Args,
7291 SourceLocation RParenLoc,
7292 Expr *ExecConfig = nullptr) {
7293 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7294 RParenLoc, ExecConfig);
7295 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007296 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007297 Expr *ResultCall = Result.get();
7298 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7299 ResultCall = BE->getSubExpr();
7300 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7301 OverloadResolution[OE] = CE->getCallee();
7302 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007303 }
7304 return Result;
7305 }
7306
Kaelyn Takata6c759512014-10-27 18:07:37 +00007307 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7308
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007309 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7310
Kaelyn Takata6c759512014-10-27 18:07:37 +00007311 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007312 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007313 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007314 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007315
Kaelyn Takata6c759512014-10-27 18:07:37 +00007316 // Exit if either the transform was valid or if there were no TypoExprs
7317 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007318 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007319 !CheckAndAdvanceTypoExprCorrectionStreams())
7320 break;
7321 }
7322
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007323 // Ensure none of the TypoExprs have multiple typo correction candidates
7324 // with the same edit length that pass all the checks and filters.
7325 // TODO: Properly handle various permutations of possible corrections when
7326 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007327 // Also, disable typo correction while attempting the transform when
7328 // handling potentially ambiguous typo corrections as any new TypoExprs will
7329 // have been introduced by the application of one of the correction
7330 // candidates and add little to no value if corrected.
7331 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007332 while (!AmbiguousTypoExprs.empty()) {
7333 auto TE = AmbiguousTypoExprs.back();
7334 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007335 auto &State = SemaRef.getTypoExprState(TE);
7336 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007337 TransformCache.erase(TE);
7338 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007339 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007340 TransformCache.erase(TE);
7341 Res = ExprError();
7342 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007343 }
7344 AmbiguousTypoExprs.remove(TE);
7345 State.Consumer->restoreSavedPosition();
7346 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007347 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007348 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007349
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007350 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007351 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007352 FindTypoExprs(TypoExprs).TraverseStmt(E);
7353
Kaelyn Takata6c759512014-10-27 18:07:37 +00007354 EmitAllDiagnostics();
7355
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007356 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007357 }
7358
7359 ExprResult TransformTypoExpr(TypoExpr *E) {
7360 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7361 // cached transformation result if there is one and the TypoExpr isn't the
7362 // first one that was encountered.
7363 auto &CacheEntry = TransformCache[E];
7364 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7365 return CacheEntry;
7366 }
7367
7368 auto &State = SemaRef.getTypoExprState(E);
7369 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7370
7371 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7372 // typo correction and return it.
7373 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007374 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007375 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007376 // FIXME: If we would typo-correct to an invalid declaration, it's
7377 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007378 ExprResult NE = State.RecoveryHandler ?
7379 State.RecoveryHandler(SemaRef, E, TC) :
7380 attemptRecovery(SemaRef, *State.Consumer, TC);
7381 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007382 // Check whether there may be a second viable correction with the same
7383 // edit distance; if so, remember this TypoExpr may have an ambiguous
7384 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007385 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007386 if ((Next = State.Consumer->peekNextCorrection()) &&
7387 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7388 AmbiguousTypoExprs.insert(E);
7389 } else {
7390 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007391 }
7392 assert(!NE.isUnset() &&
7393 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007394 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007395 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007396 }
7397 return CacheEntry = ExprError();
7398 }
7399};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007400}
Faisal Valia17d19f2013-11-07 05:17:06 +00007401
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007402ExprResult
7403Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7404 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007405 // If the current evaluation context indicates there are uncorrected typos
7406 // and the current expression isn't guaranteed to not have typos, try to
7407 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007408 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007409 (E->isTypeDependent() || E->isValueDependent() ||
7410 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007411 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7412 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7413 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007414 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007415 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007416 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007417 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007418 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007419 ExprEvalContexts.back().NumTypos -= TyposResolved;
7420 return Result;
7421 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007422 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007423 }
7424 return E;
7425}
7426
Richard Smith945f8d32013-01-14 22:39:08 +00007427ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007428 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007429 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007430 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007431 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007432
7433 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007434 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007435
7436 // If we are an init-expression in a lambdas init-capture, we should not
7437 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007438 // containing full-expression is done).
7439 // template<class ... Ts> void test(Ts ... t) {
7440 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7441 // return a;
7442 // }() ...);
7443 // }
7444 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7445 // when we parse the lambda introducer, and teach capturing (but not
7446 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7447 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7448 // lambda where we've entered the introducer but not the body, or represent a
7449 // lambda where we've entered the body, depending on where the
7450 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007451 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007452 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007453 return ExprError();
7454
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007455 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007456 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007457 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007458 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007459 if (FullExpr.isInvalid())
7460 return ExprError();
7461 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007462
Richard Smith945f8d32013-01-14 22:39:08 +00007463 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007464 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007465 if (FullExpr.isInvalid())
7466 return ExprError();
7467
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007468 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007469 if (FullExpr.isInvalid())
7470 return ExprError();
7471 }
John Wiegley01296292011-04-08 18:41:53 +00007472
Kaelyn Takata49d84322014-11-11 23:26:56 +00007473 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7474 if (FullExpr.isInvalid())
7475 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007476
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007477 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007478
Simon Pilgrim75c26882016-09-30 14:25:09 +00007479 // At the end of this full expression (which could be a deeply nested
7480 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007481 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007482 // Consider the following code:
7483 // void f(int, int);
7484 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007485 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007486 // const int x = 10, y = 20;
7487 // auto L = [=](auto a) {
7488 // auto M = [=](auto b) {
7489 // f(x, b); <-- requires x to be captured by L and M
7490 // f(y, a); <-- requires y to be captured by L, but not all Ms
7491 // };
7492 // };
7493 // }
7494
Simon Pilgrim75c26882016-09-30 14:25:09 +00007495 // FIXME: Also consider what happens for something like this that involves
7496 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007497 // void f() {
7498 // const int n = 0;
7499 // auto L = [&](auto a) {
7500 // +n + ({ 0; a; });
7501 // };
7502 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007503 //
7504 // Here, we see +n, and then the full-expression 0; ends, so we don't
7505 // capture n (and instead remove it from our list of potential captures),
7506 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007507 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007508
Alexey Bataev31939e32016-11-11 12:36:20 +00007509 LambdaScopeInfo *const CurrentLSI =
7510 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007511 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007512 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007513 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007514 // By ensuring we are in the context of a lambda's call operator
7515 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007516 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007517 // PR, a proper fix would entail :
7518 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007519 // - Add to Sema an integer holding the smallest (outermost) scope
7520 // index that we are *lexically* within, and save/restore/set to
7521 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007522 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007523 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007524 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007525 DeclContext *DC = CurContext;
7526 while (DC && isa<CapturedDecl>(DC))
7527 DC = DC->getParent();
7528 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007529 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007530 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007531 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7532 *this);
John McCall5d413782010-12-06 08:20:24 +00007533 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007534}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007535
7536StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7537 if (!FullStmt) return StmtError();
7538
John McCall5d413782010-12-06 08:20:24 +00007539 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007540}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007541
Simon Pilgrim75c26882016-09-30 14:25:09 +00007542Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007543Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7544 CXXScopeSpec &SS,
7545 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007546 DeclarationName TargetName = TargetNameInfo.getName();
7547 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007548 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007549
Douglas Gregor43edb322011-10-24 22:31:10 +00007550 // If the name itself is dependent, then the result is dependent.
7551 if (TargetName.isDependentName())
7552 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007553
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007554 // Do the redeclaration lookup in the current scope.
7555 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7556 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007557 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007558 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007559
Douglas Gregor43edb322011-10-24 22:31:10 +00007560 switch (R.getResultKind()) {
7561 case LookupResult::Found:
7562 case LookupResult::FoundOverloaded:
7563 case LookupResult::FoundUnresolvedValue:
7564 case LookupResult::Ambiguous:
7565 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007566
Douglas Gregor43edb322011-10-24 22:31:10 +00007567 case LookupResult::NotFound:
7568 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007569
Douglas Gregor43edb322011-10-24 22:31:10 +00007570 case LookupResult::NotFoundInCurrentInstantiation:
7571 return IER_Dependent;
7572 }
David Blaikie8a40f702012-01-17 06:56:22 +00007573
7574 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007575}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007576
Simon Pilgrim75c26882016-09-30 14:25:09 +00007577Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007578Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7579 bool IsIfExists, CXXScopeSpec &SS,
7580 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007581 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007582
Richard Smith151c4562016-12-20 21:35:28 +00007583 // Check for an unexpanded parameter pack.
7584 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7585 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7586 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007587 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007588
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007589 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7590}